Skip to content

feat(runtime): add per-project Runtime dashboard, live polling, and alert webhooks - #212

Open
SriRamkunamsetty wants to merge 1 commit into
secfoo-com:mainfrom
SriRamkunamsetty:feat/runtime-dashboard-72
Open

SriRamkunamsetty wants to merge 1 commit into
secfoo-com:mainfrom
SriRamkunamsetty:feat/runtime-dashboard-72

Conversation

@SriRamkunamsetty

Copy link
Copy Markdown
Contributor

Fixes #72

Summary

  • Per-project Runtime monitoring dashboard (/projects/{id}/runtime, linked from project.html):
    • Added src/secfoo/web/runtime_dashboard.py computing connected sensor health (healthy vs Stale after missing >= 3 heartbeats), events/min, dropped event totals, observation windows, function execution coverage (app_functions_executed / app_functions_total), routes observed, newly loaded packages, version drift / unscanned / new advisory findings, and newly reached vulnerable functions linking directly to SCA finding details.
    • Added /projects/{id}/runtime and /projects/{id}/runtime.json routes in src/secfoo/web/routes/projects.py plus templates projects_runtime.html, project.html, and CSP-clean external script src/secfoo/web/static/js/runtime-live.js (polling every 10s while the tab is visible).
  • Optional runtime alert webhooks ([runtime] alert_webhook):
    • Parsed [runtime] alert_webhook in src/secfoo/settings.py.
    • Added src/secfoo/runtime/alerts.py + runtime_alerts_sent deduplication table in schema.sql, emitting sanitized webhook payloads (with finding_fingerprint, app, env, and deep link, never stack samples) for reached_from_traffic (runtime/api.py), new_advisory (runtime/inventory.py), and sensor_stale (runtime_dashboard.py, reset on fresh heartbeat).
  • Documentation & tests:
    • Documented [runtime] alert_webhook and /projects/<id>/runtime in docs/REFERENCE.md.
    • Added comprehensive tests in tests/test_web/test_runtime_dashboard.py.

Verification

  • ruff check . — 0 errors
  • bandit -c .bandit -ll -r src/secfoo — 0 medium/high issues
  • pytest tests/test_web/test_runtime_dashboard.py tests/test_runtime tests/test_web/test_no_inline_scripts.py tests/test_web/test_routes.py tests/test_docs_consistency.py -q — 231 passed

@vsn411 vsn411 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, and welcome! The Runtime page is a big step for #72. Sensor health with a stale state after 3 missed heartbeats, coverage, new packages and newly reached functions are exactly what the issue asks for. The webhook payload deliberately leaves out stack samples, and the polling script is CSP-clean.

Some changes are needed in the alert path before we merge, because it currently runs inside the request handlers:

  1. Ingest blocks the event loop. post_events is async, but _notify_newly_reached runs synchronously inside it. It reads every runtime_evidence row for the project on each batch with hits, and calls emit_alert once per row. Each call does an INSERT … ; commit, and possibly a blocking urlopen with a 5 s timeout. Evidence grows without bound, so a busy sensor will slow down, and every other request waits while the webhook POST runs. Suggestions:
    • only look at fingerprints that are new in this batch, e.g. a SQL anti-join against runtime_alerts_sent;
    • send the webhook off the event loop (BackgroundTasks, or a small worker thread).
  2. A GET can fire a webhook. The sensor_stale alert is emitted while /projects/{id}/runtime (and the 10 s .json poll) renders. Viewing a page shouldn't have side effects, and with the page closed nobody gets the alert. Detect staleness where heartbeats are processed, or in a periodic check, rather than in the dashboard builder.
  3. _claim_alert commits the caller's connection. Called mid-ingest, it commits whatever the ingest had pending. Let the caller own the transaction.
  4. Don't log the webhook URL. logger.warning("… failed for %s", url) writes the full URL, and Slack/Teams-style URLs carry their secret token in the path. Log the host only.

Small things:

  • runtime/api.py now imports private helpers from web/ (_vulnerability_key, _is_request_route). Moving them to a shared module would keep runtime independent of the web layer.
  • #213 (yours too) also changes routes/projects.py and project.html, so whichever merges second will need a rebase.

CI hasn't run yet because this is your first PR here. A maintainer will approve the workflow run.

@SriRamkunamsetty
SriRamkunamsetty force-pushed the feat/runtime-dashboard-72 branch from 059909c to 3e044da Compare November 30, 2026 01:57
@SriRamkunamsetty

Copy link
Copy Markdown
Contributor Author

Addressed all review feedback and rebased onto \main:

  1. **Non-blocking \post_events**: \IngestReport\ now tracks \hit_fingerprints\ seen in the batch, _notify_newly_reached\ queries only those fingerprints via a SQL anti-join against
    untime_alerts_sent, and webhook delivery runs off the event loop via FastAPI \BackgroundTasks.
  2. Pure GET routes & off-page stale detection: Removed alert emission from
    untime_dashboard.build\ (/projects/{id}/runtime\ and .json\ are now strictly read-only). Extracted \detect_stale_sensors\ to \secfoo.runtime.alerts, invoked during /heartbeat\ / /events\ processing and periodically from \secfoo serve's lifespan watcher.
  3. Caller-owned transactions: Removed \conn.commit()\ from _claim_alert\ and \clear_alert\ so ingest/heartbeat callers own their transaction boundaries.
  4. URL host-only logging: \post_webhook\ logs \urlsplit(url).hostname\ on delivery failures so Slack/Teams webhook path tokens never hit logs.
  5. Decoupled layers: Moved \�ulnerability_key\ to \secfoo.report.sca\ and \is_request_route\ to \secfoo.runtime.evidence\ (re-exported in \secfoo.web\ for compatibility).

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

@vsn411 vsn411 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick turnaround. Every point from the last review is fixed: webhooks go out through BackgroundTasks, the GET routes have no side effects, the caller owns the transaction, only the host is logged, and the helpers moved out of web/.

One thing left before we merge:

A dead sensor is never reported as stale. detect_stale_sensors only runs inside /heartbeat and /events, so it needs some sensor in the project to still be talking. With a single sensor, the usual case for local and CI runs, nothing arrives once it dies, and sensor_stale never fires. Please add a periodic check that doesn't depend on incoming traffic. For example, a background task started with secfoo serve (FastAPI lifespan) that calls detect_stale_sensors every HEARTBEAT_INTERVAL_SECONDS. Add a test where the only sensor stops sending and the alert still goes out.

Small things, optional:

  • configured_webhook_url() reads config.toml on every emit_alert call. Reading it once per request (and returning early from _notify_newly_reached when no webhook is configured) avoids the per-row disk read and the SCA findings query.
  • The CodeQL alert in tests/test_web/test_runtime_dashboard.py:368 is a test assertion, not sanitisation. We'll dismiss it, so there's nothing to do there.
  • #210 is about to merge and also changes storage/schema.sql, so this needs a small rebase after it lands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Runtime page: sensor health, live activity and alerts

3 participants