33Severity normalization lives HERE (SSDF owns the schema knowledge): ssdf.events
44has no severity column; each provider hides severity in ext differently.
55Scale: critical=4, high=3, medium=2, low=1.
6+
7+ alert_counts: grouped counts over the SAME alert gate, severity expression and
8+ signature expression as recent_alerts, so a noisy source cannot hide how many
9+ alerts of each kind there were behind recent_alerts' row limit.
610"""
711
812from __future__ import annotations
2428# if sev != "" { ext = set!(ext, ["panw.panos.severity"], sev) }
2529PAN_SEVERITY_KEY = "panw.panos.severity"
2630
31+ # UniFi controller events (WAN down, device offline, IP conflict...) carry the CEF
32+ # header severity 0-10. Bands follow the common CEF convention: 0-3 low, 4-6 medium,
33+ # 7-8 high, 9-10 critical. UniFi does not document which severity an outage gets.
34+ _UNIFI_EVENT_SEV_SQL = "toInt32OrZero(ext['unifi.event.severity'])"
35+
2736# normalize_severity as a ClickHouse expression, so the floor applies BEFORE the
2837# LIMIT. Filtering only in Python let the newest rows below the floor (PAN-OS
2938# informational system logs, thousands a day) use up the whole LIMIT and the tool
3746 "lower(ext['panw.panos.severity']) = 'high', 3, "
3847 "lower(ext['panw.panos.severity']) = 'medium', 2, "
3948 "lower(ext['panw.panos.severity']) IN ('low', 'informational'), 1, 2), "
49+ "ext['unifi.event.severity'] != '', "
50+ f"multiIf({ _UNIFI_EVENT_SEV_SQL } <= 3, 1, { _UNIFI_EVENT_SEV_SQL } <= 6, 2, "
51+ f"{ _UNIFI_EVENT_SEV_SQL } <= 8, 3, 4), "
4052 "ext['syslog.severity'] != '', "
4153 "multiIf(toInt32OrZero(ext['syslog.severity']) <= 2, 4, "
4254 "toInt32OrZero(ext['syslog.severity']) = 3, 3, "
4759# Junos screen (RT_SCREEN) rows carry this literal instead of a rule name.
4860NO_RULE_NAMES = ("" , "N/A" )
4961
62+ # How an alert is named: UniFi IPS signature, else rule name (unless empty/N/A),
63+ # else event action, else event kind. ONE definition, used by recent_alerts and
64+ # alert_counts, in SQL so grouped counts are exact.
65+ SIGNATURE_SQL = (
66+ "multiIf(ext['unifi.ips.signature'] != '', ext['unifi.ips.signature'], "
67+ f"rule_name NOT IN { NO_RULE_NAMES !r} , rule_name, "
68+ "event_action != '', event_action, event_kind)"
69+ )
70+
71+ # Alert-class gate: explicit event_kind IN (alert) OR has UniFi IPS signature
72+ # OR has PAN severity ext key (PAN THREAT logs keep event_kind='event')
73+ ALERT_GATE_SQL = (
74+ "(event_kind IN %(kinds)s OR ext['unifi.ips.signature'] != '' "
75+ "OR ext['panw.panos.severity'] != '')"
76+ )
77+
78+ # Max (provider, observer, signature, severity) groups alert_counts returns.
79+ MAX_COUNT_GROUPS = 500
80+
81+
82+ def _int_or_zero (value : str ) -> int :
83+ """Mirror ClickHouse toInt32OrZero for the severity strings."""
84+ try :
85+ return int (value )
86+ except ValueError :
87+ return 0
88+
5089
5190def normalize_severity (provider : str , event_kind : str , ext : dict ) -> tuple [str , int ] | None :
5291 """Return (severity_label, severity_num) or None if not an alert-class row.
@@ -59,28 +98,42 @@ def normalize_severity(provider: str, event_kind: str, ext: dict) -> tuple[str,
5998 Returns:
6099 (severity_label, severity_num) tuple or None if not alert-class
61100 """
101+ # Empty values count as absent, like the SQL `!= ''` guards in SEVERITY_NUM_SQL.
62102 # UniFi IPS (Suricata): 1 is WORST, inverted scale
63- # Vector.toml line 519: if sev != "" { ext = set!(ext, ["unifi.ips.severity"], sev) }
64- if "unifi.ips.severity" in ext :
65- sev = ext ["unifi.ips.severity" ]
66- if sev == "1" :
103+ ips_sev = ext .get ("unifi.ips.severity" )
104+ if ips_sev :
105+ if ips_sev == "1" :
67106 return ("critical" , 4 )
68- elif sev == "2" :
107+ if ips_sev == "2" :
69108 return ("high" , 3 )
70- # 3 and anything else → medium
109+ # 3 and anything else -> medium
71110 return ("medium" , 2 )
72111
73112 # PAN-OS threat: string severity values
74- if PAN_SEVERITY_KEY in ext :
75- s = ext [PAN_SEVERITY_KEY ].lower ()
113+ pan_sev = ext .get (PAN_SEVERITY_KEY )
114+ if pan_sev :
115+ s = pan_sev .lower ()
76116 if s in SEVERITY_NUM :
77117 return (s , SEVERITY_NUM [s ])
78- # informational → low, anything unknown → medium
118+ # informational -> low, anything unknown -> medium
79119 return ("low" , 1 ) if s == "informational" else ("medium" , 2 )
80120
121+ # UniFi controller event: CEF severity 0-10 (bands documented at _UNIFI_EVENT_SEV_SQL)
122+ event_sev = ext .get ("unifi.event.severity" )
123+ if event_sev :
124+ n = _int_or_zero (event_sev )
125+ if n <= 3 :
126+ return ("low" , 1 )
127+ if n <= 6 :
128+ return ("medium" , 2 )
129+ if n <= 8 :
130+ return ("high" , 3 )
131+ return ("critical" , 4 )
132+
81133 # Syslog numeric severity: 0-7, lower is worse (RFC 5424)
82- if "syslog.severity" in ext :
83- n = int (ext ["syslog.severity" ])
134+ syslog_sev = ext .get ("syslog.severity" )
135+ if syslog_sev :
136+ n = _int_or_zero (syslog_sev )
84137 if n <= 2 :
85138 return ("critical" , 4 )
86139 if n == 3 :
@@ -97,49 +150,53 @@ def normalize_severity(provider: str, event_kind: str, ext: dict) -> tuple[str,
97150 return None
98151
99152
100- def build_recent_alerts_sql (
101- since : str , min_severity : str , providers : str , limit : int
102- ) -> tuple [str , dict ]:
103- """Build parameterized SQL for recent alert-class events.
153+ def _alert_where (since : str , min_severity : str , providers : str ) -> tuple [list [str ], dict ]:
154+ """WHERE clauses + params shared by recent_alerts and alert_counts.
104155
105- Args:
106- since: relative or ISO-8601 time expression (parsed via parse_time)
107- min_severity: minimum severity label, applied in SQL so LIMIT counts matching rows
108- providers: comma-separated provider names, or empty for all
109- limit: max rows to return (clamped to 2000)
110-
111- Returns:
112- (sql, params) tuple ready for ClickHouseClient.run()
156+ `timestamp` is QUALIFIED: recent_alerts' SELECT aliases `toString(timestamp) AS
157+ timestamp`, and an unqualified reference binds to that String alias rather
158+ than the real DateTime column, making the window a lexical string compare.
159+ It happens to agree today only because the bound is a datetime rendered in
160+ the same layout toString() emits; qualifying removes the dependency on that
161+ coincidence (see build_subgraph_sql, where the layouts differed and a
162+ same-day window silently returned nothing).
113163 """
114164 params = {
115165 "since" : parse_time (since ),
116- "limit" : max (1 , min (int (limit ), 2000 )),
117166 "floor" : SEVERITY_NUM .get (min_severity , 3 ), # default to high if unknown
167+ "kinds" : tuple (ALERT_KINDS ),
118168 }
119-
120- # Alert-class gate: explicit event_kind IN (alert) OR has UniFi IPS signature
121- # OR has PAN severity ext key (PAN THREAT logs keep event_kind='event')
122- # `timestamp` is QUALIFIED: the SELECT below aliases `toString(timestamp) AS
123- # timestamp`, and an unqualified reference binds to that String alias rather
124- # than the real DateTime column, making the window a lexical string compare.
125- # It happens to agree today only because the bound is a datetime rendered in
126- # the same layout toString() emits; qualifying removes the dependency on that
127- # coincidence (see build_subgraph_sql, where the layouts differed and a
128- # same-day window silently returned nothing).
129169 where = [
130170 "events.timestamp >= %(since)s" ,
131- "(event_kind IN %(kinds)s OR ext['unifi.ips.signature'] != '' OR ext['panw.panos.severity'] != '')" ,
171+ ALERT_GATE_SQL ,
132172 SEVERITY_NUM_SQL + " >= %(floor)s" ,
133173 ]
134- params ["kinds" ] = tuple (ALERT_KINDS )
135-
136174 if providers :
137175 params ["providers" ] = tuple (p .strip () for p in providers .split ("," ) if p .strip ())
138176 where .append ("event_provider IN %(providers)s" )
177+ return where , params
178+
179+
180+ def build_recent_alerts_sql (
181+ since : str , min_severity : str , providers : str , limit : int
182+ ) -> tuple [str , dict ]:
183+ """Build parameterized SQL for recent alert-class events.
139184
185+ Args:
186+ since: relative or ISO-8601 time expression (parsed via parse_time)
187+ min_severity: minimum severity label, applied in SQL so LIMIT counts matching rows
188+ providers: comma-separated provider names, or empty for all
189+ limit: max rows to return (clamped to 2000)
190+
191+ Returns:
192+ (sql, params) tuple ready for ClickHouseClient.run()
193+ """
194+ where , params = _alert_where (since , min_severity , providers )
195+ params ["limit" ] = max (1 , min (int (limit ), 2000 ))
140196 sql = (
141197 "SELECT event_id, toString(timestamp) AS timestamp, event_provider, "
142- "event_kind, event_action, rule_name, source_ip, source_port, destination_ip, "
198+ "event_kind, event_action, rule_name, "
199+ f"{ SIGNATURE_SQL } AS signature, source_ip, source_port, destination_ip, "
143200 "destination_port, observer_hostname, observer_ingress_zone, "
144201 "observer_egress_zone, ext "
145202 "FROM ssdf.events WHERE "
@@ -149,6 +206,27 @@ def build_recent_alerts_sql(
149206 return sql , params
150207
151208
209+ def build_alert_counts_sql (since : str , min_severity : str , providers : str ) -> tuple [str , dict ]:
210+ """Build SQL counting alert-class events per (provider, observer, signature, severity).
211+
212+ Same gate, severity expression and signature expression as recent_alerts. Asks
213+ for MAX_COUNT_GROUPS + 1 groups so the caller can tell the list was cut.
214+ """
215+ where , params = _alert_where (since , min_severity , providers )
216+ params ["max_groups" ] = MAX_COUNT_GROUPS + 1
217+ sql = (
218+ "SELECT event_provider AS provider, observer_hostname AS observer, "
219+ f"{ SIGNATURE_SQL } AS signature, { SEVERITY_NUM_SQL } AS severity_num, "
220+ "count() AS n, toString(min(events.timestamp)) AS first_seen, "
221+ "toString(max(events.timestamp)) AS last_seen "
222+ "FROM ssdf.events WHERE "
223+ + " AND " .join (where )
224+ + " GROUP BY provider, observer, signature, severity_num"
225+ " ORDER BY severity_num DESC, n DESC LIMIT %(max_groups)s"
226+ )
227+ return sql , params
228+
229+
152230class AlertTools :
153231 """MCP tool surface for alert-class events with normalized severity."""
154232
@@ -186,13 +264,7 @@ def recent_alerts(
186264 continue
187265
188266 # log-derived; wrapped as UntrustedText
189- rule_name = r .get ("rule_name" ) or ""
190- sig = (
191- ext .get ("unifi.ips.signature" )
192- or (rule_name if rule_name not in NO_RULE_NAMES else "" )
193- or r .get ("event_action" )
194- or r .get ("event_kind" )
195- )
267+ sig = r .get ("signature" ) or r .get ("event_kind" )
196268
197269 rows .append (
198270 {
@@ -213,7 +285,7 @@ def recent_alerts(
213285 "ext_subset" : {
214286 k : UntrustedText .from_raw (v ).to_response ()
215287 for k , v in ext .items ()
216- if k .startswith (("unifi.ips." , "panw." , "syslog." ))
288+ if k .startswith (("unifi.ips." , "unifi.event." , " panw." , "syslog." ))
217289 },
218290 }
219291 )
@@ -223,3 +295,42 @@ def recent_alerts(
223295 "row_count" : len (rows ),
224296 "truncated" : len (result .get ("rows" , [])) >= params ["limit" ],
225297 }
298+
299+ def alert_counts (
300+ self , since : str = "now-24h" , min_severity : str = "low" , providers : str = ""
301+ ) -> dict :
302+ """Count alert-class events per (provider, observer, signature, severity).
303+
304+ Args:
305+ since: time window start (ISO-8601 or relative "now-24h" style)
306+ min_severity: minimum severity to include (critical|high|medium|low)
307+ providers: comma-separated provider filter, or empty for all
308+
309+ Returns:
310+ {rows: [{provider, observer, signature, severity, severity_num, count,
311+ first_seen, last_seen}], row_count, truncated}, worst severity first
312+ then highest count; at most MAX_COUNT_GROUPS groups.
313+ """
314+ sql , params = build_alert_counts_sql (since , min_severity , providers )
315+ result = self ._ch .run (sql , params )
316+ labels = {num : label for label , num in SEVERITY_NUM .items ()}
317+
318+ raw_rows = result .get ("rows" , [])
319+ rows = [
320+ {
321+ "provider" : r ["provider" ],
322+ "observer" : UntrustedText .from_raw (r .get ("observer" ) or "" ).to_response (),
323+ "signature" : UntrustedText .from_raw (r .get ("signature" ) or "" ).to_response (),
324+ "severity" : labels .get (r ["severity_num" ], "medium" ),
325+ "severity_num" : r ["severity_num" ],
326+ "count" : r ["n" ],
327+ "first_seen" : r ["first_seen" ],
328+ "last_seen" : r ["last_seen" ],
329+ }
330+ for r in raw_rows [:MAX_COUNT_GROUPS ]
331+ ]
332+ return {
333+ "rows" : rows ,
334+ "row_count" : len (rows ),
335+ "truncated" : len (raw_rows ) > MAX_COUNT_GROUPS ,
336+ }
0 commit comments