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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/secfoo/report/architecture.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@
r"^\|[^|]*\|\s*(?P<code>[A-Z&]{2,4})\s*\|(?P<conformance>[^|]*)\|", 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*(?P<id>E\d+)\s*\|(?P<entry_point>[^|]*)\|(?P<interface>[^|]*)\|"
r"(?P<route>[^|]*)\|(?P<boundary>[^|]*)\|\s*$",
re.MULTILINE,
)

# Threat Modeling's Trust Boundaries table: | ID | Boundary | What crosses it |
_TRUST_BOUNDARY_ROW_RE = re.compile(
r"^\|\s*(?P<id>B\d+)\s*\|(?P<boundary>[^|]*)\|(?P<what_crosses>[^|]*)\|\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(
Expand Down Expand Up @@ -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
Expand Down
222 changes: 222 additions & 0 deletions src/secfoo/runtime/correlation.py
Original file line number Diff line number Diff line change
@@ -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/<id>`), 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,
)
8 changes: 7 additions & 1 deletion src/secfoo/skills/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
71 changes: 69 additions & 2 deletions src/secfoo/web/routes/projects.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
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

router = APIRouter()


@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.
Expand All @@ -27,5 +38,61 @@
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)
Loading
Loading