|
| 1 | +"""Optional webhook alerting for runtime monitoring events (#72). |
| 2 | +
|
| 3 | +Fires at most once per alert condition (tracked in `runtime_alerts_sent`) to |
| 4 | +`[runtime] alert_webhook` in `~/.secfoo/config.toml`: |
| 5 | + - `reached_from_traffic`: vulnerable function first hit during live traffic |
| 6 | + - `new_advisory`: newly discovered advisory against a running package version |
| 7 | + - `sensor_stale`: connected sensor missed >= 3 heartbeats |
| 8 | +
|
| 9 | +Payloads carry finding fingerprint, app, env, and a deep link — never stack |
| 10 | +samples or source frames. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +import logging |
| 17 | +import urllib.error |
| 18 | +import urllib.request |
| 19 | +from collections.abc import Callable |
| 20 | +from datetime import datetime, timezone |
| 21 | +from urllib.parse import urlsplit |
| 22 | + |
| 23 | +from secfoo.settings import ConfigError, load_config |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | +ALERT_TIMEOUT_SECONDS = 5 |
| 28 | +HEARTBEAT_INTERVAL_SECONDS = 30 |
| 29 | +MISSED_HEARTBEATS_FOR_STALE = 3 |
| 30 | +STALE_AFTER_SECONDS = HEARTBEAT_INTERVAL_SECONDS * MISSED_HEARTBEATS_FOR_STALE |
| 31 | + |
| 32 | +Sender = Callable[[str, dict], None] |
| 33 | + |
| 34 | + |
| 35 | +def parse_iso_timestamp(ts: str | None) -> datetime | None: |
| 36 | + """Parse an ISO-8601 timestamp string into a UTC-aware datetime, or None if invalid.""" |
| 37 | + if not ts: |
| 38 | + return None |
| 39 | + try: |
| 40 | + dt = datetime.fromisoformat(ts[:-1] + "+00:00" if ts.endswith("Z") else ts) |
| 41 | + return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt |
| 42 | + except ValueError: |
| 43 | + return None |
| 44 | + |
| 45 | + |
| 46 | +def post_webhook(url: str, payload: dict) -> None: |
| 47 | + """POST JSON `payload` to user-configured `url` (`http://` or `https://`).""" |
| 48 | + if not url.startswith(("https://", "http://")): |
| 49 | + raise ValueError("Refusing non-HTTP webhook URL") |
| 50 | + body = json.dumps(payload, sort_keys=True).encode("utf-8") |
| 51 | + request = urllib.request.Request( # nosec B310 -- scheme validated above from user config |
| 52 | + url, |
| 53 | + data=body, |
| 54 | + headers={"Content-Type": "application/json", "User-Agent": "secfoo-runtime-alerts"}, |
| 55 | + method="POST", |
| 56 | + ) |
| 57 | + try: |
| 58 | + with urllib.request.urlopen(request, timeout=ALERT_TIMEOUT_SECONDS) as resp: # nosec B310 |
| 59 | + resp.read(256) |
| 60 | + except (urllib.error.URLError, OSError) as exc: |
| 61 | + # Log hostname only: Slack/Teams-style webhook URLs carry secret tokens in the path. |
| 62 | + host = urlsplit(url).hostname or "<unknown>" |
| 63 | + logger.warning("Runtime alert webhook delivery failed for host %s: %s", host, exc) |
| 64 | + |
| 65 | + |
| 66 | +def dispatch_webhook(url: str, payload: dict) -> None: |
| 67 | + """Background-task wrapper so monkeypatched `post_webhook` is resolved at delivery time.""" |
| 68 | + post_webhook(url, payload) |
| 69 | + |
| 70 | + |
| 71 | +def configured_webhook_url() -> str | None: |
| 72 | + try: |
| 73 | + return load_config().runtime_alert_webhook |
| 74 | + except ConfigError as exc: |
| 75 | + logger.warning("Ignoring invalid runtime webhook config: %s", exc) |
| 76 | + return None |
| 77 | + |
| 78 | + |
| 79 | +def _claim_alert(conn, *, project_id: int, event_type: str, target_key: str) -> bool: |
| 80 | + """Record a deduplication claim within the caller's active transaction.""" |
| 81 | + now = datetime.now(timezone.utc).isoformat() |
| 82 | + cur = conn.execute( |
| 83 | + "INSERT OR IGNORE INTO runtime_alerts_sent (project_id, event_type, target_key, sent_at) " |
| 84 | + "VALUES (?, ?, ?, ?)", |
| 85 | + (project_id, event_type, target_key, now), |
| 86 | + ) |
| 87 | + return cur.rowcount > 0 |
| 88 | + |
| 89 | + |
| 90 | +def clear_alert(conn, *, project_id: int, event_type: str, target_key: str) -> None: |
| 91 | + """Reset deduplication once a sensor recovers (caller owns transaction commit).""" |
| 92 | + conn.execute( |
| 93 | + "DELETE FROM runtime_alerts_sent WHERE project_id = ? AND event_type = ? AND target_key = ?", |
| 94 | + (project_id, event_type, target_key), |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def emit_alert( |
| 99 | + conn, |
| 100 | + *, |
| 101 | + project_id: int, |
| 102 | + event_type: str, |
| 103 | + target_key: str, |
| 104 | + app: str | None = None, |
| 105 | + env: str | None = None, |
| 106 | + finding_fingerprint: str | None = None, |
| 107 | + link: str, |
| 108 | + details: dict[str, object] | None = None, |
| 109 | + webhook_url: str | None = None, |
| 110 | + sender: Sender | None = None, |
| 111 | +) -> bool: |
| 112 | + """Deduplicate and schedule/deliver a sanitized runtime alert payload. |
| 113 | +
|
| 114 | + Claims the row on `conn` without committing so the caller keeps control of its |
| 115 | + transaction boundary; pass `sender` (e.g. FastAPI `BackgroundTasks`) to run the |
| 116 | + network POST outside the caller's request handler. |
| 117 | + """ |
| 118 | + url = webhook_url if webhook_url is not None else configured_webhook_url() |
| 119 | + if not url: |
| 120 | + return False |
| 121 | + if not _claim_alert(conn, project_id=project_id, event_type=event_type, target_key=target_key): |
| 122 | + return False |
| 123 | + payload: dict[str, object] = { |
| 124 | + "event": event_type, |
| 125 | + "project_id": project_id, |
| 126 | + "finding_fingerprint": finding_fingerprint, |
| 127 | + "app": app, |
| 128 | + "env": env, |
| 129 | + "link": link, |
| 130 | + "sent_at": datetime.now(timezone.utc).isoformat(), |
| 131 | + } |
| 132 | + if details: |
| 133 | + # Never forward stack traces or entry frames in webhook payloads. |
| 134 | + safe_details = {k: v for k, v in details.items() if k not in {"stack_sample", "entry_frame"}} |
| 135 | + if safe_details: |
| 136 | + payload["details"] = safe_details |
| 137 | + (sender or dispatch_webhook)(url, payload) |
| 138 | + return True |
| 139 | + |
| 140 | + |
| 141 | +def detect_stale_sensors( |
| 142 | + conn, |
| 143 | + *, |
| 144 | + project_id: int | None = None, |
| 145 | + now: datetime | None = None, |
| 146 | + sender: Sender | None = None, |
| 147 | +) -> list[str]: |
| 148 | + """Emit `sensor_stale` alerts for sensors whose heartbeat exceeded STALE_AFTER_SECONDS. |
| 149 | +
|
| 150 | + Caller owns transaction commit on `conn`; pass `sender` to deliver webhooks off-loop. |
| 151 | + Returns the list of sensor IDs newly marked stale. |
| 152 | + """ |
| 153 | + if not configured_webhook_url(): |
| 154 | + return [] |
| 155 | + ref_now = now or datetime.now(timezone.utc) |
| 156 | + if ref_now.tzinfo is None: |
| 157 | + ref_now = ref_now.replace(tzinfo=timezone.utc) |
| 158 | + query = ( |
| 159 | + "SELECT s.project_id, s.sensor_id, s.app, s.env, s.last_heartbeat_at " |
| 160 | + "FROM runtime_sensors s " |
| 161 | + "LEFT JOIN runtime_alerts_sent a " |
| 162 | + "ON a.project_id = s.project_id AND a.event_type = 'sensor_stale' AND a.target_key = s.sensor_id " |
| 163 | + "WHERE a.target_key IS NULL" |
| 164 | + ) |
| 165 | + params: list[object] = [] |
| 166 | + if project_id is not None: |
| 167 | + query += " AND s.project_id = ?" |
| 168 | + params.append(project_id) |
| 169 | + rows = conn.execute(query, params).fetchall() |
| 170 | + alerted: list[str] = [] |
| 171 | + for s in rows: |
| 172 | + last_hb = parse_iso_timestamp(s["last_heartbeat_at"]) |
| 173 | + seconds_since_hb = (ref_now - last_hb).total_seconds() if last_hb else float("inf") |
| 174 | + if seconds_since_hb <= STALE_AFTER_SECONDS: |
| 175 | + continue |
| 176 | + pid = int(s["project_id"]) |
| 177 | + if emit_alert( |
| 178 | + conn, |
| 179 | + project_id=pid, |
| 180 | + event_type="sensor_stale", |
| 181 | + target_key=s["sensor_id"], |
| 182 | + app=s["app"], |
| 183 | + env=s["env"], |
| 184 | + link=f"/projects/{pid}/runtime", |
| 185 | + details={"sensor_id": s["sensor_id"], "last_heartbeat_at": s["last_heartbeat_at"]}, |
| 186 | + sender=sender, |
| 187 | + ): |
| 188 | + alerted.append(str(s["sensor_id"])) |
| 189 | + return alerted |
0 commit comments