diff --git a/src/secfoo/report/architecture.py b/src/secfoo/report/architecture.py index 14982303..74ba4487 100644 --- a/src/secfoo/report/architecture.py +++ b/src/secfoo/report/architecture.py @@ -264,3 +264,35 @@ def classify_design_verdict(value: str | None) -> str | None: if v.startswith("sound"): return "approve" return None + + +_VERDICT_LABELS = {"approve": "Sound", "conditions": "Sound with conditions", "reject": "Not sound"} +# Longest first: "sound" is a prefix of "sound with conditions". +_VERDICT_PREFIXES = ("sound with conditions", "not applicable", "not sound", "sound") + + +def split_design_verdict(value: str | None) -> tuple[str, str]: + """A Design verdict line -> (short label, the rest of the sentence). + + Agents write the verdict as a full sentence ("Not sound for any + deployment handling real users. It fits its declared purpose..."). The + label comes from classify_design_verdict, so it always agrees with the + badge colour and the gate-decision mix; the reason is whatever follows + the leading verdict phrase, for display beside the label. + """ + text = (value or "").strip() + lower = text.lower() + bucket = classify_design_verdict(text) + if bucket: + label = _VERDICT_LABELS[bucket] + elif lower.startswith(("not applicable", "n/a")): + label = "Not applicable" + else: + label = "Unclear" + rest = text + for prefix in _VERDICT_PREFIXES: + if lower.startswith(prefix): + rest = text[len(prefix):] + break + rest = rest.lstrip(" \t\u2014\u2013-:;,.").strip() + return label, (rest[:1].upper() + rest[1:]) if rest else "" diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 77c38169..13ed2c22 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -575,12 +575,16 @@ def activity_summary_by_project(self, skill_id: str) -> list[dict]: # (diagram, design verdict) -- a failed/timeout run has no # report to read, but shouldn't hide an earlier successful one. latest_success = self._conn.execute( - "SELECT report_path FROM runs WHERE skill_id = ? AND project_id = ? " + "SELECT run_uuid, report_path, finished_at FROM runs WHERE skill_id = ? AND project_id = ? " "AND status = 'success' AND report_path IS NOT NULL " "ORDER BY started_at DESC LIMIT 1", (skill_id, data["project_id"]), ).fetchone() data["latest_success_report_path"] = latest_success["report_path"] if latest_success else None + # Which run that content came from, and when -- so a verdict links + # to the review it was read from, not a later failed run. + data["latest_success_run_uuid"] = latest_success["run_uuid"] if latest_success else None + data["latest_success_at"] = latest_success["finished_at"] if latest_success else None summary.append(data) return summary @@ -1026,7 +1030,7 @@ def unreviewed_and_stale_projects(self, skill_id: str, *, stale_days: int = 365) (never reviewed, then oldest) first. """ projects = self._conn.execute( - "SELECT DISTINCT projects.id, projects.display_name, projects.kind " + "SELECT DISTINCT projects.id, projects.display_name, projects.kind, projects.last_run_at " "FROM projects JOIN assessments ON assessments.project_id = projects.id" ).fetchall() @@ -1045,6 +1049,7 @@ def unreviewed_and_stale_projects(self, skill_id: str, *, stale_days: int = 365) "project_display_name": project["display_name"], "project_kind": project["kind"], "state": "never_reviewed", + "last_activity_at": project["last_run_at"], "last_reviewed_at": None, "days_since_review": None, } @@ -1064,6 +1069,7 @@ def unreviewed_and_stale_projects(self, skill_id: str, *, stale_days: int = 365) "project_display_name": project["display_name"], "project_kind": project["kind"], "state": "stale", + "last_activity_at": project["last_run_at"], "last_reviewed_at": latest["started_at"], "days_since_review": round(days_since), } diff --git a/src/secfoo/web/architecture_dashboard.py b/src/secfoo/web/architecture_dashboard.py index 213c4295..a79db3f3 100644 --- a/src/secfoo/web/architecture_dashboard.py +++ b/src/secfoo/web/architecture_dashboard.py @@ -61,11 +61,18 @@ class ArchitectureDashboard: disposition_total: int = 0 exception_aging: dict[str, int] = field(default_factory=dict) stale_projects: list[dict] = field(default_factory=list) + # The "Unreviewed & stale" panel shows only the most recently active + # few. The full list above still labels review status on the By project + # rows that are shown. + recent_stale_projects: list[dict] = field(default_factory=list) root_causes: list[tuple[str, int]] = field(default_factory=list) gate_mix: dict[str, int] = field(default_factory=dict) top_standards: list[tuple[str, int]] = field(default_factory=list) +RECENT_STALE_LIMIT = 5 + + def build(repo: RunRepository) -> ArchitectureDashboard: dash = ArchitectureDashboard() @@ -166,8 +173,8 @@ def build(repo: RunRepository) -> ArchitectureDashboard: ) dash.uncovered_ccm_domains = [name for code, name in CCM_DOMAINS if not ccm_assessed[code]] - dash.root_causes = root_cause_counter.most_common(8) - dash.top_standards = standards_counter.most_common(5) + dash.root_causes = root_cause_counter.most_common() + dash.top_standards = standards_counter.most_common() dash.gate_mix = { "approve": gate_counter.get("approve", 0), "conditions": gate_counter.get("conditions", 0), @@ -176,5 +183,8 @@ def build(repo: RunRepository) -> ArchitectureDashboard: dash.stale_projects = repo.unreviewed_and_stale_projects(SKILL_ID, stale_days=STALE_DAYS) append_boundary_changed_projects(repo, SKILL_ID, projects, dash.stale_projects) + dash.recent_stale_projects = sorted( + dash.stale_projects, key=lambda p: p.get("last_activity_at") or "", reverse=True + )[:RECENT_STALE_LIMIT] return dash diff --git a/src/secfoo/web/dashboard_common.py b/src/secfoo/web/dashboard_common.py index 3bcef061..8b4a1c34 100644 --- a/src/secfoo/web/dashboard_common.py +++ b/src/secfoo/web/dashboard_common.py @@ -63,6 +63,7 @@ def append_boundary_changed_projects( "project_kind": project["project_kind"], "state": "boundary_changed", "last_reviewed_at": project.get("latest_started_at"), + "last_activity_at": project.get("latest_started_at"), "days_since_review": None, } ) diff --git a/src/secfoo/web/routes/activities.py b/src/secfoo/web/routes/activities.py index e1c5ea93..064ae355 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -21,7 +21,12 @@ from fastapi import APIRouter, Form, HTTPException, Request from fastapi.responses import RedirectResponse -from secfoo.report.architecture import count_trust_boundaries, extract_design_verdict, extract_mermaid_diagram +from secfoo.report.architecture import ( + count_trust_boundaries, + extract_design_verdict, + extract_mermaid_diagram, + split_design_verdict, +) from secfoo.skills.loader import SkillLoadError, load_skill from secfoo.storage.repository import RunRepository from secfoo.web import architecture_dashboard as arch_dashboard @@ -35,6 +40,11 @@ router = APIRouter() +# Design verdicts and the architecture "By project" table show only the +# newest reviews. Stat cards above them still count every project. +RECENT_VERDICTS_LIMIT = 5 +BY_PROJECT_RECENT_LIMIT = 6 + _GATE_MIX_COLORS = { "approve": "var(--color-success)", "conditions": "var(--color-warning)", @@ -81,6 +91,10 @@ def _attach_architecture_signals(projects: list[dict]) -> bool: text = Path(report_path).read_text(encoding="utf-8", errors="replace") project["diagram_source"] = extract_mermaid_diagram(text) project["design_verdict"] = extract_design_verdict(text) + if project["design_verdict"]: + # Agents write the verdict as a full sentence; badges show only + # the short label and the rest is displayed as wrapping text. + project["verdict_label"], project["verdict_reason"] = split_design_verdict(project["design_verdict"]) project["boundary_count"] = count_trust_boundaries(text) if project["diagram_source"]: any_diagram = True @@ -108,7 +122,12 @@ def _donut_gradient(counts: dict[str, int], color_map: dict[str, str]) -> str: @router.get("/activities/{skill_id}") -def activity_detail(request: Request, skill_id: str, diagram_project: int | None = None): +def activity_detail( + request: Request, + skill_id: str, + diagram_project: int | None = None, + stride_project: int | None = None, +): try: skill = load_skill(skill_id) except SkillLoadError as exc: @@ -126,6 +145,12 @@ def activity_detail(request: Request, skill_id: str, diagram_project: int | None ) diagrams_available = _attach_architecture_signals(projects) + verdict_count = sum(1 for p in projects if p.get("design_verdict")) + recent_verdicts = sorted( + (p for p in projects if p.get("design_verdict")), + key=lambda p: p.get("latest_success_at") or "", + reverse=True, + )[:RECENT_VERDICTS_LIMIT] # A gallery rendering every project's diagram at once doesn't scale # past a couple of projects -- instead show one at a time, picked via @@ -150,6 +175,15 @@ def activity_detail(request: Request, skill_id: str, diagram_project: int | None ), "run_count": sum(p["run_count"] for p in projects), "diagrams_available": diagrams_available, + "recent_verdicts": recent_verdicts, + # Architecture only: the table shows the newest projects. Other + # activities keep the full list. Review state (stale / boundary + # changed) is still resolved for every project, so the rows that + # are shown can be labelled. + "by_project_rows": projects[:BY_PROJECT_RECENT_LIMIT] if dash is not None else projects, + "by_project_total": len(projects), + "review_states": {p["project_id"]: p for p in dash.stale_projects} if dash else None, + "verdict_count": verdict_count, "diagram_projects": diagram_projects, "selected_diagram_project": selected_diagram_project, "mermaid_available": mermaid_bundle_available(), @@ -164,6 +198,12 @@ def activity_detail(request: Request, skill_id: str, diagram_project: int | None context["past_due_sla_days"] = arch_dashboard.PAST_DUE_SLA_DAYS if tm_dash is not None: context["past_due_sla_days"] = tm_dashboard.PAST_DUE_SLA_DAYS + # One project's STRIDE matrix at a time. The portfolio total above + # it still sums every project. + context["selected_stride_project"] = next( + (p for p in tm_dash.stride_by_project if p["project_id"] == stride_project), + None, + ) or (tm_dash.stride_by_project[0] if tm_dash.stride_by_project else None) if sca_dash is not None: context["sca_severity_gradient"] = _donut_gradient(sca_dash.severity_counts, _SCA_SEVERITY_COLORS) if sast_dash is not None: @@ -174,6 +214,28 @@ def activity_detail(request: Request, skill_id: str, diagram_project: int | None return templates.TemplateResponse(request, "activities/detail.html", context) +@router.get("/activities/threat-modeling/post-build") +def threat_modeling_post_build(request: Request): + """Every threat recorded with `secfoo miss`. The dashboard card shows + only the newest handful.""" + with RunRepository() as repo: + findings = repo.list_post_build_findings() + return templates.TemplateResponse( + request, "activities/threat_modeling_post_build.html", {"findings": findings} + ) + + +@router.get("/activities/threat-modeling/assumptions") +def threat_modeling_assumptions(request: Request): + """Every falsified assumption from the latest model of each project. + The dashboard card shows only the newest handful.""" + with RunRepository() as repo: + assumptions = tm_dashboard.build(repo).falsified_assumptions + return templates.TemplateResponse( + request, "activities/threat_modeling_assumptions.html", {"assumptions": assumptions} + ) + + @router.get("/activities/sast/findings") def sast_findings_list( request: Request, diff --git a/src/secfoo/web/sast_dashboard.py b/src/secfoo/web/sast_dashboard.py index f0edea04..294336e6 100644 --- a/src/secfoo/web/sast_dashboard.py +++ b/src/secfoo/web/sast_dashboard.py @@ -73,7 +73,7 @@ def build(repo: RunRepository) -> SastDashboard: exploitable_count += 1 dash.cvss_band_counts = {band: band_counter.get(band, 0) for band in _CVSS_BANDS} - dash.top_cwe_counts = cwe_counter.most_common(10) + dash.top_cwe_counts = cwe_counter.most_common() dash.funnel = { "findings": len(dash.open_findings), "exploitable": exploitable_count, diff --git a/src/secfoo/web/static/css/dashboard.css b/src/secfoo/web/static/css/dashboard.css index 65b37185..51ad39d9 100644 --- a/src/secfoo/web/static/css/dashboard.css +++ b/src/secfoo/web/static/css/dashboard.css @@ -190,3 +190,225 @@ tr.run-row:hover { background-color: var(--color-primary-50); } .u-border-t-warning-3 { border-top: 3px solid var(--color-warning) !important; } .u-wrap-anywhere { overflow-wrap: anywhere !important; } .u-cursor-pointer { cursor: pointer !important; } + +/* Design verdicts: agents write the verdict as a sentence. The badge shows + the short label; the reason wraps beside/under it instead of overflowing + a no-wrap badge. In the table it is clamped to two lines (full text in + the title tooltip). */ +.verdict-summary { display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-2); } +.verdict-summary > p { overflow-wrap: anywhere; max-width: 44rem; } +.verdict-table td { vertical-align: top; } +.verdict-reason { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + line-clamp: 2; + overflow: hidden; + overflow-wrap: anywhere; + min-width: 16rem; +} + +/* Widget info button (macro info_tip in _macros.html). */ +.has-info { position: relative; } +/* Stat cards clip their accent stripe with overflow:hidden. An open info + panel has to escape that clip, and sit above the next card. */ +.stat-card.has-info { overflow: visible; } +.stat-card.has-info:has(.info-tip[open]), +.card.has-info:has(.info-tip[open]) { z-index: 6; } +/* A stat card that is also a link: the hit target sits under the text so + the info button (higher z-index) still receives the click. */ +.stat-card__cover { position: absolute; inset: 0; z-index: 1; border-radius: inherit; } +.stat-card:has(.stat-card__cover) .stat-card__value, +.stat-card:has(.stat-card__cover) .stat-card__label, +.stat-card:has(.stat-card__cover) .stat-card__icon { position: relative; z-index: 2; pointer-events: none; } +.has-info > .card__title, +.has-info > .stat-card__label, +.has-info > .u-d-flex { padding-right: 2rem; } +.info-tip { position: absolute; top: var(--space-3); right: var(--space-3); z-index: 5; } +.info-tip--inline { position: relative; top: auto; right: auto; } +/* A heading followed by its info button: the button sits right after the + last word. Flex rather than an inline
, because WebKit always + lays
out as a block. */ +.heading-with-info { display: flex; align-items: center; flex-wrap: wrap; gap: var(--space-2); } +.info-tip__trigger { + list-style: none; + display: inline-flex; align-items: center; justify-content: center; + width: 1.25rem; height: 1.25rem; border-radius: 999px; + border: 1px solid var(--color-border); background: var(--color-surface); + color: var(--color-text-muted); font: italic 600 0.75rem/1 Georgia, "Times New Roman", serif; + cursor: pointer; user-select: none; + transition: color var(--duration-base, .15s), border-color var(--duration-base, .15s); +} +.info-tip__trigger::-webkit-details-marker { display: none; } +.info-tip__trigger::marker { content: ""; } +.info-tip__trigger:hover, .info-tip[open] > .info-tip__trigger { color: var(--color-primary-700, #1d4ed8); border-color: currentColor; } +.info-tip__trigger:focus-visible { outline: 2px solid var(--color-primary-600, #2563eb); outline-offset: 2px; } +.info-tip__panel { + position: absolute; top: calc(100% + var(--space-2)); right: 0; z-index: 20; + width: min(22rem, 80vw); + background: var(--color-surface); color: var(--color-text, inherit); + border: 1px solid var(--color-border); border-radius: var(--radius-md, 8px); + box-shadow: var(--shadow-lg, 0 10px 30px rgba(0,0,0,.12)); + padding: var(--space-4); text-align: left; + font: var(--text-body-sm); font-style: normal; font-weight: 400; letter-spacing: normal; text-transform: none; +} +.info-tip--inline .info-tip__panel { left: 0; right: auto; } +.info-tip__title { font-weight: 600; margin: 0 0 var(--space-2); } +.info-tip__panel p { margin: 0 0 var(--space-2); } +.info-tip__panel p:last-child { margin-bottom: 0; } + +/* Lists and tables marked data-scroll-rows: interactive.js sizes the box + to that many rows. Overflow only appears once there are more. */ +.widget-scroll { overflow-y: auto; overscroll-behavior: contain; } +.widget-scroll thead th { position: sticky; top: 0; z-index: 1; } + +/* Threat modeling: rework list, pattern bars, model-depth mix, STRIDE legend. + These sit in half- and third-width cards, so labels stack above their + bars instead of sharing a row with a fixed-width column. */ +.tm-accent { border-top: 3px solid var(--color-primary-600); } +.tm-accent--amber { border-top-color: var(--color-warning); } +.tm-accent--teal { border-top-color: var(--color-teal-500); } +.tm-accent--error { border-top-color: var(--color-error); } +.tm-panel__title { font: var(--text-h4); letter-spacing: -0.01em; margin-bottom: var(--space-4); width: 100%; } +.tm-panel__count { + margin-left: auto; + min-width: 1.5rem; height: 1.5rem; padding-inline: 0.45rem; + display: inline-flex; align-items: center; justify-content: center; + border-radius: var(--radius-pill); + background: var(--color-primary-50); color: var(--color-primary-700); + font: var(--text-caption); font-weight: 700; font-variant-numeric: tabular-nums; +} +.tm-accent--amber .tm-panel__count { background: var(--color-warning-bg); color: var(--color-warning); } +.tm-accent--teal .tm-panel__count { background: var(--color-teal-100); color: var(--color-teal-700); } + +.rework-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-2); } +.rework-row { + display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: var(--space-3); + padding: var(--space-3); + border: 1px solid var(--color-border); border-radius: var(--radius-md); + background: var(--color-surface); + text-decoration: none; color: inherit; + transition: border-color var(--duration-base) var(--ease-standard), + background-color var(--duration-base) var(--ease-standard), + box-shadow var(--duration-base) var(--ease-standard); +} +.rework-row:hover { border-color: var(--color-primary-300); background: var(--color-primary-50); box-shadow: var(--shadow-sm); } +.rework-row:focus-visible { outline: 2px solid var(--color-primary-500); outline-offset: 2px; } +.rework-row__mark { + width: 2.25rem; height: 2.25rem; border-radius: var(--radius-md); + display: grid; place-items: center; + font-weight: 700; font-size: 0.875rem; +} +.rework-row--never .rework-row__mark { background: var(--color-error-bg); color: var(--color-error); } +.rework-row--stale .rework-row__mark { background: var(--color-warning-bg); color: var(--color-warning); } +.rework-row__body { display: flex; flex-direction: column; align-items: flex-start; gap: var(--space-1); min-width: 0; } +.rework-row__name { font-weight: 600; line-height: 1.3; overflow-wrap: anywhere; } +.rework-row__when { font: var(--text-caption); color: var(--color-text-muted); white-space: nowrap; } +.rework-row__chevron { + width: 0.4rem; height: 0.4rem; margin-right: 0.15rem; + border-right: 2px solid var(--color-gray-400); border-top: 2px solid var(--color-gray-400); + transform: rotate(45deg); +} +[data-theme="dark"] .rework-row:hover { background: #0f3a4c; border-color: var(--color-primary-400); } +[data-theme="dark"] .tm-panel__count { background: #0f3a4c; color: var(--color-primary-200); } +[data-theme="dark"] .tm-accent--amber .tm-panel__count { background: var(--color-warning-bg); color: var(--color-warning); } +[data-theme="dark"] .tm-accent--teal .tm-panel__count { background: #0d3d3a; color: var(--color-teal-300); } + +.pattern-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-4); } +.pattern-row { display: grid; grid-template-columns: 1.75rem minmax(0, 1fr); align-items: center; gap: var(--space-3); } +.pattern-row__rank { + width: 1.75rem; height: 1.75rem; border-radius: var(--radius-circle); + display: grid; place-items: center; + background: var(--color-bg-subtle); color: var(--color-text-muted); + font-size: 0.6875rem; font-weight: 700; font-variant-numeric: tabular-nums; +} +.pattern-row--top .pattern-row__rank { background: var(--color-teal-100); color: var(--color-teal-700); } +.pattern-row__body { min-width: 0; } +.pattern-row__head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); } +.pattern-row__label { min-width: 0; font: var(--text-body-sm); font-weight: 600; color: var(--color-text); overflow-wrap: anywhere; } +.pattern-row__count { + flex-shrink: 0; min-width: 1.5rem; padding: 0 0.4rem; + border-radius: var(--radius-pill); background: var(--color-bg-subtle); + text-align: center; font: var(--text-caption); font-weight: 700; font-variant-numeric: tabular-nums; +} +.pattern-row--top .pattern-row__count { background: var(--color-teal-100); color: var(--color-teal-700); } +.pattern-row__track { + margin-top: var(--space-2); height: 0.5rem; border-radius: var(--radius-pill); + background: var(--color-gray-100); overflow: hidden; +} +.pattern-row__fill { + height: 100%; width: 0; border-radius: inherit; + background: linear-gradient(90deg, var(--color-teal-300), var(--color-teal-500)); +} +.pattern-row--top .pattern-row__fill { background: linear-gradient(90deg, var(--color-teal-500), var(--color-teal-700)); } +[data-theme="dark"] .pattern-row__track { background: var(--color-gray-900); } +[data-theme="dark"] .pattern-row__rank, +[data-theme="dark"] .pattern-row__count { background: var(--color-gray-900); color: var(--color-gray-300); } +[data-theme="dark"] .pattern-row--top .pattern-row__rank, +[data-theme="dark"] .pattern-row--top .pattern-row__count { background: #0d3d3a; color: var(--color-teal-300); } + +.depth-mix-bar { margin-top: var(--space-4); height: 0.55rem; gap: 3px; background: transparent; } +.depth-mix-bar .stacked-bar__segment { border-radius: var(--radius-pill); } +.depth-mix { list-style: none; margin: var(--space-4) 0 0; padding: 0; display: grid; gap: var(--space-2); } +.depth-mix__item { + display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--space-3); + padding: var(--space-3); border-radius: var(--radius-md); border: 1px solid transparent; +} +.depth-mix__item--full { background: var(--color-success-bg); } +.depth-mix__item--feature { background: var(--color-info-bg); } +.depth-mix__item--light { background: var(--color-warning-bg); } +.depth-mix__swatch { width: 0.625rem; height: 0.625rem; border-radius: var(--radius-circle); } +.depth-mix__name { display: block; font-weight: 600; font-size: 0.875rem; line-height: 1.3; } +.depth-mix__item .ds-caption { display: block; line-height: 1.35; } +.depth-mix__figure { display: flex; flex-direction: column; align-items: flex-end; gap: 0.125rem; } +.depth-mix__count { font-size: 1.125rem; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; } +.depth-mix__pct { font: var(--text-caption); color: var(--color-text-muted); font-variant-numeric: tabular-nums; } +.depth-mix__fill--full { background-color: var(--color-success); } +.depth-mix__fill--feature { background-color: var(--color-primary-400); } +.depth-mix__fill--light { background-color: var(--color-warning); } +.depth-mix__hint { + margin: var(--space-4) 0 0; padding: var(--space-3); + border-radius: var(--radius-md); background: var(--color-warning-bg); + font: var(--text-caption); line-height: 1.45; color: var(--color-warning); +} + +.miss-stats { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-2); margin-bottom: var(--space-4); } +.miss-stat { padding: var(--space-3); border-radius: var(--radius-md); background: var(--color-error-bg); } +.miss-stat--quiet { background: var(--color-bg-subtle); } +.miss-stat__value { display: block; font-size: 1.375rem; font-weight: 700; line-height: 1; font-variant-numeric: tabular-nums; } +.miss-stat__label { display: block; margin-top: var(--space-1); font: var(--text-caption); color: var(--color-text-muted); } +.miss-list, .assume-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--space-2); } +.assume-list { margin-top: var(--space-4); } +.miss-row, .assume-row { + display: grid; gap: var(--space-3); align-items: flex-start; + padding: var(--space-3); border-radius: var(--radius-md); +} +.miss-row { + grid-template-columns: auto minmax(0, 1fr); + background: var(--color-bg-subtle); text-decoration: none; color: inherit; + transition: background-color var(--duration-base) var(--ease-standard); +} +.miss-row:hover { background: var(--color-error-bg); } +.miss-row:focus-visible { outline: 2px solid var(--color-primary-500); outline-offset: 2px; } +.miss-row__mark { + width: 2rem; height: 2rem; border-radius: var(--radius-md); background: var(--color-error-bg); + display: grid; place-items: center; flex-shrink: 0; +} +.miss-row__mark::before { content: ""; width: 0.45rem; height: 0.45rem; border-radius: 50%; background: var(--color-error); } +.miss-row:hover .miss-row__mark { background: var(--color-surface); } +.miss-row__title, .assume-row__text { display: block; font: var(--text-body-sm); font-weight: 600; line-height: 1.35; overflow-wrap: anywhere; } +.miss-row__meta { display: block; margin-top: 0.15rem; font: var(--text-caption); color: var(--color-text-muted); } +.assume-row { grid-template-columns: auto minmax(0, 1fr); background: var(--color-warning-bg); } +.assume-row__mark { font-family: Georgia, "Times New Roman", serif; font-size: 1.35rem; line-height: 1; font-weight: 700; color: var(--color-warning); } +.assume-row__text { font-weight: 500; padding-top: 0.15rem; } +.signal-empty { + margin: var(--space-3) 0 0; padding: var(--space-3); border-radius: var(--radius-md); + background: var(--color-bg-subtle); font: var(--text-body-sm); color: var(--color-text-muted); +} +[data-theme="dark"] .miss-row:hover { background: #3d1a18; } +[data-theme="dark"] .miss-row:hover .miss-row__mark { background: var(--color-gray-800); } +.stride-legend { display: flex; flex-wrap: wrap; gap: var(--space-1) var(--space-4); margin-top: var(--space-3); } +.stride-legend abbr { text-decoration: none; font-weight: 600; } +.stride-key { display: inline-flex; align-items: center; gap: var(--space-1); } +.stride-key__swatch { width: 0.75rem; height: 0.75rem; border-radius: 3px; display: inline-block; } + diff --git a/src/secfoo/web/static/js/interactive.js b/src/secfoo/web/static/js/interactive.js index 76ca0fca..6ef36de2 100644 --- a/src/secfoo/web/static/js/interactive.js +++ b/src/secfoo/web/static/js/interactive.js @@ -115,3 +115,74 @@ document.addEventListener("change", function (event) { box.checked = all.checked; }); }); + +// Widget info buttons (
): one open at a time, +// closed by a click elsewhere or Escape (focus returns to the button). +document.addEventListener("toggle", function (event) { + const tip = event.target; + if (!(tip instanceof HTMLDetailsElement) || !tip.classList.contains("info-tip") || !tip.open) return; + document.querySelectorAll("details.info-tip[open]").forEach(function (other) { + if (other !== tip) other.open = false; + }); +}, true); +document.addEventListener("click", function (event) { + document.querySelectorAll("details.info-tip[open]").forEach(function (tip) { + if (!tip.contains(event.target)) tip.open = false; + }); +}); +document.addEventListener("keydown", function (event) { + if (event.key !== "Escape") return; + document.querySelectorAll("details.info-tip[open]").forEach(function (tip) { + tip.open = false; + const trigger = tip.querySelector("summary"); + if (trigger) trigger.focus(); + }); +}); + +// data-scroll-rows="10" on a list or a .table-wrap: show that many rows, +// then scroll. Measured from the rows themselves so wrapped text still +// counts as one row. ResizeObserver remeasures when the card gets narrower. +(function () { + const widgets = document.querySelectorAll("[data-scroll-rows]"); + if (!widgets.length) return; + + function rowsOf(el) { + const body = el.querySelector(":scope > table > tbody"); + return body ? [...body.children] : [...el.children]; + } + + function cap(el) { + const limit = parseInt(el.getAttribute("data-scroll-rows"), 10); + const rows = rowsOf(el); + if (!isFinite(limit) || limit < 1 || rows.length <= limit) { + if (el.style.maxHeight) el.style.maxHeight = ""; + return; + } + const style = getComputedStyle(el); + const extra = (parseFloat(style.paddingBottom) || 0) + (parseFloat(style.borderBottomWidth) || 0); + const height = Math.ceil( + rows[limit - 1].getBoundingClientRect().bottom - el.getBoundingClientRect().top + el.scrollTop + extra + ); + const next = height + "px"; + if (el.style.maxHeight !== next) el.style.maxHeight = next; + } + + function capAll() { + widgets.forEach(cap); + } + + capAll(); + if (typeof ResizeObserver === "undefined") { + window.addEventListener("resize", capAll); + return; + } + let framing = false; + const observer = new ResizeObserver(function () { + if (framing) return; + framing = true; + capAll(); + framing = false; + }); + widgets.forEach(function (el) { observer.observe(el); }); +})(); + diff --git a/src/secfoo/web/templates/_macros.html b/src/secfoo/web/templates/_macros.html index 59992b21..25e1bc14 100644 --- a/src/secfoo/web/templates/_macros.html +++ b/src/secfoo/web/templates/_macros.html @@ -40,3 +40,20 @@ {%- endfor %} {% endmacro %} + +{#- Small (i) button for a widget's top-right corner; clicking it explains + what the widget shows. A native
, so it works with no inline + script under the portal's CSP; static/js/interactive.js closes it on an + outside click or Escape and keeps one open at a time. The widget needs + the `has-info` class (position: relative). Pass inline=True to sit + after a section heading instead of in a corner. + Usage: {% call info_tip("Coverage") %}

...

{% endcall %} -#} +{% macro info_tip(title, inline=False) %} +
+ +
+

{{ title }}

+ {{ caller() }} +
+
+{% endmacro %} diff --git a/src/secfoo/web/templates/activities/architecture_dashboard.html b/src/secfoo/web/templates/activities/architecture_dashboard.html index 3ab9457a..49361e98 100644 --- a/src/secfoo/web/templates/activities/architecture_dashboard.html +++ b/src/secfoo/web/templates/activities/architecture_dashboard.html @@ -3,37 +3,64 @@ recurring root causes, gate decisions, and standards deviation. See web/architecture_dashboard.py for what's real vs. approximated. #} +{% from "_macros.html" import info_tip %} + Program dashboard
-
+
+ {% call info_tip("Coverage") %} +

Share of in-scope systems that have at least one successful architecture review.

+

In scope means every project that has an assessment.

+ {% endcall %} {{ dash.coverage_pct }}% Coverage — {{ dash.coverage_reviewed }} / {{ dash.coverage_in_scope }} in-scope systems
-
+
+ {% call info_tip("Exceptions past expiry") %} +

Active exceptions whose expiry date has already passed.

+

Close the exception, or record a new one with a later date, to take it off this count.

+ {% endcall %} {{ dash.exceptions_past_expiry }} Exceptions past expiry
-
+
+ {% call info_tip("Open findings past due") %} +

Findings a review left as Confirmed where that review is more than {{ past_due_sla_days }} days old.

+

Findings have no individual due dates, so the review's age stands in for one.

+ {% endcall %} {{ dash.open_findings_past_due }} Open findings past due (>{{ past_due_sla_days }}d)
-
+
+ {% call info_tip("Unverified mitigations") %} +

Findings the review marked Conditional: a fix was proposed, but not confirmed in the code.

+

Confirm the mitigation in the next review to move them off this count.

+ {% endcall %} {{ dash.unverified_mitigations }} Unverified mitigations
-
+
+ {% call info_tip("Cycle time p90") %} +

How many days nine out of ten assessments take, from start to completion.

+

One in ten takes longer than this number. A dash means no completed assessment has a duration yet.

+ {% endcall %} {{ dash.cycle_time_p90_days if dash.cycle_time_p90_days is not none else "—" }} Cycle time p90 (days)
-
+
+ {% call info_tip("CCM domain conformance") %} +

Average score per Cloud Controls Matrix domain, taken from each project's latest review.

+

Hatched bars were not assessed (process-assured or not applicable). That is not a failing score.

+ {% endcall %}

CCM domain conformance

Hatched = not assessed by review (process-assured or not applicable), not a failing score.

+
{% for row in dash.ccm_rows %}
{{ row.name }} @@ -47,10 +74,15 @@

CCM domain conformance

{{ row.code }} — {% if row.hatched %}not assessed{% else %}{{ row.score }}%{% endif %}
{% endfor %} +
-
+
+ {% call info_tip("Risk disposition") %} +

What happened to findings across the latest reviews.

+

Remediated is the drop in finding count between a project's last two reviews. Mitigated is a Conditional verdict. Accepted is an active recorded exception. Open is Confirmed and not yet past due. Past due is Confirmed on a review older than {{ past_due_sla_days }} days.

+ {% endcall %}

Risk disposition

{% if dash.disposition_total %}
@@ -73,7 +105,11 @@

Risk disposition

-
+
+ {% call info_tip("Exception aging") %} +

Active exceptions grouped by how soon they expire.

+

Past expiry is already overdue. The other three buckets are still inside 30, 60, and 90 days.

+ {% endcall %}

Exception aging

@@ -90,13 +126,23 @@

Exception aging

-

Unreviewed & stale

+
+

Unreviewed & stale + {% call info_tip("Unreviewed & stale", inline=True) %} +

In-scope projects whose architecture review is missing, stale (latest successful review is over a year old), or whose trust boundaries changed.

+

The table shows the most recently active of these.

+ {% endcall %} +

+ {% if dash.stale_projects | length > dash.recent_stale_projects | length %} + Latest {{ dash.recent_stale_projects | length }} of {{ dash.stale_projects | length }} + {% endif %} +
{% if dash.stale_projects %} -
+
- {% for p in dash.stale_projects %} + {% for p in dash.recent_stale_projects %}
ProjectStateLast reviewed
{{ p.project_display_name }} @@ -116,9 +162,15 @@

Unreviewed & stale

-

Top recurring root causes

+

Top recurring root causes + {% call info_tip("Top recurring root causes", inline=True) %} +

The most common root causes cited across architecture reviews, including older ones.

+

A cause that keeps coming back is best fixed once, at platform level, rather than project by project.

+ {% endcall %} +

{% if dash.root_causes %}
+
{% for cause, count in dash.root_causes %}
@@ -127,6 +179,7 @@

Top recurring root causes

{{ count }}
{% endfor %} +
{% else %}
No findings yet to aggregate.
@@ -135,7 +188,11 @@

Top recurring root causes

-
+
+ {% call info_tip("Gate decision mix") %} +

How each project's latest review was gated, from the design verdict in the report.

+

Approve is a sound design. With conditions can proceed once named fixes land. Reject should not proceed as designed.

+ {% endcall %}

Gate decision mix

@@ -149,9 +206,14 @@

Gate decision mix

-
+
+ {% call info_tip("Most-deviated standards") %} +

Standards the reviews cite most often as not being met.

+

A standard high on this list is a candidate for a shared control, rather than a one-off fix in each project.

+ {% endcall %}

Most-deviated standards

{% if dash.top_standards %} +
{% for standard, count in dash.top_standards %}
@@ -160,16 +222,21 @@

Most-deviated standards

{{ count }}
{% endfor %} +
{% else %}

No standard-specific findings cited yet.

{% endif %}
-
+
+ {% call info_tip("Uncovered CCM domains") %} +

Cloud Controls Matrix domains that no architecture review has assessed yet.

+

A domain listed here has no score. That is not the same as failing it.

+ {% endcall %}

Uncovered CCM domains

{{ dash.uncovered_ccm_domains | length }} / 17 {% if dash.uncovered_ccm_domains %} -
-
+
+ {% call info_tip("Model depth mix") %} +

How thorough each project's latest threat model was, as the model declares about itself.

+

Full covers the whole system. Feature-level covers one feature or new data flow. Lightweight is a fast checklist pass.

+

Lightweight models miss more. Critical systems should have a Full model; a mostly-lightweight portfolio means coverage looks better than it is.

+ {% endcall %}

Model depth mix

-
-
{{ tm_dash.model_depth_mix.full }}Full
-
{{ tm_dash.model_depth_mix.feature_level }}Feature-level
-
{{ tm_dash.model_depth_mix.lightweight }}Lightweight
+ {% set full_n = tm_dash.model_depth_mix.full %} + {% set feature_n = tm_dash.model_depth_mix.feature_level %} + {% set light_n = tm_dash.model_depth_mix.lightweight %} + {% set depth_total = full_n + feature_n + light_n %} +

How deep each project's latest model went{% if depth_total %} ({{ depth_total }} model{{ "s" if depth_total != 1 else "" }}){% endif %}.

+ {% if depth_total %} + + {% endif %} +
    +
  • + + FullWhole system: every component and trust boundary + {{ full_n }}{% if depth_total %}{{ (full_n / depth_total * 100) | round | int }}%{% endif %} +
  • +
  • + + Feature-levelOne feature or new data flow + {{ feature_n }}{% if depth_total %}{{ (feature_n / depth_total * 100) | round | int }}%{% endif %} +
  • +
  • + + LightweightFast checklist pass + {{ light_n }}{% if depth_total %}{{ (light_n / depth_total * 100) | round | int }}%{% endif %} +
  • +
+ {% if light_n > full_n %} +

More lightweight than full models: re-run critical systems at --depth standard.

+ {% endif %}
-
+
+ {% call info_tip("Threats found post-build") %} +

Threats discovered after release (an incident, a pen test, a later scan) that an earlier model should have caught.

+

Recorded by hand with secfoo miss, since a model can't know what it missed. A rising count means models are too shallow. This card shows the newest ones; the full list is on its own page.

+ {% endcall %}

Threats found post-build

- {{ tm_dash.post_build_count_recent }} - in the last 90 days ({{ tm_dash.post_build_count_total }} all-time) +
+
+ {{ tm_dash.post_build_count_recent }} + Last 90 days +
+
+ {{ tm_dash.post_build_count_total }} + All-time +
+
{% if tm_dash.post_build_recent %} -
-
+
+ {% call info_tip("Falsified assumptions") %} +

Assumptions a model relied on (for example, "only internal traffic reaches this service") that it then checked against the code and found false.

+

Each one marks a place where the design and the real system disagree. This card shows the newest ones; the full list is on its own page.

+ {% endcall %}

Falsified assumptions

- {{ tm_dash.falsified_assumptions | length }} - {% if tm_dash.falsified_assumptions %} -
    - {% for assumption in tm_dash.falsified_assumptions %} -
  • {{ assumption }}
  • +

    {{ tm_dash.falsified_assumptions | length }} checked against the code and found false.

    + {% if tm_dash.falsified_preview %} +
      + {% for item in tm_dash.falsified_preview %} +
    • + + {{ item.assumption }}{{ item.project }} +
    • {% endfor %}
    + {% if tm_dash.falsified_assumptions | length > tm_dash.falsified_preview | length %} + View all {{ tm_dash.falsified_assumptions | length }} → + {% endif %} {% else %} -

    No falsified assumptions recorded yet.

    +

    No falsified assumptions recorded yet.

    {% endif %}
diff --git a/src/secfoo/web/templates/activities/threat_modeling_post_build.html b/src/secfoo/web/templates/activities/threat_modeling_post_build.html new file mode 100644 index 00000000..ec527201 --- /dev/null +++ b/src/secfoo/web/templates/activities/threat_modeling_post_build.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} +{% block title %}Threats found post-build — secfoo{% endblock %} +{% block content %} +← Back to Threat Modeling +Threat Modeling +

Threats found post-build

+

+ Threats discovered after release that an earlier model should have caught. Recorded with secfoo miss. +

+ +{% if findings %} +
+ + + + + + {% for finding in findings %} + + + + + + + {% endfor %} + +
ThreatProjectDiscoveredFound by
{{ finding.title }}{{ finding.project_display_name }}{{ finding.discovered_at | fmt_time }}{{ finding.discovered_by or "—" }}
+
+{% else %} +
None recorded yet. Add one with secfoo miss.
+{% endif %} +{% endblock %} diff --git a/src/secfoo/web/templates/assessments/detail.html b/src/secfoo/web/templates/assessments/detail.html index 892e932c..60271cb6 100644 --- a/src/secfoo/web/templates/assessments/detail.html +++ b/src/secfoo/web/templates/assessments/detail.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% block title %}{{ assessment.project_display_name }} — secfoo{% endblock %} +{% from "_macros.html" import info_tip %} {% block content %} ← All assessments
@@ -65,7 +66,12 @@

Review pipeline

-

Findings by severity

+

Findings by severity + {% call info_tip("Findings by severity", inline=True) %} +

Severity counts from the runs attached to this assessment.

+

Repeat runs of the same activity count again, so this can be higher than the findings still open.

+ {% endcall %} +

{% for row in severity_rows %}
@@ -79,7 +85,7 @@

Findings by severity

Attached runs

{% if runs %} -
+
@@ -104,7 +110,7 @@

Attached runs

Attachments

AI-BOM: {{ models_count }} model(s), {{ tools_count }} tool(s) tracked.

{% if attachments %} -
+
StartedSkillAgentStatusCost
diff --git a/src/secfoo/web/templates/overview.html b/src/secfoo/web/templates/overview.html index 68e822fd..d7861aa8 100644 --- a/src/secfoo/web/templates/overview.html +++ b/src/secfoo/web/templates/overview.html @@ -1,5 +1,5 @@ {% extends "base.html" %} -{% from "_macros.html" import findings_badges %} +{% from "_macros.html" import findings_badges, info_tip %} {% block title %}secfoo — Dashboard{% endblock %} {% block content %} {% from "_icons.html" import icon %} @@ -64,27 +64,49 @@

Four steps to your first signed-off review

{% endif %}
-
+
+ {% call info_tip("Applications reviewed") %} +

Every application recorded in this local store.

+

A project appears here once it has been added, including ones that have not finished a review.

+ {% endcall %} {{ icon("projects") }} {{ projects | length }} Applications reviewed
-
+
+ {% call info_tip("Total findings") %} +

Finding counts written on runs, added up across every activity.

+

Repeat scans count again. This is not the same as Top findings, which lists open Critical and High items only.

+ {% endcall %} {{ icon("findings") }} {{ severity.total }} Total findings
- + +
+ {% call info_tip("Responsible AI coverage") %} +

Assessments that have a Responsible AI risk rating.

+

The rating comes from an attached Responsible AI Compliance run. An assessment without that run is not counted.

+ {% endcall %} +
{{ icon("responsible-ai") }} {{ responsible_ai_count }} Responsible AI coverage - -
+
+
+ {% call info_tip("AI spend") %} +

Cost that metered agents have reported back to secfoo.

+

Subscription agents run on your own plan and do not report a price, so they are not in this total.

+ {% endcall %} {{ icon("spend") }} {{ total_cost | fmt_cost }} AI spend @@ -99,7 +121,7 @@

Top findings across the program

in a report can appear here as Critical.

{% if top_findings %} -
+
FileKindUploaded
@@ -122,7 +144,11 @@

Top findings across the program

{% endif %}
-
+
+ {% call info_tip("Findings by severity") %} +

Counts the severity written in each run's report, summed across all runs.

+

Repeat scans count again. It can differ from Top findings, which lists open, de-duplicated items scored by CVSS.

+ {% endcall %}

Findings by severity

Counts the severity written in each run's report, summed across all runs (repeat scans count again). @@ -138,10 +164,14 @@

Findings by severity

{% endfor %}
-
+
+ {% call info_tip("Activity coverage") %} +

How many applications have at least one successful run of each activity.

+

The total is every application in this store, including ones that have never been scanned with that activity.

+ {% endcall %}

Activity coverage

Projects with at least one successful run of each activity.

-
SeveritySourceFindingProjectDetail
@@ -186,6 +225,7 @@

AI spend by agent

{% endfor %}
AgentRunsTokensCost
+

Subscription agents run on your own plan and don't report their cost to secfoo.

{% else %}

No runs yet.

@@ -195,7 +235,7 @@

AI spend by agent

Recent runs

{% if recent_runs %} -
    +
      {% for r in recent_runs %} {% set blocked = r.status in ('binary_not_found', 'failed', 'timeout') %}
    • @@ -221,7 +261,7 @@

      Recent runs

      Agents

      All agents →
-
    +
      {% for a in agents %}
    • {{ a.label }} {{ a.id }} @@ -236,7 +276,7 @@

      Agents

      Recent assessments

      {% if assessments %} -
      +
      diff --git a/src/secfoo/web/templates/responsible_ai.html b/src/secfoo/web/templates/responsible_ai.html index 92bcc799..369372b9 100644 --- a/src/secfoo/web/templates/responsible_ai.html +++ b/src/secfoo/web/templates/responsible_ai.html @@ -1,26 +1,39 @@ {% extends "base.html" %} {% block title %}secfoo — Responsible AI{% endblock %} +{% from "_macros.html" import info_tip %} {% block content %} {% from "_page.html" import page_head %} {{ page_head("responsible-ai", "Responsible AI", "Responsible AI risk mix", "Risk ratings are derived automatically from each assessment's attached Responsible AI Compliance run. An assessment stays \"provisional\" until its status is marked Completed.") }}
      -
      +
      + {% call info_tip("Assessments with a risk rating") %} +

      Assessments that have a Responsible AI risk rating.

      +

      The rating is taken from an attached Responsible AI Compliance run. An assessment without that run is not listed.

      + {% endcall %} {{ total }} Assessments with a risk rating
      -
      +
      + {% call info_tip("High-risk") %} +

      Of the rated assessments, how many the run marked high risk.

      +

      These are the ones to review first. The rating is the run's own, not a separate score secfoo computes.

      + {% endcall %} {{ high_risk }} High-risk
      -
      +
      + {% call info_tip("Provisional") %} +

      Ratings that are not final yet.

      +

      An assessment stays provisional until its status is marked Completed. Completing it does not change the risk level, only that the rating is signed off.

      + {% endcall %} {{ provisional }} Provisional
      {% if assessments %} -
      +
      ProjectTypeStatusFindingsReviewed
      diff --git a/src/secfoo/web/templates/third_party.html b/src/secfoo/web/templates/third_party.html index 5ff6b5aa..59ff133b 100644 --- a/src/secfoo/web/templates/third_party.html +++ b/src/secfoo/web/templates/third_party.html @@ -1,5 +1,5 @@ {% extends "base.html" %} -{% from "_macros.html" import findings_badges, empty_state %} +{% from "_macros.html" import findings_badges, empty_state, info_tip %} {% block title %}secfoo — Third-Party{% endblock %} {% block content %} {% from "_page.html" import page_head %} @@ -12,13 +12,18 @@ questionnaire). The conformance view below fills in from that evidence. {% endcall %} {% endif %} -
      +
      + {% call info_tip("Vendor CCM v4 conformance") %} +

      Average Cloud Controls Matrix score from each vendor's most recent Third-Party Risk Assessment.

      +

      Scores come from evidence in the vendor's documents (SOC 2, ISO, pen tests, questionnaires), never a guess. Hatched means no vendor has provided evidence for that domain yet, which is not a failing score.

      + {% endcall %}

      Vendor CCM v4 conformance

      Aggregated from {{ dash.assessed_vendor_count }} vendor(s)' most recent Third-Party Risk Assessment run -- evidence found in vendor-provided documents (SOC 2 reports, ISO certificates, pen test reports, questionnaires), never a guess. Hatched = no vendor has provided evidence for this domain yet, not a failing score.

      +
      {% for row in dash.ccm_rows %}
      {{ row.name }} @@ -32,10 +37,11 @@

      Vendor CCM v4 conformance

      {{ row.code }} — {% if row.hatched %}not assessed{% else %}{{ row.score }}%{% endif %}
      {% endfor %} +
      {% if assessments %} -
      +
      ProjectRiskRating statusAssessment status
      diff --git a/src/secfoo/web/threat_modeling_dashboard.py b/src/secfoo/web/threat_modeling_dashboard.py index 4db5e043..8945e318 100644 --- a/src/secfoo/web/threat_modeling_dashboard.py +++ b/src/secfoo/web/threat_modeling_dashboard.py @@ -28,6 +28,10 @@ SKILL_ID = "threat-modeling" +# The post-build and falsified-assumption cards show only the newest +# handful. The rest live on their own pages. +LIST_PREVIEW_LIMIT = 8 + # A Gap-disposition threat is "past due" once its most recent model is # older than this -- the same coarse, run-level proxy used for the # Security Architecture dashboard's "past due" tile, for the same reason @@ -81,7 +85,8 @@ class ThreatModelingDashboard: post_build_count_total: int = 0 post_build_count_recent: int = 0 post_build_recent: list = field(default_factory=list) - falsified_assumptions: list[str] = field(default_factory=list) + falsified_assumptions: list[dict] = field(default_factory=list) + falsified_preview: list[dict] = field(default_factory=list) def build(repo: RunRepository) -> ThreatModelingDashboard: @@ -131,7 +136,14 @@ def build(repo: RunRepository) -> ThreatModelingDashboard: if depth: depth_counter[depth] += 1 - falsified.extend(extract_falsified_assumptions(text)) + for assumption in extract_falsified_assumptions(text): + falsified.append( + { + "project_id": project["project_id"], + "project": project["project_display_name"], + "assumption": assumption, + } + ) # Both a per-project matrix (a blank cell is a real gap on that # specific system) and a running portfolio total (the same cell, @@ -245,6 +257,7 @@ def build(repo: RunRepository) -> ThreatModelingDashboard: "lightweight": depth_counter.get("Lightweight", 0), } dash.falsified_assumptions = falsified + dash.falsified_preview = falsified[:LIST_PREVIEW_LIMIT] # Recurring archetypes are aggregated across ALL successful runs, not # just the latest per project -- a pattern recurring over a project's @@ -258,11 +271,11 @@ def build(repo: RunRepository) -> ThreatModelingDashboard: for row in extract_threat_register_rows(text): if row["archetype"]: archetype_counter[row["archetype"]] += 1 - dash.recurring_patterns = archetype_counter.most_common(8) + dash.recurring_patterns = archetype_counter.most_common() dash.post_build_count_total = repo.post_build_findings_count() dash.post_build_count_recent = repo.post_build_findings_count(since_days=POST_BUILD_TREND_WINDOW_DAYS) - dash.post_build_recent = repo.list_post_build_findings(limit=5) + dash.post_build_recent = repo.list_post_build_findings(limit=LIST_PREVIEW_LIMIT) needs_rework = repo.unreviewed_and_stale_projects(SKILL_ID, stale_days=STALE_DAYS) append_boundary_changed_projects(repo, SKILL_ID, projects, needs_rework) diff --git a/tests/test_web/test_architecture_review_status.py b/tests/test_web/test_architecture_review_status.py new file mode 100644 index 00000000..a96133ae --- /dev/null +++ b/tests/test_web/test_architecture_review_status.py @@ -0,0 +1,109 @@ +"""Security Architecture page: "Unreviewed & stale" shows the five most +recently active projects, "By project" shows the six newest, and review +status is the last column of that table.""" + +from __future__ import annotations + +import re + +import pytest +from fastapi.testclient import TestClient + +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + +SKILL = "security-architecture-review" +REPORT = "# Security Architecture Review Report\n\n**Design verdict:** Sound\n" + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + return TestClient(create_app()) + + +def _project(repo: RunRepository, name: str, last_run_at: str) -> int: + project_id = repo.upsert_project(f"https://github.com/{name}", name, "github") + repo.create_assessment(project_id=project_id, assessment_type="internal", status="in_progress") + repo._conn.execute("UPDATE projects SET last_run_at = ? WHERE id = ?", (last_run_at, project_id)) + repo._conn.commit() + return project_id + + +def _run(repo: RunRepository, tmp_path, project_id: int, *, status: str, started_at: str) -> None: + run_uuid = repo.create_run(project_id=project_id, skill_id=SKILL, skill_name="Security Architecture Review", + agent_id="claude", confluence_urls=[]) + path = tmp_path / f"{run_uuid}.md" + path.write_text(REPORT) + repo.complete_run(run_uuid, status=status, exit_code=0 if status == "success" else 1, duration_seconds=1.0, + report_path=str(path) if status == "success" else None, prompt_path=None, stderr_excerpt=None) + repo._conn.execute("UPDATE runs SET started_at = ? WHERE run_uuid = ?", (started_at, run_uuid)) + repo._conn.commit() + + +def _section(html: str, start: str, end: str) -> str: + i = html.index(start) + return html[i:html.index(end, i)] + + +def test_stale_panel_shows_the_five_most_recently_active(client): + repo = RunRepository() + for day in range(1, 8): # seven never-reviewed projects, last active on days 1..7 + _project(repo, f"acme/svc-{day}", f"2026-11-0{day}T09:00:00+00:00") + repo.close() + + html = client.get(f"/activities/{SKILL}").text + panel = _section(html, "Unreviewed & stale", "
      ProjectStatusFindingsReviewed
      ") + assert re.findall(r"acme/svc-(\d)", panel) == ["7", "6", "5", "4", "3"] + assert "Latest 5 of 7" in panel + + +def test_by_project_ends_with_each_projects_review_status(client, tmp_path): + repo = RunRepository() + current = _project(repo, "acme/current", "2026-11-07T09:00:00+00:00") + _run(repo, tmp_path, current, status="success", started_at="2026-11-07T09:00:00+00:00") + stale = _project(repo, "acme/stale", "2024-01-01T09:00:00+00:00") + _run(repo, tmp_path, stale, status="success", started_at="2024-01-01T09:00:00+00:00") + broken = _project(repo, "acme/broken", "2026-11-06T09:00:00+00:00") + _run(repo, tmp_path, broken, status="failed", started_at="2026-11-06T09:00:00+00:00") + repo.close() + + html = client.get(f"/activities/{SKILL}").text + table = _section(html, 'id="by-project"', "
") + header = re.findall(r"([^<]*)", table) + assert header[-1] == "Review status" + + def status_of(name: str) -> str: + row = re.search(rf"]*>(?:(?!).)*{re.escape(name)}(?:(?!).)*", table, re.S).group(0) + cells = re.findall(r"]*>(.*?)", row, re.S) + return re.sub(r"<[^>]+>", "", cells[-1]).strip() + + assert status_of("acme/current") == "Current" + assert re.fullmatch(r"Stale \(\d+d\)", status_of("acme/stale")) + assert status_of("acme/broken") == "No successful review" + + +def test_by_project_shows_the_six_newest(client, tmp_path): + repo = RunRepository() + for day in range(1, 9): + project_id = _project(repo, f"acme/svc-{day}", f"2026-11-0{day}T09:00:00+00:00") + _run(repo, tmp_path, project_id, status="success", started_at=f"2026-11-0{day}T09:00:00+00:00") + repo.close() + + html = client.get(f"/activities/{SKILL}").text + table = _section(html, 'id="by-project"', "") + assert re.findall(r"acme/svc-(\d)", table) == ["8", "7", "6", "5", "4", "3"] + assert "Latest 6 of 8" in table + + +def test_other_activities_have_no_review_status_column(client, tmp_path): + repo = RunRepository() + project_id = _project(repo, "acme/app", "2026-11-07T09:00:00+00:00") + run_uuid = repo.create_run(project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", + confluence_urls=[]) + repo.complete_run(run_uuid, status="success", exit_code=0, duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt=None) + repo.close() + html = client.get("/activities/sast").text + assert "Review status" not in html diff --git a/tests/test_web/test_design_verdicts.py b/tests/test_web/test_design_verdicts.py new file mode 100644 index 00000000..2b262957 --- /dev/null +++ b/tests/test_web/test_design_verdicts.py @@ -0,0 +1,118 @@ +"""The Security Architecture page's Design verdicts panel and the verdict +shown on the architecture diagram card. + +Agents write the verdict as a full sentence, so the page shows a short +label in the badge and the rest as wrapping text -- never the whole +sentence inside a (no-wrap) badge -- and the panel lists only the newest +reviews. +""" + +from __future__ import annotations + +import re + +import pytest +from fastapi.testclient import TestClient + +from secfoo.report.architecture import split_design_verdict +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + return TestClient(create_app()) + + +def _report(verdict: str) -> str: + return ( + "# Security Architecture Review Report\n\n## 3. Data Flow Diagram\n\n```mermaid\nflowchart LR\n" + " a([User]) -->|\"B1: HTTPS\"| b[\"API\"]\n```\n\n" + f"## 11. Design Verdict & Remediation Roadmap\n\n**Design verdict:** {verdict}\n" + ) + + +def _seed(tmp_path, project: str, verdict: str, finished_at: str) -> str: + repo = RunRepository() + project_id = repo.upsert_project(f"https://github.com/{project}", project, "github") + run_uuid = repo.create_run(project_id=project_id, skill_id="security-architecture-review", + skill_name="Security Architecture Review", agent_id="claude", confluence_urls=[]) + path = tmp_path / f"{run_uuid}.md" + path.write_text(_report(verdict)) + repo.complete_run(run_uuid, status="success", exit_code=0, duration_seconds=1.0, report_path=str(path), + prompt_path=None, stderr_excerpt=None) + repo._conn.execute("UPDATE runs SET finished_at = ? WHERE run_uuid = ?", (finished_at, run_uuid)) + repo._conn.commit() + repo.close() + return run_uuid + + +@pytest.mark.parametrize( + "verdict, label, reason", + [ + ("Sound", "Sound", ""), + ("Sound.", "Sound", ""), + ("Sound with conditions: rotate the signing key first", "Sound with conditions", + "Rotate the signing key first"), + ("Not sound for any deployment handling real users or data. It fits its training purpose.", + "Not sound", "For any deployment handling real users or data. It fits its training purpose."), + ("Not sound — but only in the trivial sense that no design is present", "Not sound", + "But only in the trivial sense that no design is present"), + ("Not applicable — there is no design to render a verdict on", "Not applicable", + "There is no design to render a verdict on"), + ("Inconclusive pending the vendor's docs", "Unclear", "Inconclusive pending the vendor's docs"), + (None, "Unclear", ""), + ], +) +def test_split_design_verdict(verdict, label, reason): + assert split_design_verdict(verdict) == (label, reason) + + +def _badges(html: str) -> list[str]: + return [b.strip() for b in re.findall(r'([^<]*)', html)] + + +def test_panel_lists_the_five_newest_reviews_newest_first(client, tmp_path): + for day in range(1, 8): # seven projects, reviewed on days 1..7 + _seed(tmp_path, f"acme/app-{day}", "Not sound for production use. Details follow.", f"2026-11-0{day}T10:00:00") + html = client.get("/activities/security-architecture-review").text + panel = html[html.index("Design verdicts"):html.index("", html.index("Design verdicts"))] + + shown = re.findall(r"acme/app-(\d)", panel) + assert shown == ["7", "6", "5", "4", "3"] + assert "Latest 5 of 7 projects" in panel + # The badge carries only the short label; the sentence is the "Why". + assert "Not sound" in _badges(panel) + assert all(len(b) <= len("Sound with conditions") for b in _badges(panel)) + assert "For production use. Details follow" in panel + + +def test_panel_row_links_to_the_review_the_verdict_came_from(client, tmp_path): + good = _seed(tmp_path, "acme/app", "Sound", "2026-11-01T10:00:00") + repo = RunRepository() + project_id = repo.upsert_project("https://github.com/acme/app", "acme/app", "github") + failed = repo.create_run(project_id=project_id, skill_id="security-architecture-review", + skill_name="Security Architecture Review", agent_id="claude", confluence_urls=[]) + repo.complete_run(failed, status="failed", exit_code=1, duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt="boom") + repo.close() + + html = client.get("/activities/security-architecture-review").text + # Only the verdicts panel: the "By project" table rightly links the latest run. + panel = html[html.index("Design verdicts"):html.index("", html.index("Design verdicts"))] + assert f'data-href="/runs/{good}"' in panel + assert f'data-href="/runs/{failed}"' not in panel + + +def test_diagram_card_shows_label_badge_and_wrapping_reason(client, tmp_path): + long_verdict = "Not sound for any deployment handling real users or data. It fits its declared purpose." + _seed(tmp_path, "acme/app", long_verdict, "2026-11-01T10:00:00") + html = client.get("/activities/security-architecture-review").text + card = html[html.index("Architecture diagram"):] + assert long_verdict not in _badges(card) + assert "Not sound" in _badges(card) + assert '
') >= 3 + assert 'name="stride_project"' in text + assert "acme/app-a" in text and "acme/app-b" in text + section = text[text.index("By project"):text.index("Threat disposition")] + # app-b was seeded second, so it is the newest and the default selection. + assert section.count("Falsified assumptions"):page.index('id="by-project"')] + assert "Assumption number 1 is false" in card + assert "Assumption number 8 is false" in card + assert "Assumption number 9 is false" not in card + assert "View all 12" in card + + full = client.get("/activities/threat-modeling/assumptions") + assert full.status_code == 200 + assert "Assumption number 12 is false" in full.text + assert "Assumption number 1 is false" in full.text + + +def test_post_build_card_keeps_eight_and_links_to_the_rest(client, tmp_path): + project_id, _, _ = _seed(tmp_path) + repo = RunRepository() + for day in range(1, 11): + repo.create_post_build_finding( + project_id=project_id, title=f"Miss {day}", discovered_at=f"2026-01-{day:02d}", + ) + repo.close() + + page = client.get("/activities/threat-modeling").text + card = page[page.index(">Threats found post-build"):page.index(">Falsified assumptions")] + assert "Miss 10" in card and "Miss 3" in card + assert "Miss 2" not in card + assert "View all 10" in card + + full = client.get("/activities/threat-modeling/post-build") + assert full.status_code == 200 + assert "Miss 1" in full.text and "Miss 10" in full.text + + def test_dashboard_shows_accept_cli_hint(client, tmp_path): _seed(tmp_path) resp = client.get("/activities/threat-modeling") diff --git a/tests/test_web/test_widget_info_tips.py b/tests/test_web/test_widget_info_tips.py new file mode 100644 index 00000000..6b6a5568 --- /dev/null +++ b/tests/test_web/test_widget_info_tips.py @@ -0,0 +1,220 @@ +"""Widget info buttons (macro info_tip) on the Threat Modeling dashboard, +and the clearer Model depth mix / STRIDE matrix.""" + +from __future__ import annotations + +import html +import re +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + +STATIC_JS = Path(__file__).parents[2] / "src" / "secfoo" / "web" / "static" / "js" / "interactive.js" + +TM_REPORT = """\ +# Threat Modeling Report + +## 1. Executive Summary +Summary. **Overall risk rating:** High + +**Model depth:** {depth} + +## Threat Register +| ID | Threat | STRIDE | Asset class | Archetype | Disposition | Test reference | +|----|--------|--------|-------------|-----------|-------------|----------------| +| T1 | Forged token | S | Process | Auth bypass | Gap | none | +""" + + +@pytest.fixture +def client(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + return TestClient(create_app()) + + +def _seed(tmp_path, project: str, depth: str) -> None: + repo = RunRepository() + project_id = repo.upsert_project(f"https://github.com/{project}", project, "github") + repo.create_assessment(project_id=project_id, assessment_type="internal", status="in_progress") + run_uuid = repo.create_run(project_id=project_id, skill_id="threat-modeling", skill_name="Threat Modeling", + agent_id="claude", confluence_urls=[]) + path = tmp_path / f"{run_uuid}.md" + path.write_text(TM_REPORT.format(depth=depth)) + repo.complete_run(run_uuid, status="success", exit_code=0, duration_seconds=1.0, report_path=str(path), + prompt_path=None, stderr_excerpt=None) + repo.close() + + +WIDGETS = [ + "Coverage", "Open threats past due", "Mitigated but untested", "Median threats per model", + "STRIDE × asset-class coverage", "Threat disposition", "Accepted threats", "Models needing rework", + "Recurring threat patterns", "Model depth mix", "Threats found post-build", "Falsified assumptions", +] + + +def test_every_threat_modeling_widget_has_an_info_tip(client, tmp_path): + _seed(tmp_path, "acme/app", "Lightweight") + html = client.get("/activities/threat-modeling").text + tips = re.findall(r'
.*?
', html, re.S) + titles = [re.search(r'

([^<]*)

', t).group(1) for t in tips] + # The activity page also shows the generic severity card under the + # program dashboard. Architecture, SAST, SCA, and secret scanning hide it. + assert titles == WIDGETS + ["Findings by severity"] + for tip in tips: + # An accessible button and a real explanation, not an empty panel. + assert 'aria-label="What is' in tip + body = re.sub(r"<[^>]+>", " ", tip.split('class="info-tip__title"', 1)[1]) + assert len(body.split()) >= 15 + + +def test_model_depth_mix_explains_each_depth(client, tmp_path): + _seed(tmp_path, "acme/a", "Lightweight") + _seed(tmp_path, "acme/b", "Lightweight") + _seed(tmp_path, "acme/c", "Full") + html = client.get("/activities/threat-modeling").text + card = html[html.index('

Model depth mix

'):] + card = card[:card.index("")] + assert "(3 models)" in card + assert "Whole system" in card and "One feature or new data flow" in card and "Fast checklist pass" in card + counts = re.findall(r'(\d+)', card) + assert counts == ["1", "0", "2"] + assert "More lightweight than full models" in html + + +def test_no_lightweight_hint_when_models_are_full(client, tmp_path): + _seed(tmp_path, "acme/a", "Full") + assert "More lightweight than full models" not in client.get("/activities/threat-modeling").text + + +def test_stride_matrix_names_its_letters_and_colours(client, tmp_path): + _seed(tmp_path, "acme/app", "Full") + html = client.get("/activities/threat-modeling").text + for name in ("Spoofing", "Tampering", "Repudiation", "Information disclosure", "Denial of service", + "Elevation of privilege"): + assert f'' in html + assert "None found" in html and "1–2 threats" in html and "3 or more" in html + + +def test_info_tips_close_on_outside_click_and_escape(): + js = STATIC_JS.read_text() + assert "details.info-tip[open]" in js + assert '"Escape"' in js and '"toggle"' in js + + +def test_long_lists_scroll_after_ten_rows(): + js = STATIC_JS.read_text() + assert "[data-scroll-rows]" in js + assert "maxHeight" in js + tm = (STATIC_JS.parents[2] / "templates" / "activities" / "threat_modeling_dashboard.html").read_text() + for marker in ("rework-list widget-scroll", "pattern-list widget-scroll", "miss-list widget-scroll", "assume-list widget-scroll"): + assert marker in tm + assert tm.count('data-scroll-rows="10"') >= 4 + assert 'miss-list widget-scroll" data-scroll-rows="6"' in tm + assert 'assume-list widget-scroll" data-scroll-rows="6"' in tm + + +def _assert_titled_tips(page: str, expected: list[str]) -> None: + tips = re.findall(r'
.*?
', page, re.S) + titles = [ + html.unescape(re.search(r'

([^<]*)

', tip).group(1)) + for tip in tips + ] + assert titles == expected + for tip in tips: + assert 'aria-label="What is' in tip + body = re.sub(r"<[^>]+>", " ", tip.split('class="info-tip__title"', 1)[1]) + assert len(body.split()) >= 15, body + + +@pytest.mark.parametrize( + ("path", "titles"), + [ + ( + "/activities/security-architecture-review", + [ + "Coverage", "Exceptions past expiry", "Open findings past due", + "Unverified mitigations", "Cycle time p90", "CCM domain conformance", + "Risk disposition", "Exception aging", "Unreviewed & stale", + "Top recurring root causes", "Gate decision mix", "Most-deviated standards", + "Uncovered CCM domains", + ], + ), + ( + "/activities/sast", + [ + "Open findings", "Exploitable", "Verified", "Severe", "Awaiting sign-off", + "CVSS severity", "Top vulnerability types", "Top findings", + ], + ), + ( + "/activities/sca-reachability", + [ + "Coverage", "Distinct vulnerabilities", "Reachable", "Unrecognized ecosystem", + "Severity", "Vulnerabilities by ecosystem", "Top vulnerabilities", + ], + ), + ( + "/activities/secret-scanning", + [ + "Secrets found", "Looks live", "Found in documentation", + "Version-control history only", "Severity", "By source", "Top findings", + ], + ), + ( + "/", + [ + "Applications reviewed", "Total findings", "Third-party assessments", + "Responsible AI coverage", "AI spend", "Findings by severity", + "Activity coverage", "Responsible AI risk mix", "AI spend by agent", + ], + ), + ("/third-party", ["Vendor CCM v4 conformance"]), + ("/responsible-ai", ["Assessments with a risk rating", "High-risk", "Provisional"]), + ( + "/activities/prompt-review", + ["Projects covered", "Runs", "Total findings", "Critical + High", "Findings by severity"], + ), + ], +) +def test_program_pages_explain_each_widget(client, path, titles): + resp = client.get(path) + assert resp.status_code == 200 + _assert_titled_tips(resp.text, titles) + + +def test_linked_stat_cards_keep_the_info_button_clickable(client): + """The info control must not sit inside the link, or the click both + opens the note and navigates away.""" + sast = client.get("/activities/sast").text + overview = client.get("/").text + assert '{title}\s*
', html) + assert heading, f"{title}: info button must come right after the heading text" + assert "heading-with-info" in heading.group(1)