Skip to content

Commit 3e044da

Browse files
feat(runtime): add per-project Runtime dashboard, live polling, and alert webhooks
1 parent d3f37ee commit 3e044da

18 files changed

Lines changed: 1322 additions & 28 deletions

File tree

‎docs/REFERENCE.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -690,6 +690,15 @@ secfoo findings export --format sarif --runtime-priority -o findings.sarif
690690
secfoo findings check --fail-on reached:high # CI gate: exit 4 if an open High+ finding is reached in production
691691
```
692692

693+
Per-project live sensor health (healthy vs **Stale** after 3 missed heartbeats), function/route coverage, newly loaded packages, version drift, and reached functions are shown at `/projects/<id>/runtime` (linked from each project page, auto-refreshing every 10s while visible). Configure optional webhook alerts in `~/.secfoo/config.toml`:
694+
695+
```toml
696+
[runtime]
697+
alert_webhook = "https://hooks.example.com/secfoo"
698+
```
699+
700+
When set, alerts fire cleanly once per condition for functions first **Reached from traffic**, **new advisories** against running versions, and sensors going **Stale** (holding finding fingerprint, app, env, and link; never stack samples).
701+
693702
Evidence comes from two places, and the stronger state wins:
694703

695704
- **The local store**, for anything ingested here or by a self-hosted

‎src/secfoo/report/sca.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,14 @@ def findings_with_fingerprints(report_markdown: str) -> list[dict[str, str | Non
274274
}
275275
)
276276
return results
277+
278+
279+
def vulnerability_key(ecosystem: str | None, package: str, version: str, cve_or_issue: str) -> str:
280+
"""Return the opaque hashed routing key for a vulnerability detail page.
281+
282+
Shared between the web dashboard and runtime alerting so package names
283+
containing `/` (npm scopes, Maven coordinates, Go modules) map identically
284+
without coupling `secfoo.runtime` to `secfoo.web`.
285+
"""
286+
raw = f"{ecosystem or 'unknown'}|{package}|{version}|{cve_or_issue}"
287+
return hashlib.blake2b(raw.encode("utf-8"), digest_size=8).hexdigest()

‎src/secfoo/runtime/alerts.py‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
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

‎src/secfoo/runtime/api.py‎

Lines changed: 106 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,25 @@
2626
from datetime import datetime, timezone
2727
from typing import Annotated
2828

29-
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
30-
29+
from fastapi import (
30+
APIRouter,
31+
BackgroundTasks,
32+
Depends,
33+
HTTPException,
34+
Query,
35+
Request,
36+
Response,
37+
)
38+
39+
from secfoo.report.sca import vulnerability_key
3140
from secfoo.runtime import keys as keys_module
32-
from secfoo.runtime.evidence import ingest_events
41+
from secfoo.runtime.alerts import (
42+
clear_alert,
43+
detect_stale_sensors,
44+
dispatch_webhook,
45+
emit_alert,
46+
)
47+
from secfoo.runtime.evidence import ingest_events, is_request_route
3348
from secfoo.runtime.watchlist import build_watchlist
3449
from secfoo.storage.repository import RunRepository
3550
from secfoo.web.security import is_loopback
@@ -178,6 +193,7 @@ def _with_app_env(lines: list[str], app: str | None, env: str | None) -> list[st
178193
@router.post("/events")
179194
async def post_events(
180195
request: Request,
196+
background_tasks: BackgroundTasks,
181197
who: Annotated[_Caller, Depends(caller)],
182198
app: str | None = Query(None, max_length=200),
183199
env: str | None = Query(None, max_length=200),
@@ -186,6 +202,24 @@ async def post_events(
186202
if len(lines) > MAX_BATCH_LINES:
187203
raise _error(413, f"batch over {MAX_BATCH_LINES} lines; flush more often")
188204
report = ingest_events(who.repo.connection, who.project_id, _with_app_env(lines, app, env))
205+
queued = False
206+
if report.hit_fingerprints:
207+
queued |= _notify_newly_reached(
208+
who.repo,
209+
who.project_id,
210+
hit_fingerprints=report.hit_fingerprints,
211+
fallback_app=app,
212+
fallback_env=env,
213+
background_tasks=background_tasks,
214+
)
215+
if detect_stale_sensors(
216+
who.repo.connection,
217+
project_id=who.project_id,
218+
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
219+
):
220+
queued = True
221+
if queued:
222+
who.repo.connection.commit()
189223
return {
190224
"sessions": report.sessions,
191225
"loads": report.loads,
@@ -196,6 +230,64 @@ async def post_events(
196230
}
197231

198232

233+
def _notify_newly_reached(
234+
repo: RunRepository,
235+
project_id: int,
236+
*,
237+
hit_fingerprints: set[str],
238+
fallback_app: str | None,
239+
fallback_env: str | None,
240+
background_tasks: BackgroundTasks,
241+
) -> bool:
242+
if not hit_fingerprints:
243+
return False
244+
findings_by_fp = {f.fingerprint: f for f in repo.list_sca_findings(project_id=project_id, status="open")}
245+
fps = sorted(hit_fingerprints)
246+
placeholders = ",".join("?" * len(fps))
247+
rows = repo.connection.execute(
248+
"SELECT e.finding_fingerprint, e.route, e.symbol, s.app, s.env "
249+
"FROM runtime_evidence e "
250+
"JOIN runtime_sessions s ON s.id = e.session_id "
251+
"LEFT JOIN runtime_alerts_sent a "
252+
" ON a.project_id = e.project_id "
253+
" AND a.event_type = 'reached_from_traffic' "
254+
" AND a.target_key = e.finding_fingerprint "
255+
f"WHERE e.project_id = ? AND a.target_key IS NULL AND e.finding_fingerprint IN ({placeholders}) " # nosec B608 -- fixed ? binds
256+
"ORDER BY COALESCE(e.last_seen, '') DESC, e.id DESC",
257+
[project_id, *fps],
258+
).fetchall()
259+
claimed_fps: set[str] = set()
260+
any_claimed = False
261+
for row in rows:
262+
fp = row["finding_fingerprint"]
263+
if fp in claimed_fps:
264+
continue
265+
route = row["route"] or ""
266+
if not is_request_route(route):
267+
continue
268+
finding = findings_by_fp.get(fp)
269+
link = f"/projects/{project_id}/runtime"
270+
if finding is not None:
271+
cve_or_issue = finding.cve or finding.issue or ""
272+
v_key = vulnerability_key(finding.ecosystem, finding.package, finding.version or "", cve_or_issue)
273+
link = f"/activities/sca-reachability/vulnerabilities/{v_key}"
274+
if emit_alert(
275+
repo.connection,
276+
project_id=project_id,
277+
event_type="reached_from_traffic",
278+
target_key=fp,
279+
app=row["app"] or fallback_app,
280+
env=row["env"] or fallback_env,
281+
finding_fingerprint=fp,
282+
link=link,
283+
details={"route": route, "symbol": row["symbol"]},
284+
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
285+
):
286+
claimed_fps.add(fp)
287+
any_claimed = True
288+
return any_claimed
289+
290+
199291
def _bounded_text(payload: dict, key: str, *, required: bool = False) -> str | None:
200292
value = payload.get(key)
201293
if value is None and not required:
@@ -217,7 +309,11 @@ def _count(payload: dict, key: str) -> int:
217309

218310

219311
@router.post("/heartbeat")
220-
async def post_heartbeat(request: Request, who: Annotated[_Caller, Depends(caller)]):
312+
async def post_heartbeat(
313+
request: Request,
314+
background_tasks: BackgroundTasks,
315+
who: Annotated[_Caller, Depends(caller)],
316+
):
221317
try:
222318
payload = json.loads(await _read_body(request) or b"{}")
223319
except (ValueError, RecursionError): # JSONDecodeError, 4300+ digit ints, deep nesting (#121)
@@ -240,6 +336,12 @@ async def post_heartbeat(request: Request, who: Annotated[_Caller, Depends(calle
240336
(who.project_id, sensor_id, _bounded_text(payload, "version"), _bounded_text(payload, "app"),
241337
_bounded_text(payload, "env"), _count(payload, "instances"), _count(payload, "dropped"), now, now),
242338
)
339+
clear_alert(conn, project_id=who.project_id, event_type="sensor_stale", target_key=sensor_id)
340+
detect_stale_sensors(
341+
conn,
342+
project_id=who.project_id,
343+
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
344+
)
243345
conn.commit()
244346
return {"ok": True, "received_at": now}
245347

‎src/secfoo/runtime/correlation.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
extract_trust_boundaries,
1212
)
1313
from secfoo.report.markdown import read_stored_report
14+
from secfoo.runtime.evidence import is_request_route as _is_request_route
1415
from secfoo.storage.repository import RunRepository
15-
from secfoo.web.sca_runtime import _is_request_route
1616

1717
_HTTP_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ANY", "*"})
1818
_SEVERITY_RANK = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}

0 commit comments

Comments
 (0)