Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /notifications /__init__.py
| """ | |
| Notifications Module for Zen-AI-Pentest | |
| Provides unified notification capabilities for various channels: | |
| - Email (SMTP) | |
| - Slack | |
| - Discord | |
| - Telegram | |
| - Microsoft Teams | |
| Usage: | |
| from notifications import NotificationManager | |
| manager = NotificationManager() | |
| manager.send_scan_complete( | |
| scan_id="scan-001", | |
| target="example.com", | |
| findings_count=5, | |
| critical_count=1 | |
| ) | |
| """ | |
| import logging | |
| import os | |
| from typing import Any, Dict, List, Tuple, Union | |
| from notifications.discord import DiscordNotifier | |
| from notifications.email_sender import ( | |
| EmailConfig, | |
| EmailReporter, | |
| send_report_after_scan, | |
| ) | |
| from notifications.slack import SlackNotifier, slack_notify_scan_complete | |
| from notifications.teams import TeamsNotifier | |
| from notifications.telegram import TelegramNotifier | |
| logger = logging.getLogger(__name__) | |
| # Type alias for notifier instances | |
| NotifierInstance = Union[EmailReporter, SlackNotifier, DiscordNotifier, TelegramNotifier, TeamsNotifier] | |
| class NotificationManager: | |
| """ | |
| Central notification manager for all channels. | |
| Automatically initializes configured notifiers from environment variables. | |
| """ | |
| def __init__(self) -> None: | |
| self.notifiers: List[Tuple[str, NotifierInstance]] = [] | |
| self._init_notifiers() | |
| def _init_notifiers(self) -> None: | |
| """Initialize all configured notifiers from environment variables.""" | |
| self._init_email_notifier() | |
| self._init_slack_notifier() | |
| self._init_discord_notifier() | |
| self._init_telegram_notifier() | |
| self._init_teams_notifier() | |
| logger.info("Initialized %d notification channels", len(self.notifiers)) | |
| def _init_email_notifier(self) -> None: | |
| """Initialize email notifier if configured.""" | |
| smtp_host = os.getenv("SMTP_HOST") | |
| smtp_user = os.getenv("SMTP_USER") | |
| if smtp_host and smtp_user: | |
| try: | |
| self.notifiers.append(("email", EmailReporter())) | |
| logger.debug("Email notifier initialized") | |
| except Exception as e: | |
| logger.warning("Failed to init email notifier: %s", e) | |
| def _init_slack_notifier(self) -> None: | |
| """Initialize Slack notifier if configured.""" | |
| webhook_url = os.getenv("SLACK_WEBHOOK_URL") | |
| if webhook_url: | |
| try: | |
| notifier = SlackNotifier.from_raw_url(webhook_url) | |
| self.notifiers.append(("slack", notifier)) | |
| logger.debug("Slack notifier initialized") | |
| except Exception as e: | |
| logger.warning("Failed to init slack notifier: %s", e) | |
| def _init_discord_notifier(self) -> None: | |
| """Initialize Discord notifier if configured.""" | |
| webhook_url = os.getenv("DISCORD_WEBHOOK_URL") | |
| if webhook_url: | |
| try: | |
| self.notifiers.append(("discord", DiscordNotifier(webhook_url))) | |
| logger.debug("Discord notifier initialized") | |
| except Exception as e: | |
| logger.warning("Failed to init discord notifier: %s", e) | |
| def _init_telegram_notifier(self) -> None: | |
| """Initialize Telegram notifier if configured.""" | |
| bot_token = os.getenv("TELEGRAM_BOT_TOKEN") | |
| chat_id = os.getenv("TELEGRAM_CHAT_ID") | |
| if bot_token and chat_id: | |
| try: | |
| self.notifiers.append(("telegram", TelegramNotifier(bot_token=bot_token, chat_id=chat_id))) | |
| logger.debug("Telegram notifier initialized") | |
| except Exception as e: | |
| logger.warning("Failed to init telegram notifier: %s", e) | |
| def _init_teams_notifier(self) -> None: | |
| """Initialize Teams notifier if configured.""" | |
| webhook_url = os.getenv("TEAMS_WEBHOOK_URL") | |
| if webhook_url: | |
| try: | |
| self.notifiers.append(("teams", TeamsNotifier(webhook_url))) | |
| logger.debug("Teams notifier initialized") | |
| except Exception as e: | |
| logger.warning("Failed to init teams notifier: %s", e) | |
| def send_scan_complete( | |
| self, | |
| scan_id: str, | |
| target: str, | |
| findings_count: int, | |
| critical_count: int, | |
| high_count: int = 0, | |
| duration: float = 0.0, | |
| ) -> Dict[str, bool]: | |
| """Send scan completion notification to all configured channels. | |
| Args: | |
| scan_id: Unique scan identifier. | |
| target: Target that was scanned. | |
| findings_count: Total number of findings. | |
| critical_count: Number of critical findings. | |
| high_count: Number of high severity findings. | |
| duration: Scan duration in seconds. | |
| Returns: | |
| Dictionary mapping channel names to success status. | |
| """ | |
| results: Dict[str, bool] = {} | |
| for name, notifier in self.notifiers: | |
| try: | |
| success = self._send_scan_complete_to_channel( | |
| name, notifier, scan_id, target, findings_count, critical_count, high_count | |
| ) | |
| results[name] = success | |
| except Exception as e: | |
| results[name] = False | |
| logger.error("Failed to send %s notification: %s", name, e) | |
| return results | |
| def _send_scan_complete_to_channel( | |
| self, | |
| channel: str, | |
| notifier: NotifierInstance, | |
| scan_id: str, | |
| target: str, | |
| findings_count: int, | |
| critical_count: int, | |
| high_count: int = 0, | |
| ) -> bool: | |
| """Send scan complete notification to a specific channel. | |
| Args: | |
| channel: Channel name. | |
| notifier: Notifier instance. | |
| scan_id: Scan identifier. | |
| target: Scan target. | |
| findings_count: Total findings count. | |
| critical_count: Critical findings count. | |
| high_count: High findings count. | |
| Returns: | |
| True if notification was sent successfully. | |
| """ | |
| if channel == "email" and isinstance(notifier, EmailReporter): | |
| to_email = os.getenv("NOTIFY_EMAIL", os.getenv("SMTP_USER", "")) | |
| return notifier.send_simple_notification( | |
| to_email=to_email, | |
| subject=f"Pentest Complete: {target}", | |
| message=(f"Scan {scan_id} completed. Findings: {findings_count}, Critical: {critical_count}"), | |
| ) | |
| elif channel == "slack" and isinstance(notifier, SlackNotifier): | |
| return notifier.send_scan_completed( | |
| scan_id=scan_id, | |
| target=target, | |
| findings_count=findings_count, | |
| critical_count=critical_count, | |
| ) | |
| elif channel == "discord" and isinstance(notifier, DiscordNotifier): | |
| return notifier.send_scan_completed( | |
| scan_id=scan_id, | |
| target=target, | |
| findings_count=findings_count, | |
| critical_count=critical_count, | |
| ) | |
| elif channel == "telegram" and isinstance(notifier, TelegramNotifier): | |
| message = ( | |
| f"🔒 *Scan Complete*\n" | |
| f"Target: `{target}`\n" | |
| f"ID: `{scan_id}`\n" | |
| f"Findings: {findings_count} (Critical: {critical_count})" | |
| ) | |
| return notifier.send_message(message) | |
| elif channel == "teams" and isinstance(notifier, TeamsNotifier): | |
| return notifier.send_scan_completed( | |
| scan_id=scan_id, | |
| target=target, | |
| findings_count=findings_count, | |
| critical_count=critical_count, | |
| ) | |
| else: | |
| logger.warning("Unknown channel type: %s", channel) | |
| return False | |
| def send_critical_finding(self, finding: Dict[str, Any]) -> Dict[str, bool]: | |
| """Send critical finding alert to all channels. | |
| Args: | |
| finding: Finding data dictionary. | |
| Returns: | |
| Dictionary mapping channel names to success status. | |
| """ | |
| results: Dict[str, bool] = {} | |
| for name, notifier in self.notifiers: | |
| try: | |
| success = self._send_critical_finding_to_channel(name, notifier, finding) | |
| results[name] = success | |
| except Exception as e: | |
| results[name] = False | |
| logger.error("Failed to send %s critical alert: %s", name, e) | |
| return results | |
| def _send_critical_finding_to_channel( | |
| self, | |
| channel: str, | |
| notifier: NotifierInstance, | |
| finding: Dict[str, Any], | |
| ) -> bool: | |
| """Send critical finding to a specific channel. | |
| Args: | |
| channel: Channel name. | |
| notifier: Notifier instance. | |
| finding: Finding data. | |
| Returns: | |
| True if notification was sent successfully. | |
| """ | |
| if channel == "slack" and isinstance(notifier, SlackNotifier): | |
| return notifier.send_critical_finding(finding) | |
| elif channel == "discord" and isinstance(notifier, DiscordNotifier): | |
| return notifier.send_critical_finding(finding) | |
| elif channel == "telegram" and isinstance(notifier, TelegramNotifier): | |
| message = ( | |
| f"🚨 *CRITICAL FINDING*\n" | |
| f"Title: {finding.get('title', 'N/A')}\n" | |
| f"Target: {finding.get('target', 'N/A')}\n" | |
| f"Severity: CRITICAL" | |
| ) | |
| return notifier.send_message(message) | |
| elif channel == "email" and isinstance(notifier, EmailReporter): | |
| to_email = os.getenv("NOTIFY_EMAIL", os.getenv("SMTP_USER", "")) | |
| return notifier.send_simple_notification( | |
| to_email=to_email, | |
| subject=f"🚨 CRITICAL: {finding.get('title', 'Unknown')}", | |
| message=str(finding), | |
| ) | |
| else: | |
| logger.debug("Channel %s does not support critical finding alerts", channel) | |
| return False | |
| def get_configured_channels(self) -> List[str]: | |
| """Return list of configured notification channels. | |
| Returns: | |
| List of channel names. | |
| """ | |
| return [name for name, _ in self.notifiers] | |
| def is_configured(self, channel: str) -> bool: | |
| """Check if a specific channel is configured. | |
| Args: | |
| channel: Channel name to check. | |
| Returns: | |
| True if channel is configured. | |
| """ | |
| return any(name == channel for name, _ in self.notifiers) | |
| __all__ = [ | |
| "NotificationManager", | |
| "EmailReporter", | |
| "EmailConfig", | |
| "send_report_after_scan", | |
| "SlackNotifier", | |
| "slack_notify_scan_complete", | |
| "DiscordNotifier", | |
| "TelegramNotifier", | |
| "TeamsNotifier", | |
| ] | |
Xet Storage Details
- Size:
- 10.8 kB
- Xet hash:
- b49d42097fdf5e7d50103b8385eab3f00118bddab936cac6ba3b388a41713bb6
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.