diff --git a/src/secfoo/report/architecture.py b/src/secfoo/report/architecture.py index dad90a7..93aa5ce 100644 --- a/src/secfoo/report/architecture.py +++ b/src/secfoo/report/architecture.py @@ -56,6 +56,19 @@ r"^\|[^|]*\|\s*(?P[A-Z&]{2,4})\s*\|(?P[^|]*)\|", re.MULTILINE ) +# Threat Modeling's Scope & Assets Entry Points table: | ID | Entry point | Interface | Route / pattern | Boundary | +_ENTRY_POINT_ROW_RE = re.compile( + r"^\|\s*(?PE\d+)\s*\|(?P[^|]*)\|(?P[^|]*)\|" + r"(?P[^|]*)\|(?P[^|]*)\|\s*$", + re.MULTILINE, +) + +# Threat Modeling's Trust Boundaries table: | ID | Boundary | What crosses it | +_TRUST_BOUNDARY_ROW_RE = re.compile( + r"^\|\s*(?PB\d+)\s*\|(?P[^|]*)\|(?P[^|]*)\|\s*$", + re.MULTILINE, +) + # Threat Modeling's Threat Register: | ID | Threat | Archetype | Asset # Class | Boundary | STRIDE | Severity | Disposition | Test Reference | _THREAT_REGISTER_ROW_RE = re.compile( @@ -193,6 +206,33 @@ def extract_threat_register_rows(report_markdown: str) -> list[dict[str, str]]: return rows +def extract_entry_points(report_markdown: str) -> list[dict[str, str]]: + """Parse `En` entry points from Threat Modeling `## 2. Scope & Assets` (#70). + + Reports predating the Entry Points table simply yield `[]`. + """ + section = _extract_section(report_markdown, "Scope & Assets") + if not section: + return [] + rows: list[dict[str, str]] = [] + for match in _ENTRY_POINT_ROW_RE.finditer(section): + d = {key: value.strip().strip("`").strip() for key, value in match.groupdict().items()} + rows.append(d) + return rows + + +def extract_trust_boundaries(report_markdown: str) -> dict[str, dict[str, str]]: + """Map `Bn` boundary IDs from Trust Boundaries & Data Flow to `{id, boundary, what_crosses}`.""" + section = _extract_section(report_markdown, "Trust Boundaries & Data Flow") + if not section: + return {} + result: dict[str, dict[str, str]] = {} + for match in _TRUST_BOUNDARY_ROW_RE.finditer(section): + d = {key: value.strip().strip("`").strip() for key, value in match.groupdict().items()} + result[d["id"]] = d + return result + + def extract_model_depth(report_markdown: str) -> str | None: """The Threat Modeling contract's self-declared model depth (Full / Feature-level / Lightweight), normalized to one of those three labels diff --git a/src/secfoo/runtime/correlation.py b/src/secfoo/runtime/correlation.py new file mode 100644 index 0000000..6a1b32b --- /dev/null +++ b/src/secfoo/runtime/correlation.py @@ -0,0 +1,222 @@ +"""Correlate live traffic routes observed by runtime sensors with threat-model entry points (#70).""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field + +from secfoo.report.architecture import ( + extract_entry_points, + extract_threat_register_rows, + extract_trust_boundaries, +) +from secfoo.report.markdown import read_stored_report +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} + + +def _split_method_and_path(route_text: str) -> tuple[str | None, str]: + cleaned = (route_text or "").strip().strip("`") + if not cleaned: + return None, "" + parts = cleaned.split(None, 1) + if len(parts) == 2 and parts[0].upper() in _HTTP_METHODS: + return parts[0].upper(), parts[1].strip() + return None, cleaned + + +def _norm_path(path: str) -> str: + stripped = path.split("?", 1)[0].strip() + if stripped != "/" and stripped.endswith("/"): + stripped = stripped.rstrip("/") + return stripped + + +def _pattern_to_regex(pattern_path: str) -> re.Pattern[str]: + segments = [seg for seg in _norm_path(pattern_path).split("/") if seg != ""] + if not segments: + return re.compile(r"^/$") + parts: list[str] = [] + for seg in segments: + if seg == "*" or re.fullmatch(r"\{[^}]+:\*\}", seg) or seg == "**": + parts.append(".*") + elif ( + (seg.startswith("{") and seg.endswith("}")) + or (seg.startswith("<") and seg.endswith(">")) + or seg.startswith(":") + ): + parts.append("[^/]+") + else: + parts.append(re.escape(seg)) + return re.compile(r"^/" + "/".join(parts) + r"$", re.IGNORECASE) + + +def match_route(observed_route: str, pattern: str) -> bool: + """Return True if an observed runtime route matches an `En` route/pattern. + + Supports optional HTTP methods (`POST /upload`, `/upload`), exact paths, + parameterized segments (`/users/{id}`, `/users/:id`, `/users/`), and + wildcard prefixes (`/api/*`). + """ + obs_method, obs_path = _split_method_and_path(observed_route) + pat_method, pat_path = _split_method_and_path(pattern) + if not obs_path or not pat_path: + return False + if pat_method and pat_method not in {"ANY", "*"} and obs_method and obs_method != pat_method: + return False + return bool(_pattern_to_regex(pat_path).match(_norm_path(obs_path))) + + +@dataclass(frozen=True) +class LiveEntryPoint: + id: str + entry_point: str + interface: str + route_pattern: str + boundary_id: str + boundary_label: str + matched_routes: list[str] = field(default_factory=list) + hits: int = 0 + + @property + def citation(self) -> str: + if self.boundary_label: + return f"Reached via {self.id} ({self.boundary_id}: {self.boundary_label})" + if self.boundary_id: + return f"Reached via {self.id} ({self.boundary_id})" + return f"Reached via {self.id}" + + +@dataclass(frozen=True) +class TrafficCorrelation: + project_id: int + has_threat_model: bool + has_live_traffic: bool + latest_run_uuid: str | None + live_entry_points: list[LiveEntryPoint] + unmodeled_routes: list[dict[str, object]] + live_boundaries: set[str] + prioritized_threats: list[dict[str, object]] + route_matches: dict[str, LiveEntryPoint] + + def citation_for_route(self, route: str) -> str | None: + hit = self.route_matches.get(route) + return hit.citation if hit else None + + +def observed_request_routes(conn, project_id: int) -> list[dict[str, object]]: + """Aggregate live request routes seen for `project_id` from `runtime_evidence`.""" + rows = conn.execute( + "SELECT route, SUM(count) AS total_hits, MAX(last_seen) AS last_seen " + "FROM runtime_evidence WHERE project_id = ? GROUP BY route ORDER BY total_hits DESC, route ASC", + (project_id,), + ).fetchall() + result: list[dict[str, object]] = [] + for row in rows: + route = row["route"] or "" + if not _is_request_route(route): + continue + result.append( + { + "route": route, + "hits": int(row["total_hits"] or 0), + "last_seen": row["last_seen"] or "", + } + ) + return result + + +def correlate_project_traffic( + repo: RunRepository, + project_id: int, + *, + report_markdown: str | None = None, + run_uuid: str | None = None, +) -> TrafficCorrelation: + """Correlate observed runtime routes for `project_id` with its latest threat model.""" + latest_uuid = run_uuid + text = report_markdown + if text is None: + runs = repo.list_runs(project_id=project_id, skill_id="threat-modeling", status="success", limit=1) + if runs: + latest_uuid = runs[0].run_uuid + if runs[0].report_path: + text = read_stored_report(runs[0].report_path) or "" + + has_tm = bool(text) + entry_points = extract_entry_points(text or "") + boundaries = extract_trust_boundaries(text or "") + threats = extract_threat_register_rows(text or "") + observed = observed_request_routes(repo.connection, project_id) + + route_matches: dict[str, LiveEntryPoint] = {} + matched_by_ep: dict[str, list[dict[str, object]]] = {ep["id"]: [] for ep in entry_points} + unmodeled_routes: list[dict[str, object]] = [] + + for obs in observed: + obs_route = str(obs["route"]) + matched_ep = next( + (ep for ep in entry_points if match_route(obs_route, ep.get("route", ""))), + None, + ) + if matched_ep is None: + unmodeled_routes.append(obs) + else: + matched_by_ep[matched_ep["id"]].append(obs) + + live_entry_points: list[LiveEntryPoint] = [] + live_boundaries: set[str] = set() + for ep in entry_points: + hits_list = matched_by_ep.get(ep["id"], []) + if not hits_list: + continue + b_id = ep.get("boundary", "") + b_info = boundaries.get(b_id, {}) + b_label = b_info.get("boundary", "") + if b_id: + live_boundaries.add(b_id) + live_ep = LiveEntryPoint( + id=ep["id"], + entry_point=ep.get("entry_point", ""), + interface=ep.get("interface", ""), + route_pattern=ep.get("route", ""), + boundary_id=b_id, + boundary_label=b_label, + matched_routes=[str(r["route"]) for r in hits_list], + hits=sum(int(r["hits"]) for r in hits_list), + ) + live_entry_points.append(live_ep) + for obs in hits_list: + route_matches[str(obs["route"])] = live_ep + + prioritized_threats: list[dict[str, object]] = [] + for t in threats: + b_id = t.get("boundary", "").strip() + seen = bool(b_id and b_id in live_boundaries) + disp = t.get("disposition", "").strip().lower() + sev = _SEVERITY_RANK.get(t.get("severity", "").strip().lower(), -1) + prioritized_threats.append( + { + **t, + "seen_in_production": seen, + "_sort_key": (1 if disp == "gap" else 0, 1 if seen else 0, sev), + } + ) + prioritized_threats.sort(key=lambda item: item["_sort_key"], reverse=True) + for item in prioritized_threats: + item.pop("_sort_key", None) + + return TrafficCorrelation( + project_id=project_id, + has_threat_model=has_tm, + has_live_traffic=bool(observed), + latest_run_uuid=latest_uuid, + live_entry_points=live_entry_points, + unmodeled_routes=unmodeled_routes, + live_boundaries=live_boundaries, + prioritized_threats=prioritized_threats, + route_matches=route_matches, + ) diff --git a/src/secfoo/skills/renderer.py b/src/secfoo/skills/renderer.py index 0449569..fce9934 100644 --- a/src/secfoo/skills/renderer.py +++ b/src/secfoo/skills/renderer.py @@ -409,7 +409,13 @@ def merge_excludes(*sources: list[str] | None) -> list[str]: ## 2. Scope & Assets Components, entry points, and the assets worth attacking (data, -credentials, compute, availability, model/IP). +credentials, compute, availability, model/IP). Include an Entry Points table +mapping each externally reachable route or interface to its `Bn` boundary +from section 3: + +| ID | Entry point | Interface | Route / pattern | Boundary | +|----|-------------|-----------|-----------------|----------| +| E1 | Public upload API | HTTP | POST /upload | B1 | ## 3. Trust Boundaries & Data Flow A **Mermaid** diagram in a fenced ```mermaid block, plus a Trust diff --git a/src/secfoo/web/routes/projects.py b/src/secfoo/web/routes/projects.py index affdf76..34676af 100644 --- a/src/secfoo/web/routes/projects.py +++ b/src/secfoo/web/routes/projects.py @@ -1,7 +1,17 @@ from __future__ import annotations +import shutil +import tempfile +import threading +from pathlib import Path + from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import 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.templating import ordered_skills, templates @@ -9,13 +19,14 @@ @router.get("/projects/{project_id}") -def project_detail(request: Request, project_id: int): +def project_detail(request: Request, project_id: int, tm_rerun: str | None = None): with RunRepository() as repo: project = repo.get_project(project_id) if project is None: raise HTTPException(status_code=404, detail="Project not found") 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) # Every known activity, covered or not -- an activity this project has # never had run is exactly the gap worth showing. @@ -27,5 +38,61 @@ def project_detail(request: Request, project_id: int): return templates.TemplateResponse( request, "project.html", - {"project": project, "runs": runs, "activities": activities}, + { + "project": project, + "runs": runs, + "activities": activities, + "tm_correlation": tm_correlation, + "tm_rerun": tm_rerun, + }, ) + + +@router.post("/projects/{project_id}/threat-modeling/rerun") +def project_rerun_threat_modeling(project_id: int): + """Trigger a fresh `threat-modeling` run with observed unmodeled routes as context (#70).""" + with RunRepository() as repo: + project = repo.get_project(project_id) + if project is None: + raise HTTPException(status_code=404, detail="Project not found") + corr = correlate_project_traffic(repo, project_id) + + routes = [str(r["route"]) for r in corr.unmodeled_routes] + if not routes: + return RedirectResponse(f"/projects/{project_id}", status_code=303) + + try: + cfg = load_config() + agent_id = cfg.defaults.agent or "claude" + except ConfigError: + agent_id = "claude" + + note_dir = Path(tempfile.mkdtemp(prefix="secfoo-unmodeled-routes-")) + note_file = note_dir / "unmodeled-routes.md" + lines = [ + "# Unmodeled live traffic routes (threat-model drift)", + "", + "These request routes received live sensor traffic without matching an `En` entry point:", + *[f"- `{r}`" for r in routes], + "", + "Include them in `## 2. Scope & Assets`, map each to a `Bn` boundary, and assess threats in the Threat Register.", + ] + note_file.write_text("\n".join(lines) + "\n", encoding="utf-8") + + def _run_and_cleanup() -> None: + try: + execute_runs( + skill_ids=["threat-modeling"], + target=project.identifier, + confluence_urls=[], + context_sources=[ + ContextSource(raw=str(note_file), kind="file", location=str(note_file.resolve())) + ], + agent_id=agent_id, + project_id=project_id, + ) + finally: + shutil.rmtree(note_dir, ignore_errors=True) + + threading.Thread(target=_run_and_cleanup, daemon=True).start() + return RedirectResponse(f"/projects/{project_id}?tm_rerun=started", status_code=303) diff --git a/src/secfoo/web/routes/runs.py b/src/secfoo/web/routes/runs.py index cbe60e2..b3519ff 100644 --- a/src/secfoo/web/routes/runs.py +++ b/src/secfoo/web/routes/runs.py @@ -7,6 +7,7 @@ from secfoo.config import STORE_DIR from secfoo.report.markdown import render_report_html +from secfoo.runtime.correlation import correlate_project_traffic from secfoo.storage.repository import RunRepository from secfoo.web.run_status import ( ACTIVE_STATUSES, @@ -44,6 +45,7 @@ def run_detail(request: Request, run_uuid: str): context_sources = repo.list_context_sources(run_uuid) report_html = "" + raw_report = "" report_file = None if record.report_path: try: @@ -51,9 +53,16 @@ def run_detail(request: Request, run_uuid: str): except HTTPException: report_file = None if report_file is not None: - text = report_file.read_text(encoding="utf-8", errors="replace") - if text.strip(): - report_html = render_report_html(text) + raw_report = report_file.read_text(encoding="utf-8", errors="replace") + if raw_report.strip(): + report_html = render_report_html(raw_report) + + tm_correlation = None + if record.skill_id == "threat-modeling": + with RunRepository() as repo: + tm_correlation = correlate_project_traffic( + repo, record.project_id, report_markdown=raw_report or None, run_uuid=record.run_uuid + ) from secfoo.web.app import mermaid_bundle_available @@ -70,6 +79,7 @@ def run_detail(request: Request, run_uuid: str): "definition_changed": definition_changed, "mermaid_available": mermaid_bundle_available(), "context_sources": context_sources, + "tm_correlation": tm_correlation, }, ) diff --git a/src/secfoo/web/sca_dashboard.py b/src/secfoo/web/sca_dashboard.py index 90ae335..a64eb6f 100644 --- a/src/secfoo/web/sca_dashboard.py +++ b/src/secfoo/web/sca_dashboard.py @@ -25,6 +25,7 @@ inventory_lookup, resolve_ecosystem, ) +from secfoo.runtime.correlation import TrafficCorrelation, correlate_project_traffic from secfoo.storage.repository import RunRepository from secfoo.web import sca_runtime from secfoo.web.dashboard_common import read_report @@ -72,6 +73,7 @@ class ScaVulnerability: # own state is on its affected_projects entry as "runtime"). runtime: sca_runtime.RuntimeStatus = field(default_factory=sca_runtime.RuntimeStatus) runtime_conflict: bool = False + boundary_citations: list[str] = field(default_factory=list) @dataclass @@ -173,6 +175,8 @@ def build(repo: RunRepository) -> ScaDashboard: # vulnerability rows. vulnerabilities: dict[str, ScaVulnerability] = {} + correlations: dict[int, TrafficCorrelation] = {} + for finding in raw_findings: cached = None if finding["ecosystem_osv"]: @@ -235,9 +239,18 @@ def build(repo: RunRepository) -> ScaDashboard: ecosystem=finding["ecosystem_osv"], scanned_version=finding["version"], ) + pid = finding["project_id"] + if pid not in correlations: + correlations[pid] = correlate_project_traffic(repo, pid) + corr = correlations[pid] + citations: list[str] = [] + for r in runtime.routes: + cite = corr.citation_for_route(r.get("route", "")) + if cite and cite not in citations: + citations.append(cite) vuln.affected_projects.append( { - "project_id": finding["project_id"], + "project_id": pid, "project_display_name": finding["project_display_name"], "dependency_id": finding["dependency_id"], "severity": finding["severity"], @@ -245,12 +258,19 @@ def build(repo: RunRepository) -> ScaDashboard: "fixed_in": finding["fixed_in"], "runtime": runtime, "runtime_conflict": sca_runtime.is_conflict(finding["reachability"], runtime), + "boundary_citations": citations, } ) for vuln in vulnerabilities.values(): vuln.runtime = sca_runtime.strongest([p["runtime"] for p in vuln.affected_projects]) vuln.runtime_conflict = any(p["runtime_conflict"] for p in vuln.affected_projects) + seen_cites: list[str] = [] + for p in vuln.affected_projects: + for c in p["boundary_citations"]: + if c not in seen_cites: + seen_cites.append(c) + vuln.boundary_citations = seen_cites dash.vulnerabilities = sorted( vulnerabilities.values(), diff --git a/src/secfoo/web/templates/activities/sca_vulnerabilities_list.html b/src/secfoo/web/templates/activities/sca_vulnerabilities_list.html index 162a670..3ee1d8d 100644 --- a/src/secfoo/web/templates/activities/sca_vulnerabilities_list.html +++ b/src/secfoo/web/templates/activities/sca_vulnerabilities_list.html @@ -40,6 +40,7 @@

All vulnerabilities

{{ v.reachability }} {{ v.runtime.label }} + {% for cite in v.boundary_citations %}{{ cite }}{% endfor %} {% if v.runtime.state != "none" %}{{ v.runtime.summary }}{% endif %} {% if v.runtime_conflict %}Conflicts with static verdict{% endif %} diff --git a/src/secfoo/web/templates/activities/sca_vulnerability_detail.html b/src/secfoo/web/templates/activities/sca_vulnerability_detail.html index 1447020..de57b6a 100644 --- a/src/secfoo/web/templates/activities/sca_vulnerability_detail.html +++ b/src/secfoo/web/templates/activities/sca_vulnerability_detail.html @@ -71,6 +71,7 @@

Runtime evidence

{{ p.project_display_name }} {{ rt.label }} + {% for cite in p.boundary_citations %}{{ cite }}{% endfor %} {% if p.runtime_conflict %}Conflicts with static verdict{% endif %} {% if rt.sources %}Source: {{ rt.sources | join(", ") }}{% endif %}
diff --git a/src/secfoo/web/templates/activities/threat_modeling_dashboard.html b/src/secfoo/web/templates/activities/threat_modeling_dashboard.html index b02e429..31e6641 100644 --- a/src/secfoo/web/templates/activities/threat_modeling_dashboard.html +++ b/src/secfoo/web/templates/activities/threat_modeling_dashboard.html @@ -358,3 +358,27 @@

Falsified assumptions

+ +{% if tm_dash.gap_threats %} +
+

Unmitigated threats (Gap)

+

Sorted with live boundaries seen in production first.

+
+ + + + {% for t in tm_dash.gap_threats %} + + + + + + + + + {% endfor %} + +
ProjectIDThreatBoundarySeverityTraffic
{{ t.project_display_name }}{{ t.id }}{{ t.threat }}{{ t.boundary }}{{ t.severity }}{% if t.seen_in_production %}Seen in production{% else %}Unobserved{% endif %}
+
+
+{% endif %} diff --git a/src/secfoo/web/templates/project.html b/src/secfoo/web/templates/project.html index 0aae26e..77abaa9 100644 --- a/src/secfoo/web/templates/project.html +++ b/src/secfoo/web/templates/project.html @@ -7,6 +7,50 @@

{{ project.display_name }}

{{ project.identifier }}

+{% if tm_rerun == "started" %} +
Threat modeling re-run queued with unmodeled routes added as context.
+{% endif %} + +{% if tm_correlation and (tm_correlation.live_entry_points or tm_correlation.unmodeled_routes) %} +
+
+

Live entry points & threat-model correlation

+ {% if tm_correlation.latest_run_uuid %} + Latest threat model → + {% endif %} +
+ {% if tm_correlation.live_entry_points %} +
+ + + + {% for ep in tm_correlation.live_entry_points %} + + + + + + + + {% endfor %} + +
Entry pointBoundaryMatched routesTraffic hitsStatus
{{ ep.id }} {{ ep.entry_point }}{{ ep.boundary_id }}{% if ep.boundary_label %} — {{ ep.boundary_label }}{% endif %}{% for r in ep.matched_routes %}{{ r }}{% if not loop.last %}, {% endif %}{% endfor %}{{ ep.hits }}Live entry point
+
+ {% endif %} + {% if tm_correlation.unmodeled_routes %} +
+
+ Unmodeled entry points (threat-model drift): + {% for r in tm_correlation.unmodeled_routes %}{{ r.route }} ({{ r.hits }} hits){% if not loop.last %}, {% endif %}{% endfor %}. +
+ +
+
+
+ {% endif %} +
+{% endif %} +

Activity coverage

diff --git a/src/secfoo/web/templates/run_detail.html b/src/secfoo/web/templates/run_detail.html index d4e56f4..d272991 100644 --- a/src/secfoo/web/templates/run_detail.html +++ b/src/secfoo/web/templates/run_detail.html @@ -141,6 +141,63 @@

Documentation coverage

{% endif %} +{% if tm_correlation and (tm_correlation.live_entry_points or tm_correlation.unmodeled_routes) %} +
+

Live traffic correlation

+ {% if tm_correlation.live_entry_points %} +

Live entry points

+
+
+ + + {% for ep in tm_correlation.live_entry_points %} + + + + + + + + {% endfor %} + +
IDEntry pointBoundaryMatched routesHits
{{ ep.id }}{{ ep.entry_point }}{{ ep.boundary_id }}{% if ep.boundary_label %} — {{ ep.boundary_label }}{% endif %}{% for r in ep.matched_routes %}{{ r }}{% if not loop.last %}, {% endif %}{% endfor %}{{ ep.hits }}
+
+ {% endif %} + + {% if tm_correlation.unmodeled_routes %} +

Unmodeled entry points (drift)

+
+
+ Live routes with no matching entry point: + {% for r in tm_correlation.unmodeled_routes %}{{ r.route }} ({{ r.hits }} hits){% if not loop.last %}, {% endif %}{% endfor %}. + Re-run threat modeling from the project page → +
+
+ {% endif %} + + {% if tm_correlation.prioritized_threats %} +

Threats ordered by live exposure

+
+ + + + {% for t in tm_correlation.prioritized_threats %} + + + + + + + + + {% endfor %} + +
IDThreatBoundarySeverityDispositionProduction traffic
{{ t.id }}{{ t.threat }}{{ t.boundary }}{{ t.severity }}{{ t.disposition }}{% if t.seen_in_production %}Seen in production{% else %}No traffic observed{% endif %}
+
+ {% endif %} + +{% endif %} + {% if report_html %}
{{ report_html | safe }} diff --git a/src/secfoo/web/threat_modeling_dashboard.py b/src/secfoo/web/threat_modeling_dashboard.py index 0c41c9c..10aec34 100644 --- a/src/secfoo/web/threat_modeling_dashboard.py +++ b/src/secfoo/web/threat_modeling_dashboard.py @@ -23,6 +23,7 @@ extract_model_depth, extract_threat_register_rows, ) +from secfoo.runtime.correlation import correlate_project_traffic from secfoo.storage.repository import RunRepository from secfoo.web.dashboard_common import ( append_boundary_changed_projects, @@ -95,6 +96,7 @@ class ThreatModelingDashboard: post_build_recent: list = field(default_factory=list) falsified_assumptions: list[dict] = field(default_factory=list) falsified_preview: list[dict] = field(default_factory=list) + gap_threats: list[dict] = field(default_factory=list) # Stored reports that could not be parsed (shown as a warning: not a clean scan). unparsable_reports: list[str] = field(default_factory=list) @@ -313,4 +315,33 @@ def build(repo: RunRepository) -> ThreatModelingDashboard: needs_rework.sort(key=lambda r: -findings_by_project.get(r["project_id"], 0)) dash.needs_rework = needs_rework + # Correlate Gap threats across latest models with live boundary traffic (#70): + # live internet-facing / production-hit Gaps sort strictly ahead of unvisited Gaps. + gap_threats: list[dict] = [] + severity_rank = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0} + for project in projects: + text = _read(project.get("latest_success_report_path"), errors=dash.unparsable_reports) + if not text: + continue + corr = correlate_project_traffic(repo, project["project_id"], report_markdown=text) + for item in corr.prioritized_threats: + if str(item.get("disposition", "")).strip().lower() != "gap": + continue + gap_threats.append( + { + **item, + "project_id": project["project_id"], + "project_display_name": project["project_display_name"], + "run_uuid": project.get("latest_success_run_uuid"), + } + ) + gap_threats.sort( + key=lambda t: ( + 1 if t.get("seen_in_production") else 0, + severity_rank.get(str(t.get("severity", "")).strip().lower(), -1), + ), + reverse=True, + ) + dash.gap_threats = gap_threats + return dash diff --git a/tests/test_web/test_threat_model_correlation.py b/tests/test_web/test_threat_model_correlation.py new file mode 100644 index 0000000..4276809 --- /dev/null +++ b/tests/test_web/test_threat_model_correlation.py @@ -0,0 +1,258 @@ +"""Tests for correlating live sensor traffic with threat-model entry points (#70).""" +from __future__ import annotations + +import json +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from secfoo.report import sca as sca_report +from secfoo.report.architecture import extract_entry_points, extract_trust_boundaries +from secfoo.runtime.correlation import correlate_project_traffic, match_route +from secfoo.runtime.evidence import ingest_events +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + +_TM_REPORT_WITH_ENTRY_POINTS = """# Threat Modeling Report + +## 1. Executive Summary +Internet upload endpoint exposes parsing dependencies. +**Overall risk rating:** High +**Model depth:** Full + +## 2. Scope & Assets +| ID | Entry point | Interface | Route / pattern | Boundary | +|----|-------------|-----------|-----------------|----------| +| E1 | Public upload API | HTTP | POST /upload | B1 | +| E2 | User profile lookup | HTTP | GET /users/{id} | B1 | +| E3 | Internal admin export | HTTP | POST /admin/export | B2 | + +## 3. Trust Boundaries & Data Flow +| ID | Boundary | What crosses it | +|----|----------|------------------| +| B1 | Internet -> API | Unauthenticated HTTPS payloads | +| B2 | Ops VPN -> Admin | Privileged export jobs | + +## 8. Threat Register +| ID | Threat | Archetype | Asset Class | Boundary | STRIDE | Severity | Disposition | Test Reference | +|----|--------|-----------|-------------|----------|--------|----------|--------------|-----------------| +| T1 | Unvisited admin privilege escalation | Missing authorization check | Process | B2 | E | High | Gap | none | +| T2 | Malicious YAML deserialization on upload | Unsafe deserialization | Process | B1 | T | Medium | Gap | none | +| T3 | Mitigated session fixation | Weak session validation | Data Flow | B1 | S | Low | Mitigated | tests/test_auth.py | +""" + +_LEGACY_TM_REPORT_WITHOUT_ENTRY_POINTS = """# Threat Modeling Report + +## 1. Executive Summary +**Overall risk rating:** Medium +**Model depth:** Lightweight + +## 2. Scope & Assets +Just prose describing the upload endpoint. + +## 8. Threat Register +| ID | Threat | Archetype | Asset Class | Boundary | STRIDE | Severity | Disposition | Test Reference | +|----|--------|-----------|-------------|----------|--------|----------|--------------|-----------------| +| T1 | Legacy threat | Missing auth | Process | B1 | E | Medium | Gap | none | +""" + +_SCA_REPORT = """# Software Composition Analysis Report + +## 1. Executive Summary +**Overall risk rating:** High + +## 2. Dependency Inventory +| Package | Version | Direct/Transitive | Ecosystem | Source manifest | +|---------|---------|--------------------|-----------|------------------| +| pyyaml | 5.3 | Direct | Python | requirements.txt | + +## 3. Risk Register +| ID | Package | Version | Issue | Severity | Reachability | Fixed in | +|----|---------|---------|-------|----------|--------------|----------| +| D1 | pyyaml | 5.3 | Arbitrary code execution | High | Reachable | 6.0 | + +## 4. Detailed Findings + +### [HIGH] D1: pyyaml@5.3 — Arbitrary code execution +- **Package / version:** pyyaml 5.3, **CVE:** unverified, **Severity:** High +- **Reachability:** Reachable, evidence in upload handler +- **Fixed in:** 6.0 +- **Recommendation:** Upgrade to 6.0 +""" + + +@pytest.fixture +def env(tmp_path, monkeypatch): + db_path = tmp_path / "db.sqlite" + reports_dir = tmp_path / "reports" + reports_dir.mkdir(parents=True, exist_ok=True) + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + monkeypatch.setattr("secfoo.web.routes.runs.STORE_DIR", tmp_path) + return {"db_path": db_path, "reports_dir": reports_dir, "tmp_path": tmp_path} + + +def test_entry_point_parser_handles_present_and_absent_tables(): + eps = extract_entry_points(_TM_REPORT_WITH_ENTRY_POINTS) + assert len(eps) == 3 + assert eps[0] == { + "id": "E1", + "entry_point": "Public upload API", + "interface": "HTTP", + "route": "POST /upload", + "boundary": "B1", + } + bounds = extract_trust_boundaries(_TM_REPORT_WITH_ENTRY_POINTS) + assert bounds["B1"]["boundary"] == "Internet -> API" + + assert extract_entry_points(_LEGACY_TM_REPORT_WITHOUT_ENTRY_POINTS) == [] + + +def test_route_matching_exact_templated_wildcard_and_unmatched(): + assert match_route("POST /upload", "POST /upload") + assert match_route("POST /upload/", "POST /upload") + assert not match_route("GET /upload", "POST /upload") + assert match_route("GET /users/42", "GET /users/{id}") + assert match_route("GET /items/abc-1", "GET /items/:id") + assert match_route("GET /api/v2/orders", "/api/*") + assert not match_route("POST /debug/shell", "POST /upload") + + +def test_correlation_prioritizes_live_gaps_and_surfaces_in_web_ui(env, monkeypatch): + monkeypatch.setattr("secfoo.web.sca_dashboard.osv.enrich_lookups", lambda repo, keys, **kw: False) + tm_path = env["reports_dir"] / "tm.md" + tm_path.write_text(_TM_REPORT_WITH_ENTRY_POINTS, encoding="utf-8") + sca_path = env["reports_dir"] / "sca.md" + sca_path.write_text(_SCA_REPORT, encoding="utf-8") + sca_fp = sca_report.findings_with_fingerprints(_SCA_REPORT)[0]["fingerprint"] + + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/api", "acme/api", "github") + tm_uuid = repo.create_run( + project_id=pid, skill_id="threat-modeling", skill_name="Threat Modeling", + agent_id="claude", confluence_urls=[], + ) + repo.complete_run( + tm_uuid, status="success", exit_code=0, duration_seconds=1.0, + report_path=str(tm_path), prompt_path=None, stderr_excerpt=None, + high_count=1, medium_count=1, low_count=1, + ) + sca_uuid = repo.create_run( + project_id=pid, skill_id="sca-reachability", skill_name="SCA Reachability", + agent_id="claude", confluence_urls=[], + ) + repo.complete_run( + sca_uuid, status="success", exit_code=0, duration_seconds=1.0, + report_path=str(sca_path), prompt_path=None, stderr_excerpt=None, + high_count=1, + ) + sca_run = repo.get_run(sca_uuid) + repo.upsert_sca_finding( + project_id=pid, fingerprint=sca_fp, run_id=sca_run.id, current_ref="D1", + package="pyyaml", version="5.3", ecosystem="PyPI", issue="Arbitrary code execution", + severity="High", reachability="Reachable", cve=None, + ) + + # Ingest live traffic: POST /upload (modeled E1 on B1) and POST /shadow/debug (unmodeled!) + ingest_events( + repo.connection, + pid, + [ + json.dumps( + { + "type": "session", + "id": "8f8a1c2e-0000-4000-8000-000000000010", + "language": "python", + "runtime": "3.12.4", + "source": "sensor", + "app": "api", + "env": "prod", + "started_at": "2026-11-28T10:00:00Z", + } + ), + json.dumps( + { + "type": "hit", + "session": "8f8a1c2e-0000-4000-8000-000000000010", + "finding_fingerprint": sca_fp, + "symbol": "yaml.load", + "route": "POST /upload", + "auth": "anonymous", + "count": 15, + "last_seen": "2026-11-28T10:05:00Z", + } + ), + json.dumps( + { + "type": "hit", + "session": "8f8a1c2e-0000-4000-8000-000000000010", + "finding_fingerprint": sca_fp, + "symbol": "yaml.unsafe_load", + "route": "POST /shadow/debug", + "auth": "anonymous", + "count": 3, + "last_seen": "2026-11-28T10:06:00Z", + } + ), + ], + ) + + corr = correlate_project_traffic(repo, pid) + assert [ep.id for ep in corr.live_entry_points] == ["E1"] + assert corr.live_entry_points[0].citation == "Reached via E1 (B1: Internet -> API)" + assert [r["route"] for r in corr.unmodeled_routes] == ["POST /shadow/debug"] + # Live Gap T2 (Medium on B1) MUST sort ahead of unvisited Gap T1 (High on B2)! + assert [t["id"] for t in corr.prioritized_threats] == ["T2", "T1", "T3"] + assert corr.prioritized_threats[0]["seen_in_production"] is True + assert corr.prioritized_threats[1]["seen_in_production"] is False + + client = TestClient(create_app()) + + # 1. Project page shows live entry points + unmodeled drift + proj_html = client.get(f"/projects/{pid}").text + assert "Public upload API" in proj_html + assert "POST /shadow/debug" in proj_html + assert "Unmodeled entry points (threat-model drift)" in proj_html + + # Re-run endpoint queues execute_runs with unmodeled route context + rerun_calls = [] + + class _SyncThread: + def __init__(self, target, daemon=True): + self._target = target + + def start(self): + self._target() + + monkeypatch.setattr("secfoo.web.routes.projects.threading.Thread", _SyncThread) + monkeypatch.setattr( + "secfoo.web.routes.projects.execute_runs", + lambda **kw: rerun_calls.append( + { + "skill_ids": kw["skill_ids"], + "context_text": Path(kw["context_sources"][0].location).read_text(encoding="utf-8"), + } + ) + or [], + ) + post_resp = client.post(f"/projects/{pid}/threat-modeling/rerun", follow_redirects=False) + assert post_resp.status_code == 303 + assert len(rerun_calls) == 1 + assert rerun_calls[0]["skill_ids"] == ["threat-modeling"] + assert "POST /shadow/debug" in rerun_calls[0]["context_text"] + + # 2. Threat model run page shows correlation & Seen in production + run_html = client.get(f"/runs/{tm_uuid}").text + assert "Live traffic correlation" in run_html + assert "Seen in production" in run_html + assert "POST /shadow/debug" in run_html + + # 3. Threat modeling dashboard orders T2 before T1 + tm_dash_html = client.get("/activities/threat-modeling").text + assert "Seen in production" in tm_dash_html + assert tm_dash_html.index("T2") < tm_dash_html.index("T1") + + # 4. SCA list + detail pages show Reached via E1 (B1: Internet -> API) + sca_list_html = client.get("/activities/sca-reachability/vulnerabilities").text + assert "Reached via E1 (B1: Internet -> API)" in sca_list_html