Buckets:

download
raw
21.3 kB
"""
Notification Manager for Zen-AI-Pentest
Central manager for multi-channel notifications with:
- Rate limiting (per user, per channel)
- Retry logic with exponential backoff
- Jinja2 templating
- User preference management
- Event history tracking
"""
import asyncio
import logging
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
from jinja2 import Template
from sqlalchemy.orm import Session
from notifications.backends import (
DiscordBackend,
EmailBackend,
SlackBackend,
TelegramBackend,
WebhookBackend,
)
from notifications.models import (
NotificationHistory,
NotificationSettings,
NotificationTemplate,
)
logger = logging.getLogger(__name__)
class RateLimiter:
"""Simple in-memory rate limiter for notifications"""
def __init__(self, default_limit: int = 10, window_seconds: int = 60):
"""
Initialize rate limiter.
Args:
default_limit: Max requests per window
window_seconds: Time window in seconds
"""
self.default_limit = default_limit
self.window_seconds = window_seconds
self._requests: Dict[str, List[datetime]] = defaultdict(list)
self._lock = asyncio.Lock()
async def is_allowed(self, key: str, limit: Optional[int] = None) -> bool:
"""
Check if request is allowed under rate limit.
Args:
key: Rate limit key (e.g., "user_123_slack")
limit: Override default limit
Returns:
True if request is allowed
"""
async with self._lock:
now = datetime.now(timezone.utc)
window_start = now - timedelta(seconds=self.window_seconds)
# Clean old requests
self._requests[key] = [req_time for req_time in self._requests[key] if req_time > window_start]
# Check limit
max_requests = limit or self.default_limit
return len(self._requests[key]) < max_requests
async def record_request(self, key: str) -> None:
"""Record a request timestamp"""
async with self._lock:
self._requests[key].append(datetime.now(timezone.utc))
async def get_remaining(self, key: str, limit: Optional[int] = None) -> int:
"""Get remaining requests in current window"""
async with self._lock:
now = datetime.now(timezone.utc)
window_start = now - timedelta(seconds=self.window_seconds)
# Clean old requests
self._requests[key] = [req_time for req_time in self._requests[key] if req_time > window_start]
max_requests = limit or self.default_limit
return max(0, max_requests - len(self._requests[key]))
class NotificationManager:
"""
Central notification manager for all channels.
Features:
- Multi-channel support (Slack, Discord, Email, Telegram, Webhook)
- Rate limiting per user per channel
- Automatic retry with exponential backoff
- Jinja2 templating
- Event history tracking
"""
# Event types
EVENT_SCAN_STARTED = "scan_started"
EVENT_SCAN_COMPLETED = "scan_completed"
EVENT_CRITICAL_FINDING = "critical_finding"
EVENT_HIGH_SEVERITY_CVE = "high_severity_cve"
EVENT_SYSTEM_ALERT = "system_alert"
EVENT_REPORT_READY = "report_ready"
VALID_EVENTS = {
EVENT_SCAN_STARTED,
EVENT_SCAN_COMPLETED,
EVENT_CRITICAL_FINDING,
EVENT_HIGH_SEVERITY_CVE,
EVENT_SYSTEM_ALERT,
EVENT_REPORT_READY,
}
def __init__(
self,
db_session: Optional[Session] = None,
default_rate_limit: int = 10,
rate_limit_window: int = 60,
):
"""
Initialize notification manager.
Args:
db_session: SQLAlchemy session for database operations
default_rate_limit: Default max notifications per minute
rate_limit_window: Rate limit window in seconds
"""
self.db = db_session
self.rate_limiter = RateLimiter(default_rate_limit, rate_limit_window)
self._backends: Dict[str, Any] = {}
self._default_templates: Dict[str, Dict[str, str]] = self._init_default_templates()
def _init_default_templates(self) -> Dict[str, Dict[str, str]]:
"""Initialize default Jinja2 templates for each event type"""
return {
self.EVENT_SCAN_STARTED: {
"subject": "🔍 Scan Started: {{ target }}",
"body": """
Scan of {{ target }} has started.
Scan ID: {{ scan_id }}
Type: {{ scan_type }}
Started: {{ timestamp }}
""",
},
self.EVENT_SCAN_COMPLETED: {
"subject": "{% if critical_count > 0 %}🔴{% elif high_count > 0 %}🟠{% else %}🟢{% endif %} Scan Completed: {{ target }}",
"body": """
Scan of {{ target }} completed.
Status: {% if critical_count > 0 %}CRITICAL ISSUES{% elif high_count > 0 %}HIGH SEVERITY{% elif findings_count > 0 %}ISSUES FOUND{% else %}NO ISSUES{% endif %}
Findings: {{ findings_count }} (Critical: {{ critical_count }}, High: {{ high_count }})
Duration: {{ duration }}s
""",
},
self.EVENT_CRITICAL_FINDING: {
"subject": "🚨 CRITICAL: {{ title }}",
"body": """
Critical vulnerability found!
Target: {{ target }}
{% if cve %}CVE: {{ cve }}{% endif %}
{% if cvss %}CVSS: {{ cvss }}{% endif %}
Tool: {{ tool }}
{{ description[:500] }}
""",
},
self.EVENT_HIGH_SEVERITY_CVE: {
"subject": "⚠️ High Severity CVE: {{ cve }}",
"body": """
CVE: {{ cve }}
CVSS: {{ cvss }}
EPSS: {{ epss }}
Affected: {{ affected }}
{{ description[:500] }}
""",
},
self.EVENT_SYSTEM_ALERT: {
"subject": "🔔 System Alert: {{ title }}",
"body": """
Alert: {{ title }}
Component: {{ component }}
Severity: {{ alert_type }}
{{ message }}
""",
},
self.EVENT_REPORT_READY: {
"subject": "📊 Report Ready: {{ target }}",
"body": """
Your security report is ready!
Target: {{ target }}
Report ID: {{ report_id }}
Format: {{ format }}
Size: {{ size }}
""",
},
}
async def send_notification(
self,
user_id: int,
event_type: str,
data: Dict[str, Any],
channels: Optional[List[str]] = None,
force: bool = False,
) -> Dict[str, Any]:
"""
Send notification to user's configured channels.
Args:
user_id: User ID
event_type: Type of event
data: Event data
channels: Specific channels to use (None = use user preferences)
force: Skip rate limiting and preferences check
Returns:
Dict with results for each channel
"""
if event_type not in self.VALID_EVENTS:
return {
"success": False,
"error": f"Invalid event type: {event_type}",
}
# Get user settings
settings = self._get_user_settings(user_id)
if not settings:
return {
"success": False,
"error": "User notification settings not found",
}
# Check if user wants this notification type
if not force and not self._should_notify(settings, event_type):
return {
"success": True,
"message": "Notification skipped (user preferences)",
"channels": {},
}
# Determine channels to use
if not channels:
channels = self._get_enabled_channels(settings)
if not channels:
return {
"success": True,
"message": "No channels configured",
"channels": {},
}
# Add timestamp to data
data["timestamp"] = datetime.now(timezone.utc).isoformat()
# Send to each channel
results = {}
for channel in channels:
try:
result = await self._send_to_channel(channel, settings, event_type, data, force)
results[channel] = result
except Exception as e:
logger.error(f"Failed to send {channel} notification: {e}")
results[channel] = {"success": False, "error": str(e)}
return {
"success": any(r.get("success") for r in results.values()),
"channels": results,
}
async def _send_to_channel(
self,
channel: str,
settings: NotificationSettings,
event_type: str,
data: Dict[str, Any],
force: bool,
) -> Dict[str, Any]:
"""Send notification to specific channel"""
# Check rate limit
if not force:
rate_key = f"user_{settings.user_id}_{channel}"
is_allowed = await self.rate_limiter.is_allowed(rate_key, settings.rate_limit_per_minute)
if not is_allowed:
await self.rate_limiter.get_remaining(rate_key)
return {
"success": False,
"error": "Rate limit exceeded",
"retry_after": 60,
}
# Initialize backend
backend = self._get_backend(channel, settings)
if not backend:
return {
"success": False,
"error": f"Channel {channel} not configured",
}
# Get template data
template_data = await self._get_template(event_type, channel, settings.user_id, data)
# Send notification
try:
if channel == "email":
result = backend.send_event(
settings.email_address,
event_type,
data,
template_data,
)
else:
result = backend.send_event(event_type, data, template_data)
# Record rate limit
if not force:
await self.rate_limiter.record_request(rate_key)
# Save to history
self._save_history(
user_id=settings.user_id,
channel=channel,
event_type=event_type,
status="sent" if result.get("success") else "failed",
title=data.get("title", event_type),
message=str(data),
response_status=str(result.get("status_code", result.get("error", ""))),
)
return result
except Exception as e:
self._save_history(
user_id=settings.user_id,
channel=channel,
event_type=event_type,
status="failed",
title=data.get("title", event_type),
message=str(data),
error_message=str(e),
)
return {"success": False, "error": str(e)}
def _get_user_settings(self, user_id: int) -> Optional[NotificationSettings]:
"""Get notification settings for user"""
if not self.db:
return None
return self.db.query(NotificationSettings).filter(NotificationSettings.user_id == user_id).first()
def _should_notify(self, settings: NotificationSettings, event_type: str) -> bool:
"""Check if user wants notifications for this event type"""
event_checks = {
self.EVENT_SCAN_STARTED: settings.notify_on_scan_start,
self.EVENT_SCAN_COMPLETED: settings.notify_on_scan_complete,
self.EVENT_CRITICAL_FINDING: settings.notify_on_critical,
self.EVENT_HIGH_SEVERITY_CVE: settings.notify_on_high,
self.EVENT_SYSTEM_ALERT: settings.notify_on_system_alert,
self.EVENT_REPORT_READY: settings.notify_on_report_ready,
}
return event_checks.get(event_type, True)
def _get_enabled_channels(self, settings: NotificationSettings) -> List[str]:
"""Get list of enabled channels"""
channels = []
if settings.slack_enabled and settings.slack_webhook_url:
channels.append("slack")
if settings.discord_enabled and settings.discord_webhook_url:
channels.append("discord")
if settings.email_enabled and settings.email_address:
channels.append("email")
if settings.telegram_enabled and settings.telegram_bot_token:
channels.append("telegram")
if settings.webhook_enabled and settings.webhook_url:
channels.append("webhook")
return channels
def _get_backend(self, channel: str, settings: NotificationSettings) -> Optional[Any]:
"""Get or create backend for channel"""
cache_key = f"{channel}_{settings.user_id}"
if cache_key in self._backends:
return self._backends[cache_key]
backend = None
try:
if channel == "slack" and settings.slack_webhook_url:
backend = SlackBackend(
settings.slack_webhook_url,
channel=settings.slack_channel,
)
elif channel == "discord" and settings.discord_webhook_url:
backend = DiscordBackend(settings.discord_webhook_url)
elif channel == "email" and settings.email_address:
backend = EmailBackend.from_env()
elif channel == "telegram" and settings.telegram_bot_token:
backend = TelegramBackend(
settings.telegram_bot_token,
settings.telegram_chat_id,
)
elif channel == "webhook" and settings.webhook_url:
backend = WebhookBackend(
settings.webhook_url,
headers=settings.webhook_headers or {},
)
except Exception as e:
logger.error(f"Failed to initialize {channel} backend: {e}")
return None
if backend:
self._backends[cache_key] = backend
return backend
async def _get_template(
self,
event_type: str,
channel: str,
user_id: int,
data: Dict[str, Any],
) -> Optional[Dict[str, Any]]:
"""Get rendered template for event"""
if not self.db:
return None
# Try to get custom template from database
template = (
self.db.query(NotificationTemplate)
.filter(
NotificationTemplate.event_type == event_type,
NotificationTemplate.channel.in_([channel, "all"]),
NotificationTemplate.is_enabled,
)
.filter((NotificationTemplate.user_id == user_id) | (NotificationTemplate.user_id is None)) # Global templates
.order_by(NotificationTemplate.user_id.desc()) # User templates first
.first()
)
if template:
try:
body_template = Template(template.body_template)
body = body_template.render(**data)
result = {"message": body}
if template.subject_template:
subject_template = Template(template.subject_template)
result["subject"] = subject_template.render(**data)
if template.color:
result["color"] = template.color
return result
except Exception as e:
logger.warning(f"Template rendering failed: {e}")
# Fall back to default templates
default = self._default_templates.get(event_type, {})
if default:
try:
body_template = Template(default.get("body", ""))
body = body_template.render(**data)
result = {"message": body}
if "subject" in default:
subject_template = Template(default["subject"])
result["subject"] = subject_template.render(**data)
return result
except Exception as e:
logger.warning(f"Default template rendering failed: {e}")
return None
def _save_history(
self,
user_id: int,
channel: str,
event_type: str,
status: str,
title: str,
message: str,
response_status: str = "",
error_message: str = "",
) -> None:
"""Save notification to history"""
if not self.db:
return
try:
history = NotificationHistory(
user_id=user_id,
channel=channel,
event_type=event_type,
status=status,
title=title[:255],
message=message[:1000],
response_status=response_status[:50],
error_message=error_message[:500],
)
self.db.add(history)
self.db.commit()
except Exception as e:
logger.error(f"Failed to save notification history: {e}")
self.db.rollback()
async def test_channel(
self,
user_id: int,
channel: str,
) -> Dict[str, Any]:
"""
Test a notification channel.
Args:
user_id: User ID
channel: Channel to test
Returns:
Test result
"""
settings = self._get_user_settings(user_id)
if not settings:
return {"success": False, "error": "Settings not found"}
backend = self._get_backend(channel, settings)
if not backend:
return {"success": False, "error": f"Channel {channel} not configured"}
try:
if channel == "email":
result = backend.test(settings.email_address)
else:
result = backend.test()
return result
except Exception as e:
return {"success": False, "error": str(e)}
async def get_rate_limit_status(self, user_id: int) -> Dict[str, Any]:
"""Get rate limit status for all channels"""
settings = self._get_user_settings(user_id)
if not settings:
return {}
channels = self._get_enabled_channels(settings)
status = {}
for channel in channels:
rate_key = f"user_{user_id}_{channel}"
remaining = await self.rate_limiter.get_remaining(rate_key, settings.rate_limit_per_minute)
status[channel] = {
"limit": settings.rate_limit_per_minute,
"remaining": remaining,
"window_seconds": 60,
}
return status
def get_notification_history(
self,
user_id: int,
limit: int = 100,
offset: int = 0,
channel: Optional[str] = None,
status: Optional[str] = None,
) -> List[Dict[str, Any]]:
"""Get notification history for user"""
if not self.db:
return []
query = self.db.query(NotificationHistory).filter(NotificationHistory.user_id == user_id)
if channel:
query = query.filter(NotificationHistory.channel == channel)
if status:
query = query.filter(NotificationHistory.status == status)
history = query.order_by(NotificationHistory.created_at.desc()).offset(offset).limit(limit).all()
return [h.to_dict() for h in history]
def get_stats(self, user_id: int) -> Dict[str, Any]:
"""Get notification statistics for user"""
if not self.db:
return {}
total = self.db.query(NotificationHistory).filter(NotificationHistory.user_id == user_id).count()
sent = (
self.db.query(NotificationHistory)
.filter(NotificationHistory.user_id == user_id, NotificationHistory.status == "sent")
.count()
)
failed = (
self.db.query(NotificationHistory)
.filter(NotificationHistory.user_id == user_id, NotificationHistory.status == "failed")
.count()
)
# Count by channel
channel_counts = {}
for channel in ["slack", "discord", "email", "telegram", "webhook"]:
count = (
self.db.query(NotificationHistory)
.filter(NotificationHistory.user_id == user_id, NotificationHistory.channel == channel)
.count()
)
if count > 0:
channel_counts[channel] = count
return {
"total": total,
"sent": sent,
"failed": failed,
"success_rate": (sent / total * 100) if total > 0 else 0,
"by_channel": channel_counts,
}
# Global manager instance
_notification_manager: Optional[NotificationManager] = None
def get_notification_manager(db_session: Optional[Session] = None) -> NotificationManager:
"""Get or create global notification manager"""
global _notification_manager
if _notification_manager is None:
_notification_manager = NotificationManager(db_session)
elif db_session:
_notification_manager.db = db_session
return _notification_manager

Xet Storage Details

Size:
21.3 kB
·
Xet hash:
689067440cb9d9a1d7843ab342b5f1c176e3c0201bf3f0bd05f42385e6e3a690

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.