Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /notifications /backends /slack.py
| """ | |
| Slack Notification Backend for Zen-AI-Pentest | |
| SSRF Protection: All outbound requests are restricted to official Slack webhook URLs. | |
| See: https://api.slack.com/messaging/webhooks | |
| """ | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, Final, List, Optional, Tuple, Union | |
| from urllib.parse import urlparse | |
| import requests | |
| logger = logging.getLogger(__name__) | |
| # Allowed webhook hosts (constant for code analysis visibility) | |
| # codeql[python/ssrf]: These are the only allowed hosts for SSRF protection | |
| ALLOWED_SLACK_HOSTS: Final[Tuple[str, ...]] = ( | |
| "hooks.slack.com", # Official Slack incoming webhooks | |
| "hooks.slack.dev", # Slack development/testing environment | |
| ) | |
| # Validate scheme (prevent file://, ftp://, etc.) | |
| ALLOWED_SCHEMES: Final[Tuple[str, ...]] = ("https",) # Slack only uses HTTPS | |
| class ValidatedSlackWebhook: | |
| """ | |
| A Slack webhook URL that has been validated and is safe to use. | |
| This type ensures that any URL used for outbound requests has passed | |
| SSRF validation. The validation happens at construction time. | |
| """ | |
| __slots__ = ("url",) | |
| def __init__(self, url: str) -> None: | |
| """ | |
| Validate and store a Slack webhook URL. | |
| Raises: | |
| ValueError: If URL is not a valid Slack webhook URL | |
| """ | |
| self.url = self._validate(url) | |
| def _validate(url: str) -> str: | |
| """ | |
| Validate that the provided URL is a legitimate Slack webhook URL. | |
| This function provides SSRF protection by: | |
| 1. Requiring HTTPS scheme | |
| 2. Restricting to official Slack webhook hosts only | |
| 3. Ensuring the URL has a valid structure | |
| Args: | |
| url: The webhook URL to validate | |
| Returns: | |
| The validated URL (unchanged, but confirmed safe) | |
| Raises: | |
| ValueError: If URL fails any validation check | |
| """ | |
| if not url: | |
| raise ValueError("webhook_url is required") | |
| parsed = urlparse(url) | |
| # Validate scheme (prevent file://, ftp://, etc.) | |
| if parsed.scheme not in ALLOWED_SCHEMES: | |
| raise ValueError(f"Invalid webhook URL scheme: '{parsed.scheme}'. Only HTTPS is allowed for security reasons.") | |
| # Validate hostname exists | |
| if not parsed.netloc: | |
| raise ValueError("Invalid webhook URL: no hostname found") | |
| # Extract hostname (remove port if present) | |
| host = parsed.hostname or "" | |
| # Strict host validation (SSRF protection) | |
| # Only allow official Slack webhook domains | |
| if host not in ALLOWED_SLACK_HOSTS: | |
| raise ValueError(f"Webhook host is not allowed: '{host}'. Only official Slack hosts are permitted.") | |
| return url | |
| def __str__(self) -> str: | |
| """Return the validated URL (masked for logging).""" | |
| return self.url | |
| def __repr__(self) -> str: | |
| """Return masked representation.""" | |
| # Mask the URL for secure logging | |
| parsed = urlparse(self.url) | |
| masked_path = parsed.path[:15] + "..." if len(parsed.path) > 15 else parsed.path | |
| return f"ValidatedSlackWebhook(https://{parsed.netloc}{masked_path})" | |
| class SlackBackend: | |
| """Slack Notification Backend with rate limiting and retry support""" | |
| def __init__( | |
| self, | |
| webhook_url: Union[str, ValidatedSlackWebhook], | |
| channel: Optional[str] = None, | |
| timeout: int = 10, | |
| max_retries: int = 3, | |
| ) -> None: | |
| """ | |
| Initialize Slack backend. | |
| Args: | |
| webhook_url: Slack webhook URL (validated) | |
| channel: Optional channel override | |
| timeout: Request timeout in seconds | |
| max_retries: Maximum retry attempts | |
| """ | |
| if isinstance(webhook_url, str): | |
| webhook_url = ValidatedSlackWebhook(webhook_url) | |
| self._webhook: Final[str] = webhook_url.url | |
| self._channel = channel | |
| self._timeout = timeout | |
| self._max_retries = max_retries | |
| def from_raw_url( | |
| cls, | |
| webhook_url: str, | |
| channel: Optional[str] = None, | |
| timeout: int = 10, | |
| max_retries: int = 3, | |
| ) -> "SlackBackend": | |
| """Create backend from raw URL with validation.""" | |
| validated = ValidatedSlackWebhook(webhook_url) | |
| return cls(validated, channel, timeout, max_retries) | |
| def send( | |
| self, | |
| message: str, | |
| title: Optional[str] = None, | |
| color: Optional[str] = None, | |
| fields: Optional[List[Dict[str, Any]]] = None, | |
| footer: Optional[str] = None, | |
| timestamp: Optional[datetime] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Send notification to Slack. | |
| Args: | |
| message: Main message text | |
| title: Optional title for attachment | |
| color: Color for attachment bar (danger, warning, good, or hex) | |
| fields: List of field dicts with title, value, short keys | |
| footer: Footer text | |
| timestamp: Optional timestamp | |
| Returns: | |
| Dict with success status and response info | |
| """ | |
| attachment = { | |
| "color": color or "#36a64f", | |
| "text": message, | |
| } | |
| if title: | |
| attachment["title"] = title | |
| if fields: | |
| attachment["fields"] = [ | |
| { | |
| "title": f.get("title", ""), | |
| "value": str(f.get("value", "")), | |
| "short": f.get("short", False), | |
| } | |
| for f in fields | |
| ] | |
| if footer: | |
| attachment["footer"] = footer | |
| if timestamp: | |
| attachment["ts"] = int(timestamp.timestamp()) | |
| payload = {"attachments": [attachment]} | |
| if self._channel: | |
| payload["channel"] = self._channel | |
| return self._send_with_retry(payload) | |
| def send_event( | |
| self, | |
| event_type: str, | |
| data: Dict[str, Any], | |
| template_data: Optional[Dict[str, Any]] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Send event notification using templates. | |
| Args: | |
| event_type: Type of event (scan_started, scan_completed, etc.) | |
| data: Event data | |
| template_data: Optional pre-rendered template data | |
| Returns: | |
| Dict with success status | |
| """ | |
| if template_data: | |
| return self.send(**template_data) | |
| # Build message based on event type | |
| builders = { | |
| "scan_started": self._build_scan_started, | |
| "scan_completed": self._build_scan_completed, | |
| "critical_finding": self._build_critical_finding, | |
| "high_severity_cve": self._build_high_severity_cve, | |
| "system_alert": self._build_system_alert, | |
| "report_ready": self._build_report_ready, | |
| } | |
| builder = builders.get(event_type, self._build_generic) | |
| message_data = builder(data) | |
| return self.send(**message_data) | |
| def _build_scan_started(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build scan started notification""" | |
| return { | |
| "title": "๐ Scan Started", | |
| "message": f"Scan of **{data.get('target', 'Unknown')}** has started.", | |
| "color": "#3b82f6", # Blue | |
| "fields": [ | |
| {"title": "Scan ID", "value": str(data.get("scan_id", "N/A")), "short": True}, | |
| {"title": "Target", "value": data.get("target", "N/A"), "short": True}, | |
| {"title": "Scan Type", "value": data.get("scan_type", "N/A"), "short": True}, | |
| {"title": "Started By", "value": data.get("started_by", "N/A"), "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_scan_completed(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build scan completed notification""" | |
| findings = data.get("findings_count", 0) | |
| critical = data.get("critical_count", 0) | |
| high = data.get("high_count", 0) | |
| if critical > 0: | |
| color = "danger" | |
| status = "๐ด CRITICAL ISSUES FOUND" | |
| elif high > 0: | |
| color = "warning" | |
| status = "๐ HIGH SEVERITY ISSUES" | |
| elif findings > 0: | |
| color = "#FFA500" | |
| status = "๐ก ISSUES FOUND" | |
| else: | |
| color = "good" | |
| status = "๐ข NO ISSUES FOUND" | |
| return { | |
| "title": f"Scan Completed - {status}", | |
| "message": f"Scan of **{data.get('target', 'Unknown')}** completed in {data.get('duration', 'N/A')}s.", | |
| "color": color, | |
| "fields": [ | |
| {"title": "Scan ID", "value": str(data.get("scan_id", "N/A")), "short": True}, | |
| {"title": "Target", "value": data.get("target", "N/A"), "short": True}, | |
| {"title": "Total Findings", "value": str(findings), "short": True}, | |
| {"title": "Critical", "value": str(critical), "short": True}, | |
| {"title": "High", "value": str(high), "short": True}, | |
| {"title": "Duration", "value": f"{data.get('duration', 'N/A')}s", "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_critical_finding(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build critical finding notification""" | |
| return { | |
| "title": "๐จ Critical Vulnerability Found", | |
| "message": data.get("description", "A critical vulnerability has been discovered.")[:500], | |
| "color": "danger", | |
| "fields": [ | |
| {"title": "Target", "value": data.get("target", "N/A"), "short": True}, | |
| {"title": "CVE", "value": data.get("cve", "N/A"), "short": True}, | |
| {"title": "CVSS", "value": str(data.get("cvss", "N/A")), "short": True}, | |
| {"title": "Severity", "value": "CRITICAL", "short": True}, | |
| {"title": "Tool", "value": data.get("tool", "Unknown"), "short": True}, | |
| {"title": "Port", "value": str(data.get("port", "N/A")), "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest | Immediate Action Required", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_high_severity_cve(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build high severity CVE notification""" | |
| return { | |
| "title": f"โ ๏ธ High Severity CVE: {data.get('cve', 'Unknown')}", | |
| "message": data.get("description", "")[:500], | |
| "color": "warning", | |
| "fields": [ | |
| {"title": "CVE ID", "value": data.get("cve", "N/A"), "short": True}, | |
| {"title": "CVSS Score", "value": str(data.get("cvss", "N/A")), "short": True}, | |
| {"title": "Affected", "value": data.get("affected", "N/A"), "short": True}, | |
| {"title": "EPSS", "value": str(data.get("epss", "N/A")), "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_system_alert(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build system alert notification""" | |
| alert_type = data.get("alert_type", "info") | |
| colors = { | |
| "error": "danger", | |
| "warning": "warning", | |
| "info": "#3b82f6", | |
| "success": "good", | |
| } | |
| return { | |
| "title": f"๐ System Alert: {data.get('title', 'Notification')}", | |
| "message": data.get("message", ""), | |
| "color": colors.get(alert_type, "#3b82f6"), | |
| "fields": [ | |
| {"title": "Component", "value": data.get("component", "N/A"), "short": True}, | |
| {"title": "Severity", "value": alert_type.upper(), "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest System", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_report_ready(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build report ready notification""" | |
| return { | |
| "title": "๐ Report Ready", | |
| "message": f"Your security report for **{data.get('target', 'Unknown')}** is ready for download.", | |
| "color": "good", | |
| "fields": [ | |
| {"title": "Report ID", "value": str(data.get("report_id", "N/A")), "short": True}, | |
| {"title": "Scan ID", "value": str(data.get("scan_id", "N/A")), "short": True}, | |
| {"title": "Format", "value": data.get("format", "PDF").upper(), "short": True}, | |
| {"title": "Size", "value": data.get("size", "N/A"), "short": True}, | |
| ], | |
| "footer": "Zen-AI-Pentest", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _build_generic(self, data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Build generic notification""" | |
| return { | |
| "title": data.get("title", "Notification"), | |
| "message": data.get("message", ""), | |
| "color": data.get("color", "#3b82f6"), | |
| "fields": data.get("fields", []), | |
| "footer": "Zen-AI-Pentest", | |
| "timestamp": datetime.now(timezone.utc), | |
| } | |
| def _send_with_retry(self, payload: Dict[str, Any]) -> Dict[str, Any]: | |
| """Send with retry logic""" | |
| last_error = None | |
| for attempt in range(self._max_retries): | |
| try: | |
| response = requests.post( | |
| self._webhook, | |
| json=payload, | |
| timeout=self._timeout, | |
| headers={"Content-Type": "application/json"}, | |
| ) | |
| if response.status_code == 200: | |
| return { | |
| "success": True, | |
| "status_code": response.status_code, | |
| "attempt": attempt + 1, | |
| } | |
| elif response.status_code == 429: # Rate limited | |
| retry_after = int(response.headers.get("Retry-After", 5)) | |
| logger.warning(f"Slack rate limited, retrying after {retry_after}s") | |
| import time | |
| time.sleep(retry_after) | |
| last_error = f"Rate limited (HTTP {response.status_code})" | |
| else: | |
| last_error = f"HTTP {response.status_code}: {response.text}" | |
| logger.warning(f"Slack request failed: {last_error}") | |
| except requests.RequestException as e: | |
| last_error = str(e) | |
| logger.warning(f"Slack request error (attempt {attempt + 1}): {e}") | |
| # Exponential backoff | |
| if attempt < self._max_retries - 1: | |
| import time | |
| time.sleep(2**attempt) | |
| return { | |
| "success": False, | |
| "error": last_error, | |
| "attempts": self._max_retries, | |
| } | |
| def test(self) -> Dict[str, Any]: | |
| """Test the Slack connection""" | |
| return self.send( | |
| message="This is a test notification from Zen-AI-Pentest.", | |
| title="๐ Test Notification", | |
| color="good", | |
| footer="Zen-AI-Pentest Notification System", | |
| ) | |
Xet Storage Details
- Size:
- 15.4 kB
- Xet hash:
- a0fa4331fa320c94072be2bdaf437d2569e8a2dcd8908e1d50e54df956b8148a
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.