Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,15 @@ secfoo findings export --format sarif --runtime-priority -o findings.sarif
secfoo findings check --fail-on reached:high # CI gate: exit 4 if an open High+ finding is reached in production
```

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`:

```toml
[runtime]
alert_webhook = "https://hooks.example.com/secfoo"
```

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).

Evidence comes from two places, and the stronger state wins:

- **The local store**, for anything ingested here or by a self-hosted
Expand Down
11 changes: 11 additions & 0 deletions src/secfoo/report/sca.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,14 @@ def findings_with_fingerprints(report_markdown: str) -> list[dict[str, str | Non
}
)
return results


def vulnerability_key(ecosystem: str | None, package: str, version: str, cve_or_issue: str) -> str:
"""Return the opaque hashed routing key for a vulnerability detail page.

Shared between the web dashboard and runtime alerting so package names
containing `/` (npm scopes, Maven coordinates, Go modules) map identically
without coupling `secfoo.runtime` to `secfoo.web`.
"""
raw = f"{ecosystem or 'unknown'}|{package}|{version}|{cve_or_issue}"
return hashlib.blake2b(raw.encode("utf-8"), digest_size=8).hexdigest()
189 changes: 189 additions & 0 deletions src/secfoo/runtime/alerts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
"""Optional webhook alerting for runtime monitoring events (#72).

Fires at most once per alert condition (tracked in `runtime_alerts_sent`) to
`[runtime] alert_webhook` in `~/.secfoo/config.toml`:
- `reached_from_traffic`: vulnerable function first hit during live traffic
- `new_advisory`: newly discovered advisory against a running package version
- `sensor_stale`: connected sensor missed >= 3 heartbeats

Payloads carry finding fingerprint, app, env, and a deep link — never stack
samples or source frames.
"""

from __future__ import annotations

import json
import logging
import urllib.error
import urllib.request
from collections.abc import Callable
from datetime import datetime, timezone
from urllib.parse import urlsplit

from secfoo.settings import ConfigError, load_config

logger = logging.getLogger(__name__)

ALERT_TIMEOUT_SECONDS = 5
HEARTBEAT_INTERVAL_SECONDS = 30
MISSED_HEARTBEATS_FOR_STALE = 3
STALE_AFTER_SECONDS = HEARTBEAT_INTERVAL_SECONDS * MISSED_HEARTBEATS_FOR_STALE

Sender = Callable[[str, dict], None]


def parse_iso_timestamp(ts: str | None) -> datetime | None:
"""Parse an ISO-8601 timestamp string into a UTC-aware datetime, or None if invalid."""
if not ts:
return None
try:
dt = datetime.fromisoformat(ts[:-1] + "+00:00" if ts.endswith("Z") else ts)
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
except ValueError:
return None


def post_webhook(url: str, payload: dict) -> None:
"""POST JSON `payload` to user-configured `url` (`http://` or `https://`)."""
if not url.startswith(("https://", "http://")):
raise ValueError("Refusing non-HTTP webhook URL")
body = json.dumps(payload, sort_keys=True).encode("utf-8")
request = urllib.request.Request( # nosec B310 -- scheme validated above from user config
url,
data=body,
headers={"Content-Type": "application/json", "User-Agent": "secfoo-runtime-alerts"},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=ALERT_TIMEOUT_SECONDS) as resp: # nosec B310
resp.read(256)
except (urllib.error.URLError, OSError) as exc:
# Log hostname only: Slack/Teams-style webhook URLs carry secret tokens in the path.
host = urlsplit(url).hostname or "<unknown>"
logger.warning("Runtime alert webhook delivery failed for host %s: %s", host, exc)


def dispatch_webhook(url: str, payload: dict) -> None:
"""Background-task wrapper so monkeypatched `post_webhook` is resolved at delivery time."""
post_webhook(url, payload)


def configured_webhook_url() -> str | None:
try:
return load_config().runtime_alert_webhook
except ConfigError as exc:
logger.warning("Ignoring invalid runtime webhook config: %s", exc)
return None


def _claim_alert(conn, *, project_id: int, event_type: str, target_key: str) -> bool:
"""Record a deduplication claim within the caller's active transaction."""
now = datetime.now(timezone.utc).isoformat()
cur = conn.execute(
"INSERT OR IGNORE INTO runtime_alerts_sent (project_id, event_type, target_key, sent_at) "
"VALUES (?, ?, ?, ?)",
(project_id, event_type, target_key, now),
)
return cur.rowcount > 0


def clear_alert(conn, *, project_id: int, event_type: str, target_key: str) -> None:
"""Reset deduplication once a sensor recovers (caller owns transaction commit)."""
conn.execute(
"DELETE FROM runtime_alerts_sent WHERE project_id = ? AND event_type = ? AND target_key = ?",
(project_id, event_type, target_key),
)


def emit_alert(
conn,
*,
project_id: int,
event_type: str,
target_key: str,
app: str | None = None,
env: str | None = None,
finding_fingerprint: str | None = None,
link: str,
details: dict[str, object] | None = None,
webhook_url: str | None = None,
sender: Sender | None = None,
) -> bool:
"""Deduplicate and schedule/deliver a sanitized runtime alert payload.

Claims the row on `conn` without committing so the caller keeps control of its
transaction boundary; pass `sender` (e.g. FastAPI `BackgroundTasks`) to run the
network POST outside the caller's request handler.
"""
url = webhook_url if webhook_url is not None else configured_webhook_url()
if not url:
return False
if not _claim_alert(conn, project_id=project_id, event_type=event_type, target_key=target_key):
return False
payload: dict[str, object] = {
"event": event_type,
"project_id": project_id,
"finding_fingerprint": finding_fingerprint,
"app": app,
"env": env,
"link": link,
"sent_at": datetime.now(timezone.utc).isoformat(),
}
if details:
# Never forward stack traces or entry frames in webhook payloads.
safe_details = {k: v for k, v in details.items() if k not in {"stack_sample", "entry_frame"}}
if safe_details:
payload["details"] = safe_details
(sender or dispatch_webhook)(url, payload)
return True


def detect_stale_sensors(
conn,
*,
project_id: int | None = None,
now: datetime | None = None,
sender: Sender | None = None,
) -> list[str]:
"""Emit `sensor_stale` alerts for sensors whose heartbeat exceeded STALE_AFTER_SECONDS.

Caller owns transaction commit on `conn`; pass `sender` to deliver webhooks off-loop.
Returns the list of sensor IDs newly marked stale.
"""
if not configured_webhook_url():
return []
ref_now = now or datetime.now(timezone.utc)
if ref_now.tzinfo is None:
ref_now = ref_now.replace(tzinfo=timezone.utc)
query = (
"SELECT s.project_id, s.sensor_id, s.app, s.env, s.last_heartbeat_at "
"FROM runtime_sensors s "
"LEFT JOIN runtime_alerts_sent a "
"ON a.project_id = s.project_id AND a.event_type = 'sensor_stale' AND a.target_key = s.sensor_id "
"WHERE a.target_key IS NULL"
)
params: list[object] = []
if project_id is not None:
query += " AND s.project_id = ?"
params.append(project_id)
rows = conn.execute(query, params).fetchall()
alerted: list[str] = []
for s in rows:
last_hb = parse_iso_timestamp(s["last_heartbeat_at"])
seconds_since_hb = (ref_now - last_hb).total_seconds() if last_hb else float("inf")
if seconds_since_hb <= STALE_AFTER_SECONDS:
continue
pid = int(s["project_id"])
if emit_alert(
conn,
project_id=pid,
event_type="sensor_stale",
target_key=s["sensor_id"],
app=s["app"],
env=s["env"],
link=f"/projects/{pid}/runtime",
details={"sensor_id": s["sensor_id"], "last_heartbeat_at": s["last_heartbeat_at"]},
sender=sender,
):
alerted.append(str(s["sensor_id"]))
return alerted
110 changes: 106 additions & 4 deletions src/secfoo/runtime/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@
from datetime import datetime, timezone
from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response

from fastapi import (
APIRouter,
BackgroundTasks,
Depends,
HTTPException,
Query,
Request,
Response,
)

from secfoo.report.sca import vulnerability_key
from secfoo.runtime import keys as keys_module
from secfoo.runtime.evidence import ingest_events
from secfoo.runtime.alerts import (
clear_alert,
detect_stale_sensors,
dispatch_webhook,
emit_alert,
)
from secfoo.runtime.evidence import ingest_events, is_request_route
from secfoo.runtime.watchlist import build_watchlist
from secfoo.storage.repository import RunRepository
from secfoo.web.security import is_loopback
Expand Down Expand Up @@ -178,6 +193,7 @@ def _with_app_env(lines: list[str], app: str | None, env: str | None) -> list[st
@router.post("/events")
async def post_events(
request: Request,
background_tasks: BackgroundTasks,
who: Annotated[_Caller, Depends(caller)],
app: str | None = Query(None, max_length=200),
env: str | None = Query(None, max_length=200),
Expand All @@ -186,6 +202,24 @@ async def post_events(
if len(lines) > MAX_BATCH_LINES:
raise _error(413, f"batch over {MAX_BATCH_LINES} lines; flush more often")
report = ingest_events(who.repo.connection, who.project_id, _with_app_env(lines, app, env))
queued = False
if report.hit_fingerprints:
queued |= _notify_newly_reached(
who.repo,
who.project_id,
hit_fingerprints=report.hit_fingerprints,
fallback_app=app,
fallback_env=env,
background_tasks=background_tasks,
)
if detect_stale_sensors(
who.repo.connection,
project_id=who.project_id,
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
):
queued = True
if queued:
who.repo.connection.commit()
return {
"sessions": report.sessions,
"loads": report.loads,
Expand All @@ -196,6 +230,64 @@ async def post_events(
}


def _notify_newly_reached(
repo: RunRepository,
project_id: int,
*,
hit_fingerprints: set[str],
fallback_app: str | None,
fallback_env: str | None,
background_tasks: BackgroundTasks,
) -> bool:
if not hit_fingerprints:
return False
findings_by_fp = {f.fingerprint: f for f in repo.list_sca_findings(project_id=project_id, status="open")}
fps = sorted(hit_fingerprints)
placeholders = ",".join("?" * len(fps))
rows = repo.connection.execute(
"SELECT e.finding_fingerprint, e.route, e.symbol, s.app, s.env "
"FROM runtime_evidence e "
"JOIN runtime_sessions s ON s.id = e.session_id "
"LEFT JOIN runtime_alerts_sent a "
" ON a.project_id = e.project_id "
" AND a.event_type = 'reached_from_traffic' "
" AND a.target_key = e.finding_fingerprint "
f"WHERE e.project_id = ? AND a.target_key IS NULL AND e.finding_fingerprint IN ({placeholders}) " # nosec B608 -- fixed ? binds
"ORDER BY COALESCE(e.last_seen, '') DESC, e.id DESC",
[project_id, *fps],
).fetchall()
claimed_fps: set[str] = set()
any_claimed = False
for row in rows:
fp = row["finding_fingerprint"]
if fp in claimed_fps:
continue
route = row["route"] or ""
if not is_request_route(route):
continue
finding = findings_by_fp.get(fp)
link = f"/projects/{project_id}/runtime"
if finding is not None:
cve_or_issue = finding.cve or finding.issue or ""
v_key = vulnerability_key(finding.ecosystem, finding.package, finding.version or "", cve_or_issue)
link = f"/activities/sca-reachability/vulnerabilities/{v_key}"
if emit_alert(
repo.connection,
project_id=project_id,
event_type="reached_from_traffic",
target_key=fp,
app=row["app"] or fallback_app,
env=row["env"] or fallback_env,
finding_fingerprint=fp,
link=link,
details={"route": route, "symbol": row["symbol"]},
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
):
claimed_fps.add(fp)
any_claimed = True
return any_claimed


def _bounded_text(payload: dict, key: str, *, required: bool = False) -> str | None:
value = payload.get(key)
if value is None and not required:
Expand All @@ -217,7 +309,11 @@ def _count(payload: dict, key: str) -> int:


@router.post("/heartbeat")
async def post_heartbeat(request: Request, who: Annotated[_Caller, Depends(caller)]):
async def post_heartbeat(
request: Request,
background_tasks: BackgroundTasks,
who: Annotated[_Caller, Depends(caller)],
):
try:
payload = json.loads(await _read_body(request) or b"{}")
except (ValueError, RecursionError): # JSONDecodeError, 4300+ digit ints, deep nesting (#121)
Expand All @@ -240,6 +336,12 @@ async def post_heartbeat(request: Request, who: Annotated[_Caller, Depends(calle
(who.project_id, sensor_id, _bounded_text(payload, "version"), _bounded_text(payload, "app"),
_bounded_text(payload, "env"), _count(payload, "instances"), _count(payload, "dropped"), now, now),
)
clear_alert(conn, project_id=who.project_id, event_type="sensor_stale", target_key=sensor_id)
detect_stale_sensors(
conn,
project_id=who.project_id,
sender=lambda u, p: background_tasks.add_task(dispatch_webhook, u, p),
)
conn.commit()
return {"ok": True, "received_at": now}

Expand Down
2 changes: 1 addition & 1 deletion src/secfoo/runtime/correlation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
extract_trust_boundaries,
)
from secfoo.report.markdown import read_stored_report
from secfoo.runtime.evidence import is_request_route as _is_request_route
from secfoo.storage.repository import RunRepository
from secfoo.web.sca_runtime import _is_request_route

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