From 3e044daa271e3165ac13a0eadc43d2ea2a425593 Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Sun, 29 Nov 2026 08:25:59 +0530 Subject: [PATCH] feat(runtime): add per-project Runtime dashboard, live polling, and alert webhooks --- docs/REFERENCE.md | 9 + src/secfoo/report/sca.py | 11 + src/secfoo/runtime/alerts.py | 189 +++++++++ src/secfoo/runtime/api.py | 110 +++++- src/secfoo/runtime/correlation.py | 2 +- src/secfoo/runtime/evidence.py | 8 + src/secfoo/runtime/inventory.py | 22 +- src/secfoo/settings.py | 14 + src/secfoo/storage/schema.sql | 10 + src/secfoo/web/app.py | 46 ++- src/secfoo/web/routes/projects.py | 27 +- src/secfoo/web/runtime_dashboard.py | 297 ++++++++++++++ src/secfoo/web/sca_dashboard.py | 16 +- src/secfoo/web/sca_runtime.py | 7 +- src/secfoo/web/static/js/runtime-live.js | 37 ++ src/secfoo/web/templates/project.html | 10 +- .../web/templates/projects_runtime.html | 165 ++++++++ tests/test_web/test_runtime_dashboard.py | 370 ++++++++++++++++++ 18 files changed, 1322 insertions(+), 28 deletions(-) create mode 100644 src/secfoo/runtime/alerts.py create mode 100644 src/secfoo/web/runtime_dashboard.py create mode 100644 src/secfoo/web/static/js/runtime-live.js create mode 100644 src/secfoo/web/templates/projects_runtime.html create mode 100644 tests/test_web/test_runtime_dashboard.py diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 9ff4cff..79e76c7 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -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//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 diff --git a/src/secfoo/report/sca.py b/src/secfoo/report/sca.py index 8c3b993..45d2d0a 100644 --- a/src/secfoo/report/sca.py +++ b/src/secfoo/report/sca.py @@ -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() diff --git a/src/secfoo/runtime/alerts.py b/src/secfoo/runtime/alerts.py new file mode 100644 index 0000000..b4f3883 --- /dev/null +++ b/src/secfoo/runtime/alerts.py @@ -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 "" + 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 diff --git a/src/secfoo/runtime/api.py b/src/secfoo/runtime/api.py index 93c97a1..4f223fd 100644 --- a/src/secfoo/runtime/api.py +++ b/src/secfoo/runtime/api.py @@ -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 @@ -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), @@ -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, @@ -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: @@ -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) @@ -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} diff --git a/src/secfoo/runtime/correlation.py b/src/secfoo/runtime/correlation.py index 6a1b32b..6a5ce07 100644 --- a/src/secfoo/runtime/correlation.py +++ b/src/secfoo/runtime/correlation.py @@ -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} diff --git a/src/secfoo/runtime/evidence.py b/src/secfoo/runtime/evidence.py index 02200b2..214c929 100644 --- a/src/secfoo/runtime/evidence.py +++ b/src/secfoo/runtime/evidence.py @@ -51,6 +51,12 @@ _FRAME_RE = re.compile(rf"^\S.{{0,{MAX_TEXT - 8}}}:\d+$") _CONCRETE_URL_RE = re.compile(r"://|[?#]") +_NO_REQUEST_ROUTES = ("", "unknown", "startup") + + +def is_request_route(route: str) -> bool: + """Return True if `route` represents an inbound request rather than startup/unknown/background job.""" + return route not in _NO_REQUEST_ROUTES and not route.startswith("job:") class EvidenceError(ValueError): @@ -64,6 +70,7 @@ class IngestReport: hits: int = 0 skipped: list[tuple[int, str]] = field(default_factory=list) # (line number, reason) unknown_fingerprints: set[str] = field(default_factory=set) + hit_fingerprints: set[str] = field(default_factory=set) @property def stored(self) -> int: @@ -348,6 +355,7 @@ def is_finding(fingerprint: str) -> bool: elif is_finding(event["finding_fingerprint"]): _store_hit(conn, project_id, session_id, event) report.hits += 1 + report.hit_fingerprints.add(event["finding_fingerprint"]) else: report.unknown_fingerprints.add(event["finding_fingerprint"]) report.skipped.append( diff --git a/src/secfoo/runtime/inventory.py b/src/secfoo/runtime/inventory.py index 2b5ce62..0bff635 100644 --- a/src/secfoo/runtime/inventory.py +++ b/src/secfoo/runtime/inventory.py @@ -28,6 +28,7 @@ from secfoo import osv from secfoo.report.markdown import read_stored_report from secfoo.report.sca import SKILL_ID, inventory_lookup +from secfoo.runtime.alerts import emit_alert DEFAULT_BASELINE_HOURS = 24 OSV_BATCH_URL = "https://api.osv.dev/v1/querybatch" @@ -187,7 +188,26 @@ def analyze(repo, project_id: int, *, app: str | None = None, env: str | None = item.status, item.scanned_versions = "scanned", sorted(versions) for advisory in item.advisories: if advisory not in known.get((item.ecosystem, item.package.lower()), set()): - report.raised.append(_raise(conn, project_id, "new_advisory", item, advisory)) + raised_row = _raise(conn, project_id, "new_advisory", item, advisory) + report.raised.append(raised_row) + first_app = min(item.apps) if item.apps else "" + app_name, _, env_name = first_app.partition("/") if first_app else ("", "", "") + emit_alert( + conn, + project_id=project_id, + event_type="new_advisory", + target_key=f"{item.ecosystem}|{item.package}|{item.version}|{advisory}", + app=app_name or app, + env=env_name or env, + finding_fingerprint=advisory, + link=f"/projects/{project_id}/runtime", + details={ + "ecosystem": item.ecosystem, + "package": item.package, + "version": item.version, + "advisory": advisory, + }, + ) # New in production: first seen after its app's baseline window. seen = _parse(item.first_seen) for label in item.apps: diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index f2157e7..a4cfa3e 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -89,6 +89,8 @@ class SecfooConfig: agent_tool_call_budget: dict[str, int] = field(default_factory=dict) # [skills] paths -- extra folders of custom skill definitions (#79). skill_paths: list[str] = field(default_factory=list) + # [runtime] alert_webhook -- optional webhook URL for runtime alerts (#72). + runtime_alert_webhook: str | None = None MCP_TRANSPORTS = ("stdio", "sse", "http") @@ -311,6 +313,17 @@ def load_config(path: Path | None = None) -> SecfooConfig: if not isinstance(memory_enabled, bool): raise ConfigError("memory.enabled must be true or false") + runtime_raw = data.get("runtime", {}) + if not isinstance(runtime_raw, dict): + raise ConfigError("[runtime] must be a table") + alert_webhook = runtime_raw.get("alert_webhook") + if alert_webhook is not None: + if not isinstance(alert_webhook, str) or not alert_webhook.strip(): + raise ConfigError("runtime.alert_webhook must be a non-empty URL string") + alert_webhook = alert_webhook.strip() + if not alert_webhook.startswith(("https://", "http://")): + raise ConfigError("runtime.alert_webhook must start with https:// or http://") + return SecfooConfig( defaults=defaults, mcp_servers=servers, @@ -321,6 +334,7 @@ def load_config(path: Path | None = None) -> SecfooConfig: agent_max_input_tokens=agent_max_input_tokens, agent_tool_call_budget=agent_tool_call_budget, skill_paths=list(skill_paths), + runtime_alert_webhook=alert_webhook, ) diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 35d4786..fa4a063 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -502,3 +502,13 @@ CREATE TABLE IF NOT EXISTS runtime_findings ( last_seen_at TEXT NOT NULL, UNIQUE (project_id, kind, ecosystem, package, version, advisory) ); + +-- #72: tracks sent webhook alerts so steady-state stale sensors or repeat hits +-- do not flood `[runtime] alert_webhook` on every poll/heartbeat cycle. +CREATE TABLE IF NOT EXISTS runtime_alerts_sent ( + project_id INTEGER NOT NULL REFERENCES projects(id), + event_type TEXT NOT NULL, + target_key TEXT NOT NULL, + sent_at TEXT NOT NULL, + PRIMARY KEY (project_id, event_type, target_key) +); diff --git a/src/secfoo/web/app.py b/src/secfoo/web/app.py index 2e40e98..edb927d 100644 --- a/src/secfoo/web/app.py +++ b/src/secfoo/web/app.py @@ -1,6 +1,9 @@ from __future__ import annotations +import logging +import threading from collections.abc import Iterable +from contextlib import asynccontextmanager from pathlib import Path from fastapi import FastAPI @@ -9,6 +12,13 @@ from secfoo.config import STORE_DIR from secfoo.runtime import api as runtime_api +from secfoo.runtime.alerts import ( + HEARTBEAT_INTERVAL_SECONDS, + configured_webhook_url, + detect_stale_sensors, + dispatch_webhook, +) +from secfoo.storage.repository import RunRepository from secfoo.web import security from secfoo.web.routes import ( activities, @@ -21,6 +31,7 @@ third_party, ) +logger = logging.getLogger(__name__) STATIC_DIR = Path(__file__).parent / "static" # Mermaid is an optional asset (~3.6MB), deliberately not shipped in the @@ -37,10 +48,43 @@ def mermaid_bundle_available() -> bool: return MERMAID_BUNDLE.is_file() +@asynccontextmanager +async def _lifespan(_app: FastAPI): + """Run periodic runtime sensor health checks outside GET request handlers.""" + stop_event = threading.Event() + + def _check_stale_once() -> None: + pending: list[tuple[str, dict]] = [] + with RunRepository() as repo: + detect_stale_sensors( + repo.connection, + sender=lambda url, payload: pending.append((url, payload)), + ) + repo.connection.commit() + for url, payload in pending: + dispatch_webhook(url, payload) + + def _watch_stale_sensors() -> None: + while not stop_event.wait(HEARTBEAT_INTERVAL_SECONDS): + if not configured_webhook_url(): + continue + try: + _check_stale_once() + except Exception: + logger.exception("Periodic runtime stale-sensor check failed") + + watcher = threading.Thread(target=_watch_stale_sensors, name="secfoo-stale-sensor-watch", daemon=True) + watcher.start() + try: + yield + finally: + stop_event.set() + + def create_app( *, bind_host: str = "127.0.0.1", allow_insecure_runtime: bool = False, allow_hosts: Iterable[str] = () ) -> FastAPI: - app = FastAPI(title="secfoo dashboard") + app = FastAPI(title="secfoo dashboard", lifespan=_lifespan) # Read by the runtime ingest API (#66): on a non-loopback bind it refuses # API keys over plain HTTP unless the operator opted in. app.state.bind_host = bind_host diff --git a/src/secfoo/web/routes/projects.py b/src/secfoo/web/routes/projects.py index 34676af..449413b 100644 --- a/src/secfoo/web/routes/projects.py +++ b/src/secfoo/web/routes/projects.py @@ -6,13 +6,14 @@ from pathlib import Path from fastapi import APIRouter, HTTPException, Request -from fastapi.responses import RedirectResponse +from fastapi.responses import JSONResponse, RedirectResponse from secfoo.context_sources import ContextSource from secfoo.runner import execute_runs from secfoo.runtime.correlation import correlate_project_traffic from secfoo.settings import ConfigError, load_config from secfoo.storage.repository import RunRepository +from secfoo.web import runtime_dashboard from secfoo.web.templating import ordered_skills, templates router = APIRouter() @@ -27,6 +28,7 @@ def project_detail(request: Request, project_id: int, tm_rerun: str | None = Non runs = repo.list_runs(project_id=project_id, limit=200) coverage = repo.project_activity_coverage(project_id) tm_correlation = correlate_project_traffic(repo, project_id) + runtime_dash = runtime_dashboard.build(repo, project_id) # Every known activity, covered or not -- an activity this project has # never had run is exactly the gap worth showing. @@ -44,6 +46,7 @@ def project_detail(request: Request, project_id: int, tm_rerun: str | None = Non "activities": activities, "tm_correlation": tm_correlation, "tm_rerun": tm_rerun, + "runtime_dash": runtime_dash, }, ) @@ -96,3 +99,25 @@ def _run_and_cleanup() -> None: threading.Thread(target=_run_and_cleanup, daemon=True).start() return RedirectResponse(f"/projects/{project_id}?tm_rerun=started", status_code=303) + + +@router.get("/projects/{project_id}/runtime") +def project_runtime(request: Request, project_id: int): + with RunRepository() as repo: + dash = runtime_dashboard.build(repo, project_id) + if dash is None: + raise HTTPException(status_code=404, detail="Project not found") + return templates.TemplateResponse( + request, + "projects_runtime.html", + {"dash": dash}, + ) + + +@router.get("/projects/{project_id}/runtime.json") +def project_runtime_json(project_id: int): + with RunRepository() as repo: + dash = runtime_dashboard.build(repo, project_id) + if dash is None: + raise HTTPException(status_code=404, detail="Project not found") + return JSONResponse(dash.as_json()) diff --git a/src/secfoo/web/runtime_dashboard.py b/src/secfoo/web/runtime_dashboard.py new file mode 100644 index 0000000..7cabdfa --- /dev/null +++ b/src/secfoo/web/runtime_dashboard.py @@ -0,0 +1,297 @@ +"""Per-project runtime health, live coverage, activity feed, and alerts (#72).""" + +from __future__ import annotations + +import json +from collections import defaultdict +from dataclasses import dataclass +from datetime import datetime, timezone + +from secfoo import osv +from secfoo.report.sca import vulnerability_key +from secfoo.runtime.alerts import ( + STALE_AFTER_SECONDS, + configured_webhook_url, + parse_iso_timestamp, +) +from secfoo.runtime.evidence import is_request_route +from secfoo.storage.repository import RunRepository + + +def _format_window(minutes: float) -> str: + if minutes >= 1440: + return f"{minutes / 1440:.1f}d" + if minutes >= 60: + return f"{minutes / 60:.1f}h" + if minutes >= 1: + return f"{minutes:.0f}m" + if minutes > 0: + return "<1m" + return "—" + + +@dataclass(frozen=True) +class RuntimeDashboard: + project_id: int + project_display_name: str + sensors: list[dict[str, object]] + healthy_count: int + stale_count: int + functions_executed: int + functions_total: int + coverage_pct: int | None + routes_seen: list[dict[str, object]] + newly_loaded_packages: list[dict[str, object]] + runtime_findings: list[dict[str, object]] + reached_functions: list[dict[str, object]] + alert_webhook_configured: bool + + def as_json(self) -> dict[str, object]: + return { + "project_id": self.project_id, + "project_display_name": self.project_display_name, + "sensors": self.sensors, + "healthy_count": self.healthy_count, + "stale_count": self.stale_count, + "coverage": { + "functions_executed": self.functions_executed, + "functions_total": self.functions_total, + "percent": self.coverage_pct, + "routes_seen": self.routes_seen, + }, + "newly_loaded_packages": self.newly_loaded_packages, + "runtime_findings": self.runtime_findings, + "reached_functions": self.reached_functions, + "alert_webhook_configured": self.alert_webhook_configured, + } + + +def build( + repo: RunRepository, + project_id: int, + *, + now: datetime | None = None, +) -> RuntimeDashboard | None: + """Build read-only sensor health, live coverage, and recent activity state for `project_id`.""" + project = repo.get_project(project_id) + if project is None: + return None + + ref_now = now or datetime.now(timezone.utc) + if ref_now.tzinfo is None: + ref_now = ref_now.replace(tzinfo=timezone.utc) + conn = repo.connection + + sca_findings = repo.list_sca_findings(project_id=project_id) + sca_by_fp = {f.fingerprint: f for f in sca_findings} + sca_by_pkg: dict[tuple[str, str], str] = {} + for f in sca_findings: + eco = (osv.normalize_ecosystem(f.ecosystem) or f.ecosystem or "").lower() + key = vulnerability_key( + f.ecosystem, f.package, f.version or "", f.cve or f.issue or "" + ) + sca_by_pkg.setdefault((eco, f.package.lower()), f"/activities/sca-reachability/vulnerabilities/{key}") + sca_by_pkg.setdefault(("", f.package.lower()), f"/activities/sca-reachability/vulnerabilities/{key}") + + sessions_rows = conn.execute( + "SELECT id, app, env, started_at, ended_at, app_functions_total, app_functions_executed " + "FROM runtime_sessions WHERE project_id = ? ORDER BY COALESCE(started_at, '') DESC", + (project_id,), + ).fetchall() + + # Observation windows & hit counts per (app, env) and overall coverage + window_by_app_env: dict[tuple[str, str], tuple[datetime | None, datetime | None]] = {} + functions_total = 0 + functions_executed = 0 + for s in sessions_rows: + functions_total = max(functions_total, int(s["app_functions_total"] or 0)) + functions_executed = max(functions_executed, int(s["app_functions_executed"] or 0)) + s_start = parse_iso_timestamp(s["started_at"]) + s_end = parse_iso_timestamp(s["ended_at"]) or ref_now + app_key = (s["app"] or "", s["env"] or "") + prev_start, prev_end = window_by_app_env.get(app_key, (None, None)) + if s_start and (prev_start is None or s_start < prev_start): + prev_start = s_start + if s_end and (prev_end is None or s_end > prev_end): + prev_end = s_end + window_by_app_env[app_key] = (prev_start, prev_end) + + hits_by_app_env: dict[tuple[str, str], int] = defaultdict(int) + route_stats: dict[str, dict[str, object]] = {} + reached_functions: list[dict[str, object]] = [] + ev_rows = conn.execute( + "SELECT e.finding_fingerprint, e.symbol, e.route, e.auth, e.count, e.last_seen, s.app, s.env " + "FROM runtime_evidence e JOIN runtime_sessions s ON s.id = e.session_id " + "WHERE e.project_id = ? ORDER BY COALESCE(e.last_seen, '') DESC, e.count DESC", + (project_id,), + ).fetchall() + for row in ev_rows: + hits_by_app_env[(row["app"] or "", row["env"] or "")] += int(row["count"] or 0) + route = row["route"] or "" + fp = row["finding_fingerprint"] + finding = sca_by_fp.get(fp) + if finding is not None: + v_key = vulnerability_key( + finding.ecosystem, finding.package, finding.version or "", finding.cve or finding.issue or "" + ) + link = f"/activities/sca-reachability/vulnerabilities/{v_key}" + pkg_label = f"{finding.package}@{finding.version or '?'}" + severity = finding.severity + else: + link = "/activities/sca-reachability" + pkg_label = row["symbol"] + severity = "unknown" + + if is_request_route(route): + r_entry = route_stats.setdefault( + route, {"route": route, "hits": 0, "auth_states": set(), "findings": set()} + ) + r_entry["hits"] = int(r_entry["hits"]) + int(row["count"] or 0) + if row["auth"]: + r_entry["auth_states"].add(row["auth"]) + r_entry["findings"].add(fp) + reached_functions.append( + { + "finding_fingerprint": fp, + "package": pkg_label, + "severity": severity, + "symbol": row["symbol"], + "route": route, + "auth": row["auth"] or "unknown", + "count": int(row["count"] or 0), + "last_seen": row["last_seen"] or "", + "link": link, + } + ) + + routes_seen = sorted( + ( + { + "route": r["route"], + "hits": r["hits"], + "auth_states": sorted(r["auth_states"]), + "findings_count": len(r["findings"]), + } + for r in route_stats.values() + ), + key=lambda r: int(r["hits"]), + reverse=True, + ) + + sensors_rows = conn.execute( + "SELECT sensor_id, version, app, env, instances, dropped_total, first_seen_at, last_heartbeat_at " + "FROM runtime_sensors WHERE project_id = ? ORDER BY last_heartbeat_at DESC, sensor_id ASC", + (project_id,), + ).fetchall() + sensors: list[dict[str, object]] = [] + healthy_count = 0 + stale_count = 0 + for s in sensors_rows: + last_hb = parse_iso_timestamp(s["last_heartbeat_at"]) + first_seen = parse_iso_timestamp(s["first_seen_at"]) + seconds_since_hb = (ref_now - last_hb).total_seconds() if last_hb else float("inf") + is_stale = seconds_since_hb > STALE_AFTER_SECONDS + status = "stale" if is_stale else "healthy" + if is_stale: + stale_count += 1 + else: + healthy_count += 1 + + app_name = s["app"] or "" + env_name = s["env"] or "" + win_start, win_end = window_by_app_env.get((app_name, env_name), (None, None)) + start_dt = min(d for d in (first_seen, win_start) if d is not None) if (first_seen or win_start) else None + end_dt = max(d for d in (last_hb, win_end) if d is not None) if (last_hb or win_end) else ref_now + obs_minutes = max((end_dt - start_dt).total_seconds() / 60.0, 0.0) if start_dt else 0.0 + total_hits = hits_by_app_env.get((app_name, env_name), 0) + epm = round(total_hits / max(obs_minutes, 1.0), 1) if total_hits else 0.0 + + sensors.append( + { + "sensor_id": s["sensor_id"], + "app": app_name or "—", + "env": env_name or "—", + "version": s["version"] or "—", + "instances": s["instances"] if s["instances"] is not None else "—", + "last_heartbeat_at": s["last_heartbeat_at"], + "events_per_minute": epm, + "dropped_total": int(s["dropped_total"] or 0), + "observation_window": _format_window(obs_minutes), + "status": status, + } + ) + + pkg_rows = conn.execute( + "SELECT p.ecosystem, p.package, p.version, p.first_seen, s.app, s.env " + "FROM runtime_packages p JOIN runtime_sessions s ON s.id = p.session_id " + "WHERE p.project_id = ? ORDER BY COALESCE(p.first_seen, '') DESC, p.id DESC LIMIT 30", + (project_id,), + ).fetchall() + newly_loaded_packages = [ + { + "ecosystem": r["ecosystem"], + "package": r["package"], + "version": r["version"], + "app": r["app"] or "—", + "env": r["env"] or "—", + "first_seen": r["first_seen"] or "", + "link": ( + sca_by_pkg.get(((r["ecosystem"] or "").lower(), r["package"].lower())) + or sca_by_pkg.get(("", r["package"].lower())) + or "/activities/sca-reachability" + ), + } + for r in pkg_rows + ] + + rf_rows = conn.execute( + "SELECT kind, ecosystem, package, version, advisory, scanned_versions, apps, last_seen_at " + "FROM runtime_findings WHERE project_id = ? ORDER BY last_seen_at DESC, id DESC LIMIT 50", + (project_id,), + ).fetchall() + runtime_findings: list[dict[str, object]] = [] + for r in rf_rows: + try: + scanned = json.loads(r["scanned_versions"] or "[]") + except ValueError: + scanned = [] + try: + apps = json.loads(r["apps"] or "[]") + except ValueError: + apps = [] + link = ( + sca_by_pkg.get(((r["ecosystem"] or "").lower(), r["package"].lower())) + or sca_by_pkg.get(("", r["package"].lower())) + or "/activities/sca-reachability" + ) + runtime_findings.append( + { + "kind": r["kind"], + "ecosystem": r["ecosystem"], + "package": r["package"], + "version": r["version"], + "advisory": r["advisory"], + "scanned_versions": ", ".join(scanned) if isinstance(scanned, list) and scanned else "—", + "apps": ", ".join(apps) if isinstance(apps, list) and apps else "—", + "last_seen_at": r["last_seen_at"], + "link": link, + } + ) + + coverage_pct = round(functions_executed / functions_total * 100) if functions_total > 0 else None + + return RuntimeDashboard( + project_id=project_id, + project_display_name=project.display_name, + sensors=sensors, + healthy_count=healthy_count, + stale_count=stale_count, + functions_executed=functions_executed, + functions_total=functions_total, + coverage_pct=coverage_pct, + routes_seen=routes_seen, + newly_loaded_packages=newly_loaded_packages, + runtime_findings=runtime_findings, + reached_functions=reached_functions, + alert_webhook_configured=bool(configured_webhook_url()), + ) diff --git a/src/secfoo/web/sca_dashboard.py b/src/secfoo/web/sca_dashboard.py index a64eb6f..eb7ea0d 100644 --- a/src/secfoo/web/sca_dashboard.py +++ b/src/secfoo/web/sca_dashboard.py @@ -11,7 +11,6 @@ from __future__ import annotations -import hashlib from collections import Counter from dataclasses import dataclass, field @@ -24,6 +23,7 @@ findings_with_fingerprints, inventory_lookup, resolve_ecosystem, + vulnerability_key, ) from secfoo.runtime.correlation import TrafficCorrelation, correlate_project_traffic from secfoo.storage.repository import RunRepository @@ -35,19 +35,7 @@ _REACHABILITY_RANK = {"not reachable": 0, "conditionally reachable": 1, "reachable": 2} _SEVERITY_RANK = {"low": 0, "medium": 1, "high": 2} - -def _vulnerability_key(ecosystem: str | None, package: str, version: str, cve_or_issue: str) -> str: - """One opaque hashed routing key, whether or not a real OSV id exists - -- package names aren't safe URL segments (scoped npm `@scope/pkg`, - Maven groupIds, and Go module paths all contain literal "/"), so a - composite path would either break routing or need per-consumer - percent-encoding. Same (ecosystem, package, version, cve) always - collapses to the same key across projects; two LLM-only "unverified" - findings only collapse if their issue text actually matches -- there's - no stable identity to merge unverified narratives by otherwise. - """ - raw = f"{ecosystem or 'unknown'}|{package}|{version}|{cve_or_issue}" - return hashlib.blake2b(raw.encode("utf-8"), digest_size=8).hexdigest() +_vulnerability_key = vulnerability_key @dataclass diff --git a/src/secfoo/web/sca_runtime.py b/src/secfoo/web/sca_runtime.py index c6c5e2e..4aef54d 100644 --- a/src/secfoo/web/sca_runtime.py +++ b/src/secfoo/web/sca_runtime.py @@ -39,12 +39,9 @@ "not_observed": "badge--neutral", "none": "badge--neutral", } -# A hit on one of these "routes" had no inbound request behind it. -_NO_REQUEST_ROUTES = ("", "unknown", "startup") +from secfoo.runtime.evidence import is_request_route - -def _is_request_route(route: str) -> bool: - return route not in _NO_REQUEST_ROUTES and not route.startswith("job:") +_is_request_route = is_request_route def _parse(ts: str | None) -> datetime | None: diff --git a/src/secfoo/web/static/js/runtime-live.js b/src/secfoo/web/static/js/runtime-live.js new file mode 100644 index 0000000..f1f3c99 --- /dev/null +++ b/src/secfoo/web/static/js/runtime-live.js @@ -0,0 +1,37 @@ +/* Live polling for the per-project Runtime monitoring page (#72): + refreshes /projects/{id}/runtime.json every 10s while the tab is visible. */ +(function () { + var root = document.getElementById("runtime-root"); + if (!root) return; + var url = root.getAttribute("data-runtime-poll-url"); + if (!url) return; + + function setText(id, value) { + var el = document.getElementById(id); + if (el) el.textContent = String(value); + } + + function refresh() { + if (document.visibilityState !== "visible") return; + fetch(url, { headers: { Accept: "application/json" } }) + .then(function (resp) { + return resp.ok ? resp.json() : null; + }) + .then(function (data) { + if (!data) return; + setText("runtime-healthy-count", data.healthy_count); + setText("runtime-stale-count", data.stale_count); + var cov = data.coverage || {}; + setText("runtime-coverage-pct", cov.percent === null || cov.percent === undefined ? "—" : cov.percent + "%"); + setText("runtime-coverage-counts", (cov.functions_executed || 0) + " / " + (cov.functions_total || 0)); + setText("runtime-routes-count", (cov.routes_seen || []).length); + setText("runtime-poll-status", "Last refreshed " + new Date().toLocaleTimeString()); + }) + .catch(function () {}); + } + + setInterval(refresh, 10000); + document.addEventListener("visibilitychange", function () { + if (document.visibilityState === "visible") refresh(); + }); +})(); diff --git a/src/secfoo/web/templates/project.html b/src/secfoo/web/templates/project.html index c2b5f69..14b0078 100644 --- a/src/secfoo/web/templates/project.html +++ b/src/secfoo/web/templates/project.html @@ -5,7 +5,15 @@ ← All projects {{ project.kind }}

{{ project.display_name }}

-

{{ project.identifier }}

+ {% if tm_rerun == "started" %}
Threat modeling re-run queued with unmodeled routes added as context.
diff --git a/src/secfoo/web/templates/projects_runtime.html b/src/secfoo/web/templates/projects_runtime.html new file mode 100644 index 0000000..bff9c03 --- /dev/null +++ b/src/secfoo/web/templates/projects_runtime.html @@ -0,0 +1,165 @@ +{% extends "base.html" %} +{% block title %}{{ dash.project_display_name }} — Runtime — secfoo{% endblock %} +{% block content %} +← Back to {{ dash.project_display_name }} +Runtime monitoring +
+

{{ dash.project_display_name }}

+ Live refresh every 10s while visible +
+ +
+
+ {{ dash.healthy_count }} + Healthy sensors +
+
+ {{ dash.stale_count }} + Stale sensors (>3 missed heartbeats) +
+
+ {% if dash.coverage_pct is not none %}{{ dash.coverage_pct }}%{% else %}—{% endif %} + Functions executed ({{ dash.functions_executed }} / {{ dash.functions_total }}) +
+
+ {{ dash.routes_seen | length }} + Routes observed +
+
+ +

Connected apps & sensors

+{% if dash.sensors %} +
+ + + + + + + + {% for s in dash.sensors %} + + + + + + + + + + + + {% endfor %} + +
AppEnvVersionInstancesHealthLast heartbeatEvents/minDroppedWindow
{{ s.app }}
{{ s.sensor_id }}
{{ s.env }}{{ s.version }}{{ s.instances }} + {% if s.status == "healthy" %}Healthy + {% else %}Stale{% endif %} + {{ s.last_heartbeat_at | fmt_time }}{{ s.events_per_minute }}{{ s.dropped_total }}{{ s.observation_window }}
+
+{% else %} +
+
No runtime sensor has connected for this project yet. Issue a runtime key with secfoo serve key create to stream live telemetry.
+
+{% endif %} + +
+
+

Routes seen

+ {% if dash.routes_seen %} +
+ + + + {% for r in dash.routes_seen %} + + + + + + + {% endfor %} + +
RouteHitsAuthFindings
{{ r.route }}{{ r.hits }}{{ r.auth_states | join(", ") or "unknown" }}{{ r.findings_count }}
+
+ {% else %} +

No request routes recorded yet.

+ {% endif %} +
+ +
+

Newly loaded packages

+ {% if dash.newly_loaded_packages %} +
+ + + + {% for p in dash.newly_loaded_packages %} + + + + + + + {% endfor %} + +
PackageVersionApp / EnvFirst seen
{{ p.package }} ({{ p.ecosystem }}){{ p.version }}{{ p.app }} / {{ p.env }}{{ p.first_seen | fmt_time if p.first_seen else "—" }}
+
+ {% else %} +

No loaded runtime packages reported yet.

+ {% endif %} +
+
+ +

Recent runtime activity & alerts

+{% if dash.reached_functions %} +

Newly reached vulnerable functions

+
+ + + + {% for f in dash.reached_functions %} + + + + + + + + + {% endfor %} + +
PackageSeveritySymbolRouteAuthHits
{{ f.package }}{{ f.severity }}{{ f.symbol }}{{ f.route }}{{ f.auth }}{{ f.count }}
+
+{% endif %} + +{% if dash.runtime_findings %} +

Version drift, unscanned packages & new advisories

+
+ + + + {% for rf in dash.runtime_findings %} + + + + + + + + + {% endfor %} + +
TypePackageRunningScannedAdvisoryApps
+ {% if rf.kind == "new_advisory" %}New advisory + {% elif rf.kind == "drift" %}Version drift + {% else %}Unscanned{% endif %} + {{ rf.package }} ({{ rf.ecosystem }}){{ rf.version }}{{ rf.scanned_versions }}{{ rf.advisory }}{{ rf.apps }}
+
+{% elif not dash.reached_functions %} +
+
No drift, unscanned packages, new advisories, or reached vulnerable functions reported yet.
+
+{% endif %} + + +{% endblock %} diff --git a/tests/test_web/test_runtime_dashboard.py b/tests/test_web/test_runtime_dashboard.py new file mode 100644 index 0000000..86e759a --- /dev/null +++ b/tests/test_web/test_runtime_dashboard.py @@ -0,0 +1,370 @@ +"""Tests for the Runtime page, sensor health, live JSON polling, and webhook alerts (#72).""" +from __future__ import annotations + +import json +import logging +import urllib.error +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from secfoo.runtime import inventory +from secfoo.runtime.alerts import ( + clear_alert, + detect_stale_sensors, + emit_alert, + post_webhook, +) +from secfoo.runtime.evidence import ingest_events +from secfoo.runtime.keys import create_key +from secfoo.settings import ConfigError, load_config +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + + +@pytest.fixture +def env(tmp_path, monkeypatch): + db_path = tmp_path / "db.sqlite" + cfg_path = tmp_path / "config.toml" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.settings.CONFIG_PATH", cfg_path) + return {"db_path": db_path, "config_path": cfg_path, "tmp_path": tmp_path} + + +def _seed_project_and_sca(repo: RunRepository) -> int: + pid = repo.upsert_project("https://github.com/acme/payments", "acme/payments", "github") + ru = repo.create_run( + project_id=pid, + skill_id="sca-reachability", + skill_name="SCA Reachability", + agent_id="claude", + confluence_urls=[], + ) + repo.complete_run( + ru, + status="success", + exit_code=0, + duration_seconds=1.0, + report_path=None, + prompt_path=None, + stderr_excerpt=None, + high_count=1, + ) + r = repo.get_run(ru) + repo.upsert_sca_finding( + project_id=pid, + fingerprint="fp-sca-1", + run_id=r.id, + current_ref="D1", + package="requests", + version="2.31.0", + ecosystem="PyPI", + issue="SSRF bypass", + severity="High", + reachability="Reachable", + cve="CVE-2024-99999", + ) + return pid + + +def test_runtime_config_parses_and_validates_alert_webhook(env): + cfg: Path = env["config_path"] + cfg.write_text('[runtime]\nalert_webhook = "https://hooks.example.com/secfoo"\n', encoding="utf-8") + loaded = load_config(cfg) + assert loaded.runtime_alert_webhook == "https://hooks.example.com/secfoo" + + cfg.write_text('[runtime]\nalert_webhook = "ftp://bad.example.com"\n', encoding="utf-8") + with pytest.raises(ConfigError): + load_config(cfg) + + +def test_runtime_page_never_connected_healthy_and_stale_sensors(env, monkeypatch): + sent: list[tuple[str, dict]] = [] + monkeypatch.setattr("secfoo.runtime.alerts.configured_webhook_url", lambda: "https://hooks.example.com/rt") + monkeypatch.setattr("secfoo.runtime.alerts.post_webhook", lambda url, payload: sent.append((url, payload))) + + with RunRepository() as repo: + pid = _seed_project_and_sca(repo) + + client = TestClient(create_app()) + # Never connected state + proj_resp = client.get(f"/projects/{pid}") + assert proj_resp.status_code == 200 + assert f"/projects/{pid}/runtime" in proj_resp.text + assert "Not connected" in proj_resp.text + + empty_rt = client.get(f"/projects/{pid}/runtime") + assert empty_rt.status_code == 200 + assert "No runtime sensor has connected" in empty_rt.text + assert client.get("/projects/9999/runtime").status_code == 404 + + # Seed one healthy sensor, one stale sensor (> 3 missed heartbeats = > 90s), session coverage & hits + now = datetime.now(timezone.utc) + healthy_hb = (now - timedelta(seconds=15)).isoformat() + stale_hb = (now - timedelta(seconds=240)).isoformat() + started = (now - timedelta(hours=2)).isoformat() + + with RunRepository() as repo: + conn = repo.connection + conn.execute( + "INSERT INTO runtime_sensors " + "(project_id, sensor_id, version, app, env, instances, dropped_total, first_seen_at, last_heartbeat_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (pid, "sensor-healthy", "0.4.0", "payments-api", "prod", 3, 2, started, healthy_hb), + ) + conn.execute( + "INSERT INTO runtime_sensors " + "(project_id, sensor_id, version, app, env, instances, dropped_total, first_seen_at, last_heartbeat_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (pid, "sensor-stale", "0.3.9", "billing-worker", "staging", 1, 7, started, stale_hb), + ) + conn.commit() + + ingest_events( + conn, + pid, + [ + json.dumps( + { + "type": "session", + "id": "8f8a1c2e-0000-4000-8000-000000000001", + "language": "python", + "runtime": "3.12.4", + "source": "sensor", + "app": "payments-api", + "env": "prod", + "started_at": started, + "ended_at": now.isoformat(), + "app_functions_total": 200, + "app_functions_executed": 50, + } + ), + json.dumps( + { + "type": "load", + "session": "8f8a1c2e-0000-4000-8000-000000000001", + "ecosystem": "PyPI", + "package": "requests", + "version": "2.31.0", + "first_seen": started, + } + ), + json.dumps( + { + "type": "hit", + "session": "8f8a1c2e-0000-4000-8000-000000000001", + "finding_fingerprint": "fp-sca-1", + "symbol": "requests.get", + "route": "POST /charge", + "auth": "authenticated", + "count": 120, + "last_seen": healthy_hb, + "stack_sample": ["app/pay.py:12"], + } + ), + ], + ) + + rt_resp = client.get(f"/projects/{pid}/runtime") + assert rt_resp.status_code == 200 + body = rt_resp.text + assert "payments-api" in body + assert "billing-worker" in body + assert "Healthy" in body + assert "Stale" in body + assert "25%" in body + assert "50 / 200" in body + assert "POST /charge" in body + assert "requests.get" in body + assert "/activities/sca-reachability/vulnerabilities/" in body + assert "/static/js/runtime-live.js" in body + + # Live JSON poll endpoint + json_resp = client.get(f"/projects/{pid}/runtime.json") + assert json_resp.status_code == 200 + doc = json_resp.json() + assert doc["healthy_count"] == 1 + assert doc["stale_count"] == 1 + assert doc["coverage"]["percent"] == 25 + assert doc["sensors"][0]["sensor_id"] in {"sensor-healthy", "sensor-stale"} + + # GET views / JSON polls must remain pure read-only (no side-effect webhooks) + assert sent == [] + + # Stale sensors are detected explicitly (via heartbeat processing or periodic check) + # without needing any browser page to be open, and alert at most once until recovery. + with RunRepository() as repo: + alerted = detect_stale_sensors(repo.connection) + repo.connection.commit() + assert alerted == ["sensor-stale"] + assert detect_stale_sensors(repo.connection) == [] + stale_alerts = [p for _u, p in sent if p["event"] == "sensor_stale"] + assert len(stale_alerts) == 1 + assert stale_alerts[0]["app"] == "billing-worker" + assert stale_alerts[0]["env"] == "staging" + assert stale_alerts[0]["link"] == f"/projects/{pid}/runtime" + assert "stack_sample" not in json.dumps(stale_alerts[0]) + + +def test_runtime_ingest_and_advisory_webhook_payloads_exclude_stacks(env, monkeypatch): + sent: list[tuple[str, dict]] = [] + monkeypatch.setattr("secfoo.runtime.alerts.configured_webhook_url", lambda: "https://hooks.example.com/rt") + monkeypatch.setattr("secfoo.runtime.alerts.post_webhook", lambda url, payload: sent.append((url, payload))) + + with RunRepository() as repo: + pid = _seed_project_and_sca(repo) + raw_token, _ = create_key(repo.connection, name="test-sensor", scope="runtime", project_id=pid) + repo.upsert_osv_lookup( + ecosystem="PyPI", + package="requests", + version="2.31.0", + vulns=[{"id": "GHSA-NEW-999", "aliases": []}], + ) + + client = TestClient(create_app()) + headers = {"Authorization": f"Bearer {raw_token}"} + now = datetime.now(timezone.utc).isoformat() + ndjson = "\n".join( + [ + json.dumps( + { + "type": "session", + "id": "8f8a1c2e-0000-4000-8000-000000000002", + "language": "python", + "runtime": "3.12.4", + "source": "sensor", + "app": "checkout", + "env": "prod", + "started_at": now, + } + ), + json.dumps( + { + "type": "load", + "session": "8f8a1c2e-0000-4000-8000-000000000002", + "ecosystem": "PyPI", + "package": "requests", + "version": "2.31.0", + "first_seen": now, + } + ), + json.dumps( + { + "type": "hit", + "session": "8f8a1c2e-0000-4000-8000-000000000002", + "finding_fingerprint": "fp-sca-1", + "symbol": "requests.sessions.Session.request", + "route": "GET /checkout", + "auth": "authenticated", + "count": 4, + "last_seen": now, + "stack_sample": ["secret/internal_frame.py:99"], + "entry_frame": "wsgi.py:1", + } + ), + ] + ) + resp = client.post( + "/api/runtime/v1/events", + params={"project": "https://github.com/acme/payments", "app": "checkout", "env": "prod"}, + content=ndjson, + headers=headers, + ) + assert resp.status_code == 200 + assert resp.json()["hits"] == 1 + + reached_alerts = [p for _u, p in sent if p["event"] == "reached_from_traffic"] + assert len(reached_alerts) == 1 + assert reached_alerts[0]["finding_fingerprint"] == "fp-sca-1" + assert reached_alerts[0]["app"] == "checkout" + assert reached_alerts[0]["env"] == "prod" + assert "/activities/sca-reachability/vulnerabilities/" in reached_alerts[0]["link"] + assert "stack_sample" not in json.dumps(reached_alerts[0]) + assert "internal_frame.py" not in json.dumps(reached_alerts[0]) + + # Trigger new_advisory alert via runtime inventory analysis + with RunRepository() as repo: + report = inventory.analyze(repo, pid, app="checkout", env="prod", known={}) + assert any(r["kind"] == "new_advisory" for r in report.raised) + + adv_alerts = [p for _u, p in sent if p["event"] == "new_advisory"] + assert len(adv_alerts) == 1 + assert adv_alerts[0]["finding_fingerprint"] == "GHSA-NEW-999" + assert adv_alerts[0]["app"] == "checkout" + assert adv_alerts[0]["link"] == f"/projects/{pid}/runtime" + assert "stack_sample" not in json.dumps(adv_alerts[0]) + + # Verify heartbeat detects pre-existing stale sensors and resets recovery + stale_hb = (datetime.now(timezone.utc) - timedelta(seconds=240)).isoformat() + with RunRepository() as repo: + repo.connection.execute( + "INSERT INTO runtime_sensors " + "(project_id, sensor_id, version, app, env, instances, dropped_total, first_seen_at, last_heartbeat_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (pid, "s-stale-peer", "0.4.0", "worker", "prod", 1, 0, stale_hb, stale_hb), + ) + repo.connection.commit() + + hb_resp = client.post( + "/api/runtime/v1/heartbeat", + params={"project": "https://github.com/acme/payments"}, + json={"sensor_id": "s-1", "version": "0.4.0", "app": "checkout", "env": "prod", "instances": 2, "dropped": 0}, + headers=headers, + ) + assert hb_resp.status_code == 200 + assert any(p["event"] == "sensor_stale" and p["details"]["sensor_id"] == "s-stale-peer" for _u, p in sent) + + with RunRepository() as repo: + emit_alert( + repo.connection, + project_id=pid, + event_type="sensor_stale", + target_key="s-1", + app="checkout", + env="prod", + link=f"/projects/{pid}/runtime", + ) + # _claim_alert does not commit on the caller's behalf: rolling back removes the claim. + repo.connection.rollback() + assert ( + emit_alert( + repo.connection, + project_id=pid, + event_type="sensor_stale", + target_key="s-1", + app="checkout", + env="prod", + link=f"/projects/{pid}/runtime", + ) + is True + ) + clear_alert(repo.connection, project_id=pid, event_type="sensor_stale", target_key="s-1") + repo.connection.commit() + assert ( + emit_alert( + repo.connection, + project_id=pid, + event_type="sensor_stale", + target_key="s-1", + app="checkout", + env="prod", + link=f"/projects/{pid}/runtime", + ) + is True + ) + + +def test_webhook_failure_logs_host_only_without_secret_path(monkeypatch, caplog): + def _fail(_req, timeout=5): + raise urllib.error.URLError("connection refused") + + monkeypatch.setattr("secfoo.runtime.alerts.urllib.request.urlopen", _fail) + secret_url = "https://hooks.example.com/services/SECRET_WORKSPACE/SECRET_TOKEN" + with caplog.at_level(logging.WARNING, logger="secfoo.runtime.alerts"): + post_webhook(secret_url, {"event": "sensor_stale"}) + assert "hooks.example.com" in caplog.text + assert "SECRET_TOKEN" not in caplog.text + assert "SECRET_WORKSPACE" not in caplog.text