diff --git a/src/secfoo/report/generic.py b/src/secfoo/report/generic.py new file mode 100644 index 0000000..4fc7833 --- /dev/null +++ b/src/secfoo/report/generic.py @@ -0,0 +1,210 @@ +"""Extracts structured findings from any report following the generic OUTPUT_CONTRACT. + +Used by generic/custom skills (and built-ins without a dedicated contract like +`prompt-review` or `deployment-readiness`) to drive `generic_findings` lifecycle +and the dynamic activity dashboard (#92). +""" + +from __future__ import annotations + +import hashlib +import re +from dataclasses import dataclass + +from secfoo.report.markdown import ( + MalformedReportError, + detail_blocks, + example_finding_ids, + parse_report, + prose_source, +) +from secfoo.report.markdown import section as _extract_section +from secfoo.report.severity import extract_overall_risk_rating + +_REGISTER_5COL_RE = re.compile( + r"^\|\s*`?(?P[A-Za-z]+\d+)`?\s*\|(?P[^|]*)\|(?P<severity>[^|]*)\|" + r"(?P<cwe>[^|]*)\|(?P<verdict>[^|]*)\|\s*$", + re.MULTILINE, +) + +# Tolerates reports that omit the CWE column: | ID | Finding | Severity | Verdict | +_REGISTER_4COL_RE = re.compile( + r"^\|\s*`?(?P<id>[A-Za-z]+\d+)`?\s*\|(?P<title>[^|]*)\|(?P<severity>[^|]*)\|(?P<verdict>[^|]*)\|\s*$", + re.MULTILINE, +) + +_DETAIL_HEADING_RE = re.compile( + r"^###\s*\[(?P<severity>[^\]]+)\]\s*(?:(?P<id>[A-Za-z]+\d+)\s*:\s*)?(?P<title>.+?)\s*$", + re.MULTILINE, +) + +_VERDICT_FIELD_RE = re.compile(r"\*\*Verdict:\*\*\s*([^\n]+)", re.IGNORECASE) +_CWE_FIELD_RE = re.compile(r"\*\*CWE:\*\*\s*([^\n]+)", re.IGNORECASE) +_NO_FINDINGS_RE = re.compile(r"\bno findings\b|\bnone found\b|\bno issues\b", re.IGNORECASE) + +CANONICAL_SEVERITIES = ("critical", "high", "medium", "low", "info") + + +@dataclass(frozen=True) +class GenericExtraction: + findings: list[dict[str, str]] + overall_rating: str | None + contract_valid: bool + + +def normalize_generic_severity(value: str | None) -> str: + """Normalize canonical severities while keeping custom words intact.""" + cleaned = (value or "").strip().strip("`*").strip().lower() + if not cleaned: + return "unknown" + if cleaned == "informational": + return "info" + return cleaned + + +def _clean_cell(value: str | None) -> str: + return (value or "").strip().strip("`").strip() + + +def _normalize_cwe(cwe: str | None) -> str: + cleaned = _clean_cell(cwe) + if not cleaned or cleaned.lower() in {"unverified", "none", "n/a", "-"}: + return "" + return cleaned.upper() + + +def _normalize_verdict(verdict: str | None) -> str: + cleaned = _clean_cell(verdict) + if not cleaned: + return "" + # Strip trailing parenthetical precondition note: "Conditional (if ...)" -> "Conditional" + head = cleaned.split("(", 1)[0].strip() + return head or cleaned + + +def fingerprint_for_generic_finding( + skill_id: str, + *, + title: str, + cwe: str = "", + ref: str = "", + occurrence: int = 0, +) -> str: + """Stable identity for one generic finding across runs of the same skill.""" + norm_title = re.sub(r"\s+", " ", (title or "").strip().lower()) + norm_cwe = _normalize_cwe(cwe) + key_part = norm_title or ref.strip().lower() + raw = f"generic\0{skill_id}\0{norm_cwe}\0{key_part}\0{occurrence}" + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32] + + +def _extract_register_rows(report_markdown: str) -> list[dict[str, str]]: + reg_section = prose_source(_extract_section(report_markdown, "Findings Register")) + if not reg_section.strip(): + return [] + rows: list[dict[str, str]] = [] + for match in _REGISTER_5COL_RE.finditer(reg_section): + d = {k: _clean_cell(v) for k, v in match.groupdict().items()} + rows.append(d) + if rows: + return rows + for match in _REGISTER_4COL_RE.finditer(reg_section): + d = {k: _clean_cell(v) for k, v in match.groupdict().items()} + d["cwe"] = "" + rows.append(d) + return rows + + +def extract_generic_report(report_markdown: str, *, skill_id: str) -> GenericExtraction: + """Parse any OUTPUT_CONTRACT-shaped report into structured findings + rating.""" + if not (report_markdown or "").strip(): + return GenericExtraction(findings=[], overall_rating=None, contract_valid=False) + try: + parsed = parse_report(report_markdown) + overall_rating = extract_overall_risk_rating(parsed) + except MalformedReportError: + return GenericExtraction(findings=[], overall_rating=None, contract_valid=False) + + excluded_ids = example_finding_ids(parsed) + register_rows = [r for r in _extract_register_rows(parsed) if r["id"] not in excluded_ids] + blocks = detail_blocks(parsed) + + blocks_by_id: dict[str, tuple[str, str, str]] = {} + blocks_by_order: list[tuple[str, str, str, str]] = [] + for heading_text, body in blocks: + m = _DETAIL_HEADING_RE.match(heading_text) + if not m: + continue + fid = (m.group("id") or "").strip() + sev = normalize_generic_severity(m.group("severity")) + title = (m.group("title") or "").strip() + body_clean = body.strip() + if fid and fid in excluded_ids: + continue + if fid and fid not in blocks_by_id: + blocks_by_id[fid] = (sev, title, body_clean) + blocks_by_order.append((fid, sev, title, body_clean)) + + raw_items: list[dict[str, str]] = [] + if register_rows: + for row in register_rows: + fid = row["id"] + b_sev, b_title, b_body = blocks_by_id.get(fid, ("", "", "")) + severity = normalize_generic_severity(row.get("severity") or b_sev) + title = row.get("title") or b_title or fid + cwe = _normalize_cwe(row.get("cwe")) + if not cwe and b_body: + cm = _CWE_FIELD_RE.search(b_body) + if cm: + cwe = _normalize_cwe(cm.group(1)) + verdict = _normalize_verdict(row.get("verdict")) + if not verdict and b_body: + vm = _VERDICT_FIELD_RE.search(b_body) + if vm: + verdict = _normalize_verdict(vm.group(1)) + body_text = b_body or f"**Severity:** {severity}\n**Verdict:** {verdict or 'Reported'}" + raw_items.append( + { + "id": fid, + "title": title, + "severity": severity, + "cwe": cwe, + "verdict": verdict, + "body": body_text, + } + ) + elif blocks_by_order: + for idx, (fid, sev, title, body_clean) in enumerate(blocks_by_order, start=1): + ref = fid or f"F{idx}" + cm = _CWE_FIELD_RE.search(body_clean) + vm = _VERDICT_FIELD_RE.search(body_clean) + raw_items.append( + { + "id": ref, + "title": title or ref, + "severity": sev, + "cwe": _normalize_cwe(cm.group(1)) if cm else "", + "verdict": _normalize_verdict(vm.group(1)) if vm else "", + "body": body_clean, + } + ) + + seen_counts: dict[tuple[str, str], int] = {} + findings: list[dict[str, str]] = [] + for item in raw_items: + dedupe_key = (item["cwe"], item["title"].strip().lower()) + occ = seen_counts.get(dedupe_key, 0) + seen_counts[dedupe_key] = occ + 1 + fp = fingerprint_for_generic_finding( + skill_id, + title=item["title"], + cwe=item["cwe"], + ref=item["id"], + occurrence=occ, + ) + findings.append({**item, "fingerprint": fp}) + + has_findings_section = bool(_extract_section(parsed, "Findings").strip() or _extract_section(parsed, "Findings Register").strip()) + explicit_empty = bool(_NO_FINDINGS_RE.search(prose_source(parsed))) + contract_valid = bool(findings) or (overall_rating is not None and (has_findings_section or explicit_empty)) + return GenericExtraction(findings=findings, overall_rating=overall_rating, contract_valid=contract_valid) diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index fb32750..5eb6f03 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -30,6 +30,7 @@ from secfoo.report import sca as sca_report from secfoo.report import secret_scanning as secret_report from secfoo.report.context_coverage import CoverageRecord, coverage_for_run +from secfoo.report.generic import extract_generic_report from secfoo.report.markdown import ( MalformedReportError, detail_blocks, @@ -48,7 +49,7 @@ from secfoo.skills.loader import load_skill from secfoo.skills.renderer import TargetContext, render_prompt from secfoo.stack import Stack, detect_stack, language_for_ecosystem, language_for_path -from secfoo.storage.repository import RunRepository +from secfoo.storage.repository import SPECIALIZED_FINDINGS_OUTPUTS, RunRepository from secfoo.targets.diff import ( classify_finding_scope, extract_scope_by_id, @@ -400,6 +401,44 @@ def _mark_run_crashed(repo: RunRepository, run_uuid: str, *, duration_seconds: f STRUCTURED_FINDINGS_SKILLS = frozenset({SAST_SKILL_ID, SCA_SKILL_ID, SECRET_SKILL_ID}) +def update_generic_findings( + repo: RunRepository, + *, + skill_id: str, + project_id: int, + run_id: int, + report_text: str, + close_stale: bool = True, +) -> None: + """Persist structured findings for a generic OUTPUT_CONTRACT skill (#92).""" + extraction = extract_generic_report(report_text, skill_id=skill_id) + if not extraction.contract_valid and not extraction.findings: + return + seen_fingerprints: list[str] = [] + for item in extraction.findings: + fp = item["fingerprint"] + seen_fingerprints.append(fp) + repo.upsert_generic_finding( + project_id=project_id, + skill_id=skill_id, + fingerprint=fp, + run_id=run_id, + finding_ref=item["id"], + title=item["title"], + severity=item["severity"], + cwe=item["cwe"], + verdict=item["verdict"], + body=item["body"], + ) + if close_stale: + repo.close_stale_generic_findings( + skill_id=skill_id, + project_id=project_id, + run_id=run_id, + seen_fingerprints=seen_fingerprints, + ) + + def update_structured_findings( repo: RunRepository, *, @@ -437,6 +476,11 @@ def update_structured_findings( repo, project_id=project_id, run_id=run_id, report_text=report_text, workdir=workdir, stack=stack, scan_scope=scan_scope, close_stale=close_stale, ) + elif skill_id not in SPECIALIZED_FINDINGS_OUTPUTS: + update_generic_findings( + repo, skill_id=skill_id, project_id=project_id, run_id=run_id, + report_text=report_text, close_stale=close_stale, + ) @contextmanager @@ -733,6 +777,24 @@ def _run_single_skill( ) except Exception: logger.exception("Failed to update %s finding lifecycle for run %s", skill.id, run_uuid) + if skill.id not in SPECIALIZED_FINDINGS_OUTPUTS: + try: + completed_run = repo.get_run(run_uuid) + update_generic_findings( + repo, + skill_id=skill.id, + project_id=project_id, + run_id=completed_run.id, + report_text=report_text, + # A scoped run (--changed-since/--changed-files, or an + # adapter that only sent changed files) did not look at + # the rest of the repo, so it must not close findings + # it never re-checked. Generic findings carry no file + # location to classify against the scope. + close_stale=effective_scan_scope is None, + ) + except Exception: + logger.exception("Failed to update generic finding lifecycle for run %s", run_uuid) run_findings = _extract_run_findings( output_type=output_type, skill_id=skill.id, diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 0a29e96..46c4935 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -255,6 +255,28 @@ class SecretFindingRecord: project_display_name: str | None = None +@dataclass(frozen=True) +class GenericFindingRecord: + id: int + project_id: int + skill_id: str + fingerprint: str + finding_ref: str + title: str + severity: str + cwe: str + verdict: str + body: str + status: str + first_seen_run_id: int + first_seen_at: str + last_seen_run_id: int + last_seen_at: str + closed_in_run_id: int | None + closed_at: str | None + project_display_name: str | None = None + + @dataclass(frozen=True) class CostRow: label: str diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index a441896..6422f1e 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -45,6 +45,7 @@ def use_db_path(path: Path): yield finally: _default_db_path.reset(token) +from secfoo.report.generic import extract_generic_report from secfoo.report.sast import locations_json, parse_locations from secfoo.report.severity import SeverityCounts, extract_overall_risk_rating from secfoo.storage.models import ( @@ -53,6 +54,7 @@ def use_db_path(path: Path): ContextSourceRecord, CostRow, ExceptionRecord, + GenericFindingRecord, OsvLookupRecord, PostBuildFindingRecord, ProjectRecord, @@ -135,6 +137,21 @@ def use_db_path(path: Path): # shares the open/closed + first/last-seen columns, which is what lets # close_stale_findings and list_structured_findings serve all three. _FINDINGS_TABLES = {"sast": "sast_findings", "sca-reachability": "sca_findings", "secret-scanning": "secret_findings"} +# Built-in skills whose outputs are managed by dedicated dashboards/tables +# rather than `generic_findings`. Any other skill (including `prompt-review`, +# `deployment-readiness`, and user-defined custom skills) uses `generic_findings` +# unless its definition sets `output:` to one of these specialized pipelines. +SPECIALIZED_FINDINGS_OUTPUTS = frozenset( + { + "sast", + "sca-reachability", + "secret-scanning", + "security-architecture-review", + "threat-modeling", + "responsible-ai-compliance", + "third-party-risk-assessment", + } +) # Findings tables with a location_file column, i.e. ones an incremental # scan's file scope can be applied to (see close_stale_findings). _FILE_SCOPED_TABLES = frozenset({"sast_findings", "secret_findings"}) @@ -242,6 +259,7 @@ def _migrate(self) -> None: self._conn.commit() self._backfill_locations() self._backfill_responsible_ai_ratings() + self._backfill_generic_findings() self._migrate_attachment_kind_check() self._migrate_runs_status_check() @@ -295,6 +313,65 @@ def _backfill_locations(self) -> None: ) self._conn.commit() + def _backfill_generic_findings(self) -> None: + """One-time migration (#92): replays existing successful generic runs in + chronological order so upgrading an existing DB populates + `generic_findings` with accurate open/closed state.""" + already = self._conn.execute( + "SELECT 1 FROM schema_migrations WHERE key = 'generic_findings_backfill_v1'" + ).fetchone() + if already is not None: + return + rows = self._conn.execute( + "SELECT id, project_id, skill_id, report_path, finished_at, started_at FROM runs " + "WHERE status = 'success' AND report_path IS NOT NULL " + "ORDER BY started_at ASC, id ASC" + ).fetchall() + for row in rows: + skill_id = row["skill_id"] + if skill_id in SPECIALIZED_FINDINGS_OUTPUTS: + continue + try: + text = read_stored_report(row["report_path"]) + except (OSError, ValueError) as exc: + logging.getLogger(__name__).debug("Skipping unreadable report %s: %s", row["report_path"], exc) + continue + if not text: + continue + extraction = extract_generic_report(text, skill_id=skill_id) + if not extraction.contract_valid and not extraction.findings: + continue + seen_at = row["finished_at"] or row["started_at"] or _now() + seen_fps: list[str] = [] + for item in extraction.findings: + fp = item["fingerprint"] + seen_fps.append(fp) + self.upsert_generic_finding( + project_id=row["project_id"], + skill_id=skill_id, + fingerprint=fp, + run_id=row["id"], + finding_ref=item["id"], + title=item["title"], + severity=item["severity"], + cwe=item["cwe"], + verdict=item["verdict"], + body=item["body"], + seen_at=seen_at, + ) + self.close_stale_generic_findings( + skill_id=skill_id, + project_id=row["project_id"], + run_id=row["id"], + seen_fingerprints=seen_fps, + closed_at=seen_at, + ) + self._conn.execute( + "INSERT OR IGNORE INTO schema_migrations (key, applied_at) VALUES (?, ?)", + ("generic_findings_backfill_v1", _now()), + ) + self._conn.commit() + def _add_column(self, ddl: str) -> None: # Skills run in parallel threads, each opening its own connection, so # two connections can both see a column missing on an old database @@ -2188,3 +2265,114 @@ def list_findings_for_baseline( } ) return items + + # ---------- Generic findings (#92: custom & contract-based skills) ---------- + + def upsert_generic_finding( + self, + *, + project_id: int, + skill_id: str, + fingerprint: str, + run_id: int, + finding_ref: str, + title: str, + severity: str, + cwe: str = "", + verdict: str = "", + body: str = "", + seen_at: str | None = None, + ) -> None: + now = seen_at or _now() + self._conn.execute( + "INSERT INTO generic_findings " + "(project_id, skill_id, fingerprint, finding_ref, title, severity, cwe, verdict, body, " + "status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) " + "ON CONFLICT(project_id, skill_id, fingerprint) DO UPDATE SET " + "finding_ref = excluded.finding_ref, title = excluded.title, severity = excluded.severity, " + "cwe = excluded.cwe, verdict = excluded.verdict, body = excluded.body, status = 'open', " + "last_seen_run_id = excluded.last_seen_run_id, last_seen_at = excluded.last_seen_at, " + "closed_in_run_id = NULL, closed_at = NULL", + ( + project_id, + skill_id, + fingerprint, + finding_ref, + title, + severity, + cwe, + verdict, + body, + run_id, + now, + run_id, + now, + ), + ) + self._conn.commit() + + def close_stale_generic_findings( + self, + *, + skill_id: str, + project_id: int, + run_id: int, + seen_fingerprints: list[str], + closed_at: str | None = None, + ) -> None: + now = closed_at or _now() + query = ( + "UPDATE generic_findings SET status = 'closed', closed_in_run_id = ?, closed_at = ? " + "WHERE project_id = ? AND skill_id = ? AND status = 'open'" + ) + params: list[object] = [run_id, now, project_id, skill_id] + if seen_fingerprints: + query += f" AND fingerprint NOT IN ({','.join('?' * len(seen_fingerprints))})" # nosec B608 -- placeholders are ? binds + params.extend(seen_fingerprints) + self._conn.execute(query, params) + self._conn.commit() + + def list_generic_findings( + self, + *, + skill_id: str | None = None, + project_id: int | None = None, + status: str | None = None, + limit: int = 1000, + ) -> list[GenericFindingRecord]: + query = ( + "SELECT generic_findings.*, projects.display_name FROM generic_findings " + "JOIN projects ON projects.id = generic_findings.project_id WHERE 1=1" + ) + params: list[object] = [] + if skill_id is not None: + query += " AND generic_findings.skill_id = ?" + params.append(skill_id) + if project_id is not None: + query += " AND generic_findings.project_id = ?" + params.append(project_id) + if status is not None: + query += " AND generic_findings.status = ?" + params.append(status) + query += " ORDER BY generic_findings.last_seen_at DESC, generic_findings.id DESC LIMIT ?" + params.append(limit) + rows = self._conn.execute(query, params).fetchall() + return [self._row_to_finding(GenericFindingRecord, row) for row in rows] + + def get_generic_finding( + self, skill_id: str, finding_key: str, *, project_id: int | None = None + ) -> GenericFindingRecord | None: + base = ( + "SELECT generic_findings.*, projects.display_name FROM generic_findings " + "JOIN projects ON projects.id = generic_findings.project_id " + "WHERE generic_findings.skill_id = ?" + ) + params: list[object] = [skill_id] + if project_id is not None: + base += " AND generic_findings.project_id = ?" + params.append(project_id) + row = self._conn.execute(base + " AND generic_findings.fingerprint = ? LIMIT 1", [*params, finding_key]).fetchone() + if row is None and finding_key.isdigit(): + row = self._conn.execute(base + " AND generic_findings.id = ? LIMIT 1", [*params, int(finding_key)]).fetchone() + return self._row_to_finding(GenericFindingRecord, row) if row is not None else None diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 3b2c702..7c018c0 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -503,3 +503,35 @@ CREATE TABLE IF NOT EXISTS runtime_findings ( last_seen_at TEXT NOT NULL, UNIQUE (project_id, kind, ecosystem, package, version, advisory) ); + +-- #92: tracks one-time data migrations (such as the initial backfill of +-- generic_findings from pre-existing runs) so they run once and stay idempotent. +CREATE TABLE IF NOT EXISTS schema_migrations ( + key TEXT PRIMARY KEY, + applied_at TEXT NOT NULL +); + +-- #92: persistent open/closed lifecycle for findings produced by generic / +-- custom skills following OUTPUT_CONTRACT (anything without its own dedicated +-- findings table). Keyed by (project_id, skill_id, fingerprint) so different +-- skills on the same project stay isolated across runs. +CREATE TABLE IF NOT EXISTS generic_findings ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + project_id INTEGER NOT NULL REFERENCES projects(id), + skill_id TEXT NOT NULL, + fingerprint TEXT NOT NULL, + finding_ref TEXT NOT NULL, + title TEXT NOT NULL, + severity TEXT NOT NULL, + cwe TEXT NOT NULL DEFAULT '', + verdict TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open','closed')), + first_seen_run_id INTEGER NOT NULL REFERENCES runs(id), + first_seen_at TEXT NOT NULL, + last_seen_run_id INTEGER NOT NULL REFERENCES runs(id), + last_seen_at TEXT NOT NULL, + closed_in_run_id INTEGER REFERENCES runs(id), + closed_at TEXT, + UNIQUE (project_id, skill_id, fingerprint) +); diff --git a/src/secfoo/storage/schema_indexes.sql b/src/secfoo/storage/schema_indexes.sql index 5cd9d73..72a5ba2 100644 --- a/src/secfoo/storage/schema_indexes.sql +++ b/src/secfoo/storage/schema_indexes.sql @@ -16,3 +16,5 @@ CREATE INDEX IF NOT EXISTS idx_rai_dimensions_project ON rai_dimensions(project_ CREATE INDEX IF NOT EXISTS idx_rai_dimensions_run ON rai_dimensions(run_id); CREATE INDEX IF NOT EXISTS idx_rai_findings_project ON rai_findings(project_id, run_id); CREATE INDEX IF NOT EXISTS idx_rai_findings_dimension ON rai_findings(dimension); +CREATE INDEX IF NOT EXISTS idx_generic_findings_skill_status ON generic_findings(skill_id, status); +CREATE INDEX IF NOT EXISTS idx_generic_findings_project_skill ON generic_findings(project_id, skill_id, status); diff --git a/src/secfoo/web/generic_dashboard.py b/src/secfoo/web/generic_dashboard.py new file mode 100644 index 0000000..c0529ab --- /dev/null +++ b/src/secfoo/web/generic_dashboard.py @@ -0,0 +1,200 @@ +"""Computes the dynamic activity dashboard for any skill following OUTPUT_CONTRACT (#92). + +Powers built-in skills without a specialized pipeline (such as `prompt-review` +and `deployment-readiness`) as well as any custom user skill whose `output` +remains `"generic"`. Reads persisted lifecycle rows from `generic_findings`, +evaluates latest reports for overall risk ratings and contract compliance, and +builds a 20-run trend series. +""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass + +from secfoo.report.generic import ( + CANONICAL_SEVERITIES, + extract_generic_report, + normalize_generic_severity, +) +from secfoo.storage.models import GenericFindingRecord +from secfoo.storage.repository import RunRepository +from secfoo.web.dashboard_common import read_report + +GENERIC_TREND_LIMIT = 20 + +_KNOWN_STYLE: dict[str, tuple[str, str, str]] = { + "critical": ("var(--color-error)", "u-bg-error", "badge--error"), + "high": ("var(--color-error)", "u-bg-error", "badge--error"), + "medium": ("var(--color-warning)", "u-bg-warning", "badge--warning"), + "low": ("var(--color-teal-500)", "u-bg-teal-500", "badge--neutral"), + "info": ("var(--color-gray-400)", "u-bg-gray-400", "badge--neutral"), +} + +_CUSTOM_STYLE_CYCLE: tuple[tuple[str, str, str], ...] = ( + ("var(--color-warning)", "u-bg-warning", "badge--warning"), + ("var(--color-teal-500)", "u-bg-teal-500", "badge--neutral"), + ("var(--color-gray-400)", "u-bg-gray-400", "badge--neutral"), +) + +_RATING_ORDER = ("critical", "high", "medium", "low", "info") + + +@dataclass(frozen=True) +class SeverityBucket: + key: str + label: str + count: int + color: str + dot_class: str + badge_class: str + + +@dataclass(frozen=True) +class GenericDashboard: + skill_id: str + open_findings: list[GenericFindingRecord] + closed_findings: list[GenericFindingRecord] + severity_counts: dict[str, int] + severity_color_map: dict[str, str] + severity_buckets: list[SeverityBucket] + severity_filter_options: list[tuple[str, str]] + verdict_filter_options: list[str] + rating_distribution: list[dict[str, object]] + rated_projects: int + run_trend: list[dict[str, object]] + contract_warnings: list[dict[str, str]] + + @property + def open_count(self) -> int: + return len(self.open_findings) + + @property + def closed_count(self) -> int: + return len(self.closed_findings) + + +def style_for_severity(severity: str, *, custom_index: int = 0) -> tuple[str, str, str]: + norm = normalize_generic_severity(severity) + if norm in _KNOWN_STYLE: + return _KNOWN_STYLE[norm] + return _CUSTOM_STYLE_CYCLE[custom_index % len(_CUSTOM_STYLE_CYCLE)] + + +def build(repo: RunRepository, skill_id: str) -> GenericDashboard: + """Builds the dynamic dashboard state for `skill_id`.""" + all_findings = repo.list_generic_findings(skill_id=skill_id, limit=5000) + open_findings = [f for f in all_findings if f.status == "open"] + closed_findings = [f for f in all_findings if f.status == "closed"] + + open_sev_counter: Counter[str] = Counter(normalize_generic_severity(f.severity) for f in open_findings) + all_sev_keys = {normalize_generic_severity(f.severity) for f in all_findings} + + # Include canonical severities plus any custom/non-standard severity words + # observed in findings so custom scales get their own distinct buckets. + extra_keys = sorted(k for k in all_sev_keys if k not in CANONICAL_SEVERITIES) + ordered_keys = [*CANONICAL_SEVERITIES, *extra_keys] + + severity_counts: dict[str, int] = {} + severity_color_map: dict[str, str] = {} + severity_buckets: list[SeverityBucket] = [] + severity_filter_options: list[tuple[str, str]] = [] + custom_idx = 0 + for key in ordered_keys: + count = open_sev_counter.get(key, 0) + if key not in CANONICAL_SEVERITIES and key not in all_sev_keys: + continue + if key in _KNOWN_STYLE: + color, dot_cls, badge_cls = _KNOWN_STYLE[key] + else: + color, dot_cls, badge_cls = _CUSTOM_STYLE_CYCLE[custom_idx % len(_CUSTOM_STYLE_CYCLE)] + custom_idx += 1 + label = "Informational" if key == "info" else key.capitalize() + severity_counts[key] = count + severity_color_map[key] = color + if count > 0 or key in CANONICAL_SEVERITIES: + severity_buckets.append( + SeverityBucket( + key=key, + label=label, + count=count, + color=color, + dot_class=dot_cls, + badge_class=badge_cls, + ) + ) + severity_filter_options.append((key, label)) + + verdict_filter_options = sorted({f.verdict for f in all_findings if f.verdict}) + + projects = repo.activity_summary_by_project(skill_id) + rating_counter: Counter[str] = Counter() + contract_warnings: list[dict[str, str]] = [] + for project in projects: + text = read_report(project.get("latest_success_report_path")) + if not text: + continue + extraction = extract_generic_report(text, skill_id=skill_id) + if not extraction.contract_valid: + contract_warnings.append( + { + "project": project.get("project_display_name") or "-", + "run_uuid": project.get("latest_success_run_uuid") or "", + } + ) + if extraction.overall_rating: + rating_counter[normalize_generic_severity(extraction.overall_rating)] += 1 + + rated_projects = sum(rating_counter.values()) + extra_ratings = sorted(r for r in rating_counter if r not in _RATING_ORDER) + rating_distribution: list[dict[str, object]] = [] + for rating in [*_RATING_ORDER, *extra_ratings]: + count = rating_counter.get(rating, 0) + if count == 0: + continue + _, _, badge_cls = style_for_severity(rating) + rating_distribution.append( + { + "rating": rating, + "label": "Informational" if rating == "info" else rating.capitalize(), + "count": count, + "pct": round(count / rated_projects * 100) if rated_projects else 0, + "badge_class": badge_cls, + } + ) + + recent_runs = repo.list_runs(skill_id=skill_id, limit=GENERIC_TREND_LIMIT) + trend_points: list[dict[str, object]] = [] + for run in reversed(recent_runs): + total = run.critical_count + run.high_count + run.medium_count + run.low_count + run.info_count + if total == 0 and run.status == "success" and run.report_path: + text = read_report(run.report_path) + if text: + total = len(extract_generic_report(text, skill_id=skill_id).findings) + trend_points.append( + { + "run_uuid": run.run_uuid, + "started_at": run.started_at, + "status": run.status, + "total": total, + } + ) + max_total = max((int(p["total"]) for p in trend_points), default=0) + for point in trend_points: + total = int(point["total"]) + point["bar_pct"] = round(total / max_total * 100) if max_total else 0 + + return GenericDashboard( + skill_id=skill_id, + open_findings=open_findings, + closed_findings=closed_findings, + severity_counts=severity_counts, + severity_color_map=severity_color_map, + severity_buckets=severity_buckets, + severity_filter_options=severity_filter_options, + verdict_filter_options=verdict_filter_options, + rating_distribution=rating_distribution, + rated_projects=rated_projects, + run_trend=trend_points, + contract_warnings=contract_warnings, + ) diff --git a/src/secfoo/web/routes/activities.py b/src/secfoo/web/routes/activities.py index da0737b..a658bd1 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -27,11 +27,14 @@ extract_mermaid_diagram, split_design_verdict, ) +from secfoo.report.generic import normalize_generic_severity +from secfoo.report.markdown import render_report_html from secfoo.skills.loader import SkillLoadError, load_skill from secfoo.storage.repository import RunRepository from secfoo.web import architecture_dashboard as arch_dashboard from secfoo.web import ( finding_filters, + generic_dashboard, sast_dashboard, sca_dashboard, secret_scanning_dashboard, @@ -124,34 +127,96 @@ def _donut_gradient(counts: dict[str, int], color_map: dict[str, str]) -> str: return ", ".join(segments) +# Keyed by built-in skill_id (#92): custom skills declaring `output: sast` +# (etc.) route to the generic dashboard instead so they never display the +# built-in SAST/SCA/secret skill's data. +_SPECIALIZED_DASHBOARDS: dict[str, tuple[str, object]] = { + arch_dashboard.SKILL_ID: ("dash", arch_dashboard.build), + tm_dashboard.SKILL_ID: ("tm_dash", tm_dashboard.build), + sca_dashboard.SKILL_ID: ("sca_dash", sca_dashboard.build), + sast_dashboard.SKILL_ID: ("sast_dash", sast_dashboard.build), + secret_scanning_dashboard.SKILL_ID: ("secret_dash", secret_scanning_dashboard.build), +} +_NON_GENERIC_OUTPUTS = frozenset( + {*_SPECIALIZED_DASHBOARDS, rai_dashboard.SKILL_ID, "third-party-risk-assessment"} +) + + +def _filter_generic_findings( + findings: list, + *, + project_id: int | None, + severity: str, + verdict: str, + search: str, +) -> list: + needle = search.lower() + result = [] + for f in findings: + if project_id is not None and f.project_id != project_id: + continue + if severity and normalize_generic_severity(f.severity) != severity: + continue + if verdict and f.verdict.lower() != verdict.lower(): + continue + if needle and not any( + needle in field.lower() + for field in (f.title, f.cwe, f.verdict, f.finding_ref, f.project_display_name or "") + ): + continue + result.append(f) + return result + + @router.get("/activities/{skill_id}") def activity_detail( request: Request, skill_id: str, diagram_project: int | None = None, stride_project: int | None = None, + status: str = "open", + severity: str | None = None, + verdict: str | None = None, + project_id: str | None = None, + q: str | None = None, ): try: skill = load_skill(skill_id) except SkillLoadError as exc: raise HTTPException(status_code=404, detail=str(exc)) from exc + built: dict[str, object] = { + "dash": None, + "tm_dash": None, + "sca_dash": None, + "sast_dash": None, + "secret_dash": None, + "rai_dash": None, + "generic_dash": None, + } with RunRepository() as repo: projects = repo.activity_summary_by_project(skill_id) - severity = repo.activity_severity_totals(skill_id) - dash = arch_dashboard.build(repo) if skill_id == arch_dashboard.SKILL_ID else None - tm_dash = tm_dashboard.build(repo) if skill_id == tm_dashboard.SKILL_ID else None - sca_dash = sca_dashboard.build(repo) if skill_id == sca_dashboard.SKILL_ID else None - sast_dash = sast_dashboard.build(repo) if skill_id == sast_dashboard.SKILL_ID else None - secret_dash = ( - secret_scanning_dashboard.build(repo) if skill_id == secret_scanning_dashboard.SKILL_ID else None - ) - rai_dash = rai_dashboard.build(repo) if skill_id == rai_dashboard.SKILL_ID else None - # A report written before the #131 contract has no structured - # dimensions. Keep the generic cards in that case rather than showing - # an empty program dashboard in place of useful run statistics. - if rai_dash is not None and not rai_dash.systems: - rai_dash = None + severity_totals = repo.activity_severity_totals(skill_id) + spec = _SPECIALIZED_DASHBOARDS.get(skill_id) + if spec is not None: + ctx_key, builder = spec + built[ctx_key] = builder(repo) + elif skill_id == rai_dashboard.SKILL_ID: + rai_dash = rai_dashboard.build(repo) + # A report written before the #131 contract has no structured + # dimensions. Keep the generic cards in that case rather than showing + # an empty program dashboard in place of useful run statistics. + built["rai_dash"] = rai_dash if rai_dash.systems else None + elif skill_id not in _NON_GENERIC_OUTPUTS: + built["generic_dash"] = generic_dashboard.build(repo, skill_id) + + dash = built["dash"] + tm_dash = built["tm_dash"] + sca_dash = built["sca_dash"] + sast_dash = built["sast_dash"] + secret_dash = built["secret_dash"] + rai_dash = built["rai_dash"] + generic_dash = built["generic_dash"] diagrams_available = _attach_architecture_signals(projects) verdict_count = sum(1 for p in projects if p.get("design_verdict")) @@ -178,9 +243,13 @@ def activity_detail( context = { "skill": skill, "projects": projects, - "severity": severity, + "severity": severity_totals, "severity_rows": severity_rows( - severity.critical, severity.high, severity.medium, severity.low, severity.info + severity_totals.critical, + severity_totals.high, + severity_totals.medium, + severity_totals.low, + severity_totals.info, ), "run_count": sum(p["run_count"] for p in projects), "diagrams_available": diagrams_available, @@ -202,6 +271,7 @@ def activity_detail( "sast_dash": sast_dash, "secret_dash": secret_dash, "rai_dash": rai_dash, + "generic_dash": generic_dash, } if dash is not None: context["gate_mix_gradient"] = _donut_gradient(dash.gate_mix, _GATE_MIX_COLORS) @@ -220,6 +290,50 @@ def activity_detail( context["sast_cvss_gradient"] = _donut_gradient(sast_dash.cvss_band_counts, _SAST_CVSS_COLORS) if secret_dash is not None: context["secret_severity_gradient"] = _donut_gradient(secret_dash.severity_counts, _SCA_SEVERITY_COLORS) + if generic_dash is not None: + selected_status = "closed" if status == "closed" else "open" + selected_project_id = finding_filters.parse_project_id(project_id) + selected_severity = normalize_generic_severity(severity) if severity else "" + selected_verdict = (verdict or "").strip() + search = (q or "").strip() + filtered_open = _filter_generic_findings( + generic_dash.open_findings, + project_id=selected_project_id, + severity=selected_severity, + verdict=selected_verdict, + search=search, + ) + filtered_closed = _filter_generic_findings( + generic_dash.closed_findings, + project_id=selected_project_id, + severity=selected_severity, + verdict=selected_verdict, + search=search, + ) + generic_filters = { + "project_id": selected_project_id, + "severity": selected_severity, + "verdict": selected_verdict, + "q": search, + } + context.update( + { + "generic_severity_gradient": _donut_gradient( + generic_dash.severity_counts, generic_dash.severity_color_map + ), + "generic_selected_status": selected_status, + "generic_selected_project_id": selected_project_id, + "generic_selected_severity": selected_severity, + "generic_selected_verdict": selected_verdict, + "generic_search": search, + "generic_open_count": len(filtered_open), + "generic_closed_count": len(filtered_closed), + "generic_findings": filtered_closed if selected_status == "closed" else filtered_open, + "generic_open_query": finding_filters.query_string(status="open", **generic_filters), + "generic_closed_query": finding_filters.query_string(status="closed", **generic_filters), + "generic_filters_active": any(v not in (None, "") for v in generic_filters.values()), + } + ) return templates.TemplateResponse(request, "activities/detail.html", context) @@ -509,3 +623,29 @@ def secret_scanning_finding_detail(request: Request, key: str): return templates.TemplateResponse( request, "activities/secret_scanning_finding_detail.html", {"finding": finding} ) + + +@router.get("/activities/{skill_id}/findings/{finding_id}") +def generic_finding_detail(request: Request, skill_id: str, finding_id: str): + """Detail view for a single finding stored in `generic_findings` (#92).""" + try: + skill = load_skill(skill_id) + except SkillLoadError as exc: + raise HTTPException(status_code=404, detail=str(exc)) from exc + + with RunRepository() as repo: + finding = repo.get_generic_finding(skill_id, finding_id) + if finding is None: + raise HTTPException(status_code=404, detail="Finding not found") + + _, _, badge_class = generic_dashboard.style_for_severity(finding.severity) + return templates.TemplateResponse( + request, + "activities/generic_finding_detail.html", + { + "skill": skill, + "finding": finding, + "severity_badge_class": badge_class, + "body_html": render_report_html(finding.body), + }, + ) diff --git a/src/secfoo/web/templates/activities/detail.html b/src/secfoo/web/templates/activities/detail.html index fd7a5e2..94039cb 100644 --- a/src/secfoo/web/templates/activities/detail.html +++ b/src/secfoo/web/templates/activities/detail.html @@ -128,7 +128,7 @@ <h4 class="card__title u-m-0">Design verdicts</h4> </div> {% endif %} -{% if not dash and not sca_dash and not sast_dash and not secret_dash and not rai_dash %} +{% if not dash and not sca_dash and not sast_dash and not secret_dash and not rai_dash and not generic_dash %} {# The program dashboards above already have their own severity/disposition breakdowns -- a raw severity-count bar here would just be a second, less specific cut of the same findings. #} @@ -149,6 +149,10 @@ <h4 class="card__title">Findings by severity</h4> </div> {% endif %} +{% if generic_dash %} +{% include "activities/generic_dashboard.html" %} +{% endif %} + {% if diagrams_available and skill.id != "threat-modeling" %} <h2 class="u-mt-12">Architecture diagram</h2> <p class="ds-body u-color-text-muted u-max-w-44rem"> diff --git a/src/secfoo/web/templates/activities/generic_dashboard.html b/src/secfoo/web/templates/activities/generic_dashboard.html new file mode 100644 index 0000000..cec058e --- /dev/null +++ b/src/secfoo/web/templates/activities/generic_dashboard.html @@ -0,0 +1,146 @@ +{# Dynamic dashboard for any skill following the generic OUTPUT_CONTRACT (#92). #} +{% from "_macros.html" import info_tip %} + +{% if generic_dash.contract_warnings %} +<div class="alert alert--warning u-mt-6" role="status"> + <div> + <strong>Report did not follow the output contract</strong> for + {% for w in generic_dash.contract_warnings %}{{ w.project }}{% if w.run_uuid %} (<a href="/runs/{{ w.run_uuid }}">inspect run</a>){% endif %}{% if not loop.last %}, {% endif %}{% endfor %}. + </div> +</div> +{% endif %} + +<div class="stat-card-grid u-mt-6"> + <div class="stat-card"> + <span class="stat-card__value">{{ generic_dash.open_count }}</span> + <span class="stat-card__label">Open findings</span> + </div> + <div class="stat-card"> + <span class="stat-card__value">{{ generic_dash.closed_count }}</span> + <span class="stat-card__label">Closed findings</span> + </div> + <div class="stat-card"> + <span class="stat-card__value">{{ generic_dash.rated_projects }}</span> + <span class="stat-card__label">Projects with overall rating</span> + </div> +</div> + +<div class="u-d-grid u-cols-3fr-2fr u-gap-6 u-mt-6"> + <div class="card has-info"> + {% call info_tip("Findings by severity") %} + <p>Severity breakdown across currently open findings for this skill.</p> + <p>Custom severity labels defined by the skill appear as their own buckets.</p> + {% endcall %} + <h4 class="card__title">Findings by severity</h4> + <div class="donut-row u-mt-4"> + <div class="donut" data-donut-gradient="{{ generic_severity_gradient }}"> + <div class="donut__hole">{{ generic_dash.open_count }}</div> + </div> + <div class="donut-legend"> + {% for bucket in generic_dash.severity_buckets %} + <span class="donut-legend__item"><span class="donut-legend__dot {{ bucket.dot_class }}"></span>{{ bucket.label }} ({{ bucket.count }})</span> + {% endfor %} + </div> + </div> + </div> + + <div class="card"> + <h4 class="card__title">Overall risk rating distribution</h4> + {% if generic_dash.rating_distribution %} + <div class="u-mt-4"> + {% for row in generic_dash.rating_distribution %} + <div class="conformance-bar"> + <span class="conformance-bar__label"><span class="badge {{ row.badge_class }}">{{ row.label }}</span></span> + <div class="conformance-bar__track"> + <div class="conformance-bar__fill conformance-bar__fill--partial" data-bar-width="{{ row.pct }}"></div> + </div> + <span class="conformance-bar__value">{{ row.count }} ({{ row.pct }}%)</span> + </div> + {% endfor %} + </div> + {% else %} + <p class="ds-body-sm u-color-text-muted u-mt-4">No overall risk ratings parsed from completed runs yet.</p> + {% endif %} + </div> +</div> + +{% if generic_dash.run_trend %} +<div class="card u-mt-6"> + <h4 class="card__title">Findings trend (newest {{ generic_dash.run_trend | length }} run{% if generic_dash.run_trend | length != 1 %}s{% endif %})</h4> + <div class="u-mt-4"> + {% for pt in generic_dash.run_trend %} + <div class="conformance-bar"> + <span class="conformance-bar__label"><a href="/runs/{{ pt.run_uuid }}">{{ pt.started_at | fmt_time }}</a></span> + <div class="conformance-bar__track"> + <div class="conformance-bar__fill {% if pt.total > 0 %}conformance-bar__fill--non-conformant{% else %}conformance-bar__fill--conformant{% endif %}" data-bar-width="{{ pt.bar_pct }}"></div> + </div> + <span class="conformance-bar__value">{{ pt.total }} finding{% if pt.total != 1 %}s{% endif %} ({{ pt.status }})</span> + </div> + {% endfor %} + </div> +</div> +{% endif %} + +<div class="u-mt-8" id="findings"> + <h2>Findings register</h2> + <div class="segmented u-mt-4"> + <a class="segmented__option" {% if generic_selected_status == 'open' %}aria-selected="true"{% endif %} href="/activities/{{ skill.id }}?{{ generic_open_query }}">Open ({{ generic_open_count }})</a> + <a class="segmented__option" {% if generic_selected_status == 'closed' %}aria-selected="true"{% endif %} href="/activities/{{ skill.id }}?{{ generic_closed_query }}">Closed ({{ generic_closed_count }})</a> + </div> + + <form method="get" action="/activities/{{ skill.id }}" class="filter-bar u-mt-4"> + <input type="hidden" name="status" value="{{ generic_selected_status }}"> + <select class="select" name="project_id" data-autosubmit aria-label="Filter by project"> + <option value="">All projects</option> + {% for p in projects %} + <option value="{{ p.project_id }}" {% if generic_selected_project_id == p.project_id %}selected{% endif %}>{{ p.project_display_name }}</option> + {% endfor %} + </select> + <select class="select" name="severity" data-autosubmit aria-label="Filter by severity"> + <option value="">All severities</option> + {% for value, label in generic_dash.severity_filter_options %} + <option value="{{ value }}" {% if generic_selected_severity == value %}selected{% endif %}>{{ label }}</option> + {% endfor %} + </select> + <select class="select" name="verdict" data-autosubmit aria-label="Filter by verdict"> + <option value="">All verdicts</option> + {% for v in generic_dash.verdict_filter_options %} + <option value="{{ v }}" {% if generic_selected_verdict|lower == v|lower %}selected{% endif %}>{{ v }}</option> + {% endfor %} + </select> + <input class="input" type="search" name="q" placeholder="Search title, CWE, verdict..." value="{{ generic_search }}" aria-label="Search findings"> + <div class="filter-bar__actions"> + <button class="btn btn--outline btn--sm" type="submit">Apply</button> + {% if generic_filters_active %}<a class="ds-caption" href="/activities/{{ skill.id }}?status={{ generic_selected_status }}">Clear filters</a>{% endif %} + </div> + </form> + + {% if generic_findings %} + <div class="table-wrap u-mt-4"> + <table class="table"> + <thead> + <tr> + <th>ID</th><th>Title</th><th>Project</th><th>Severity</th><th>CWE</th><th>Verdict</th><th>Last seen</th> + </tr> + </thead> + <tbody> + {% for f in generic_findings %} + <tr class="run-row" data-href="/activities/{{ skill.id }}/findings/{{ f.fingerprint }}" tabindex="0"> + <td><code>{{ f.finding_ref }}</code></td> + <td>{{ f.title }}</td> + <td>{{ f.project_display_name or "-" }}</td> + <td><span class="badge badge--neutral">{{ f.severity }}</span></td> + <td>{{ f.cwe or "—" }}</td> + <td>{{ f.verdict or "—" }}</td> + <td>{{ f.last_seen_at | fmt_time }}</td> + </tr> + {% endfor %} + </tbody> + </table> + </div> + {% else %} + <div class="alert alert--info u-mt-4" role="status"> + <div>No {{ generic_selected_status }} findings{% if generic_filters_active %} match these filters. <a href="/activities/{{ skill.id }}?status={{ generic_selected_status }}">Clear filters</a>{% else %} yet.{% endif %}</div> + </div> + {% endif %} +</div> diff --git a/src/secfoo/web/templates/activities/generic_finding_detail.html b/src/secfoo/web/templates/activities/generic_finding_detail.html new file mode 100644 index 0000000..0432959 --- /dev/null +++ b/src/secfoo/web/templates/activities/generic_finding_detail.html @@ -0,0 +1,33 @@ +{% extends "base.html" %} +{% block title %}{{ finding.finding_ref }}: {{ finding.title }} — {{ skill.nav_label }} — secfoo{% endblock %} +{% block content %} +<a href="/activities/{{ skill.id }}" class="ds-caption">← Back to {{ skill.nav_label }}</a> +<span class="ds-overline u-d-block u-mt-4">{{ skill.nav_label }} · {{ finding.finding_ref }}</span> +<h1>{{ finding.title }}</h1> + +<div class="u-d-flex u-gap-2 u-items-center u-flex-wrap u-mt-3"> + <span class="badge {{ severity_badge_class }}">{{ finding.severity }}</span> + {% if finding.status == "open" %} + <span class="badge badge--error">Open</span> + {% else %} + <span class="badge badge--success">Closed</span> + {% endif %} + {% if finding.cwe %}<span class="badge badge--neutral">{{ finding.cwe }}</span>{% endif %} + {% if finding.verdict %}<span class="badge badge--neutral">{{ finding.verdict }}</span>{% endif %} + {% if finding.project_display_name %}<span class="ds-caption u-color-text-muted">Project: {{ finding.project_display_name }}</span>{% endif %} +</div> + +<div class="card u-mt-4"> + <div class="u-d-flex u-gap-6 u-flex-wrap ds-caption u-color-text-muted"> + <span>First seen: {{ finding.first_seen_at | fmt_time }}</span> + <span>Last seen: {{ finding.last_seen_at | fmt_time }}</span> + {% if finding.closed_at %}<span>Closed: {{ finding.closed_at | fmt_time }}</span>{% endif %} + </div> +</div> + +<div class="card u-mt-6"> + <div class="markdown-body"> + {{ body_html | safe }} + </div> +</div> +{% endblock %} diff --git a/src/secfoo/web/top_findings.py b/src/secfoo/web/top_findings.py index 6eef689..0c44023 100644 --- a/src/secfoo/web/top_findings.py +++ b/src/secfoo/web/top_findings.py @@ -20,7 +20,9 @@ from secfoo import cvss from secfoo.report.architecture import extract_threat_register_rows +from secfoo.report.generic import normalize_generic_severity from secfoo.report.markdown import section as _extract_section +from secfoo.skills.loader import load_all_skills from secfoo.storage.repository import RunRepository from secfoo.web import ( sast_dashboard, @@ -206,6 +208,28 @@ def _threat_modeling_findings(repo: RunRepository) -> list[TopFinding]: return results +def _generic_findings(repo: RunRepository) -> list[TopFinding]: + skills = load_all_skills() + results = [] + for f in repo.list_generic_findings(status="open", limit=1000): + severity = normalize_generic_severity(f.severity) + if severity not in _INCLUDED_SEVERITIES: + continue + skill = skills.get(f.skill_id) + source = skill.nav_label if skill else f.skill_id + results.append( + TopFinding( + source=source, + title=f.title, + project=f.project_display_name or "-", + severity=severity, + detail=f.cwe or f.verdict or f.finding_ref, + url=f"/activities/{f.skill_id}/findings/{f.fingerprint}", + ) + ) + return results + + def build_top_findings(repo: RunRepository, *, limit: int = 15) -> list[TopFinding]: findings = [ *_sast_findings(repo), @@ -214,6 +238,7 @@ def build_top_findings(repo: RunRepository, *, limit: int = 15) -> list[TopFindi *_secret_scanning_findings(repo), *_architecture_findings(repo), *_threat_modeling_findings(repo), + *_generic_findings(repo), ] findings.sort(key=lambda f: _SEVERITY_RANK.get(f.severity, 0), reverse=True) return findings[:limit] diff --git a/tests/test_report/test_generic.py b/tests/test_report/test_generic.py new file mode 100644 index 0000000..25d4cf9 --- /dev/null +++ b/tests/test_report/test_generic.py @@ -0,0 +1,133 @@ +"""Unit tests for the generic OUTPUT_CONTRACT extractor (#92).""" +from __future__ import annotations + +from secfoo.report.generic import ( + extract_generic_report, + fingerprint_for_generic_finding, + normalize_generic_severity, +) + +_VALID_REPORT = """# Custom Review Report + +## Summary +Overall summary of findings. +**Overall risk rating:** High + +## Findings Register +| ID | Finding | Severity | CWE | Verdict | +|----|---------|----------|-----|---------| +| F1 | Missing auth check on export | High | CWE-862 | Confirmed | +| F2 | Verbose error leak | Low | Unverified | Conditional (only in debug) | + +## Findings + +### [HIGH] F1: Missing auth check on export +**Verdict:** Confirmed +**Location:** `api/export.py:18` +Users can export records without a role check. + +### [LOW] F2: Verbose error leak +**Verdict:** Conditional (only in debug) +Stack traces are returned when DEBUG=True. +""" + +_FOUR_COL_REPORT = """# Deployment Readiness Report + +## Summary +**Overall risk rating:** Medium + +## Findings Register +| ID | Finding | Severity | Verdict | +|----|---------|----------|---------| +| F1 | Missing readiness probe | Medium | Confirmed | + +## Findings +### [MEDIUM] F1: Missing readiness probe +**CWE:** CWE-703 +**Verdict:** Confirmed +Add `/readyz` before cutover. +""" + + +def test_extract_valid_contract_report(): + ext = extract_generic_report(_VALID_REPORT, skill_id="custom-review") + assert ext.contract_valid is True + assert ext.overall_rating == "high" + assert len(ext.findings) == 2 + f1, f2 = ext.findings + assert f1["id"] == "F1" + assert f1["title"] == "Missing auth check on export" + assert f1["severity"] == "high" + assert f1["cwe"] == "CWE-862" + assert f1["verdict"] == "Confirmed" + assert "api/export.py:18" in f1["body"] + + assert f2["id"] == "F2" + assert f2["cwe"] == "" + assert f2["verdict"] == "Conditional" + + +def test_extract_four_column_register_and_detail_cwe(): + ext = extract_generic_report(_FOUR_COL_REPORT, skill_id="deployment-readiness") + assert ext.contract_valid is True + assert ext.overall_rating == "medium" + assert len(ext.findings) == 1 + assert ext.findings[0]["cwe"] == "CWE-703" + assert ext.findings[0]["verdict"] == "Confirmed" + + +def test_extract_drifted_headings_without_register_table(): + md = """# Custom Skill Report + +## Summary +**Overall risk rating:** Urgent + +## Findings +### [Urgent] Unencrypted webhook secret +**CWE:** CWE-312 +**Verdict:** Confirmed +Stored in plaintext config. + +### [Informational] Extra telemetry enabled +Logs include timing. +""" + ext = extract_generic_report(md, skill_id="webhook-audit") + assert ext.contract_valid is True + assert ext.overall_rating == "urgent" + assert [f["severity"] for f in ext.findings] == ["urgent", "info"] + assert ext.findings[0]["cwe"] == "CWE-312" + + +def test_extract_malformed_or_off_format_reports_marked_invalid(): + assert extract_generic_report("", skill_id="custom").contract_valid is False + off_format = "# Something Random\n\nAll services looked okay to me." + ext = extract_generic_report(off_format, skill_id="custom") + assert ext.contract_valid is False + assert ext.findings == [] + + +def test_extract_clean_zero_finding_report_is_valid(): + clean = """# Deployment Readiness Report + +## Summary +**Overall risk rating:** Low + +## Findings Register +No findings identified. + +## Findings +No findings. +""" + ext = extract_generic_report(clean, skill_id="deployment-readiness") + assert ext.contract_valid is True + assert ext.overall_rating == "low" + assert ext.findings == [] + + +def test_fingerprint_stability_and_custom_severity_normalization(): + assert normalize_generic_severity("`Informational`") == "info" + assert normalize_generic_severity("Blocker") == "blocker" + fp_a = fingerprint_for_generic_finding("s1", title="Missing Check", cwe="cwe-862") + fp_b = fingerprint_for_generic_finding("s1", title="missing check", cwe="CWE-862") + assert fp_a == fp_b + assert fp_a != fingerprint_for_generic_finding("s2", title="Missing Check", cwe="CWE-862") diff --git a/tests/test_web/test_generic_dashboard.py b/tests/test_web/test_generic_dashboard.py new file mode 100644 index 0000000..67323a6 --- /dev/null +++ b/tests/test_web/test_generic_dashboard.py @@ -0,0 +1,401 @@ +"""End-to-end tests for dynamic custom skill dashboards (#92).""" +from __future__ import annotations + +import sqlite3 +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from secfoo.runner import update_generic_findings +from secfoo.storage.repository import SCHEMA_INDEXES_PATH, SCHEMA_PATH, RunRepository +from secfoo.web.app import create_app +from secfoo.web.top_findings import build_top_findings + +_RUN1_REPORT = """# API Hygiene Report + +## Summary +**Overall risk rating:** High + +## Findings Register +| ID | Finding | Severity | CWE | Verdict | +|----|---------|----------|-----|---------| +| F1 | Unbounded GraphQL depth | High | CWE-400 | Confirmed | +| F2 | Missing rate limit on reset | Medium | CWE-307 | Likely | +| F3 | Urgent schema exposure | Urgent | None | Confirmed | + +## Findings + +### [HIGH] F1: Unbounded GraphQL depth +**Verdict:** Confirmed +Arbitrarily nested queries trigger OOM. <script>alert(1)</script> + +### [MEDIUM] F2: Missing rate limit on reset +**Verdict:** Likely +Brute force risk on password reset. + +### [URGENT] F3: Urgent schema exposure +**Verdict:** Confirmed +Introspection left enabled in production. +""" + +_RUN2_REPORT = """# API Hygiene Report + +## Summary +**Overall risk rating:** Medium + +## Findings Register +| ID | Finding | Severity | CWE | Verdict | +|----|---------|----------|-----|---------| +| F1 | Unbounded GraphQL depth | High | CWE-400 | Confirmed | + +## Findings + +### [HIGH] F1: Unbounded GraphQL depth +**Verdict:** Confirmed +Still present in gateway. +""" + +_MALFORMED_REPORT = """This model ignored instructions completely and wrote plain text without headings.""" + + +@pytest.fixture +def env(tmp_path, monkeypatch, _isolated_custom_skills): + db_path = tmp_path / "db.sqlite" + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", db_path) + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + reports_dir = tmp_path / "reports" + reports_dir.mkdir(parents=True, exist_ok=True) + return { + "db_path": db_path, + "home": _isolated_custom_skills, + "reports_dir": reports_dir, + } + + +def _write_custom_skill(home: Path, skill_id: str, *, extra: str = "") -> Path: + skills_dir = home / "skills" + skills_dir.mkdir(parents=True, exist_ok=True) + p = skills_dir / f"{skill_id}.md" + p.write_text( + f"---\nid: {skill_id}\nname: {skill_id.replace('-', ' ').title()}\n" + f"description: Custom skill\nversion: 1\n{extra}---\n\nInspect target.\n", + encoding="utf-8", + ) + return p + + +def _record_run( + repo: RunRepository, + reports_dir: Path, + *, + project_id: int, + skill_id: str, + skill_name: str, + report_name: str, + markdown: str, + critical: int = 0, + high: int = 0, + medium: int = 0, + low: int = 0, + info: int = 0, + run_lifecycle: bool = True, +) -> tuple[str, int]: + report_path = reports_dir / report_name + report_path.write_text(markdown, encoding="utf-8") + run_uuid = repo.create_run( + project_id=project_id, + skill_id=skill_id, + skill_name=skill_name, + agent_id="claude", + confluence_urls=[], + ) + repo.complete_run( + run_uuid, + status="success", + exit_code=0, + duration_seconds=1.2, + report_path=str(report_path), + prompt_path=None, + stderr_excerpt=None, + critical_count=critical, + high_count=high, + medium_count=medium, + low_count=low, + info_count=info, + ) + run = repo.get_run(run_uuid) + if run_lifecycle: + update_generic_findings( + repo, skill_id=skill_id, project_id=project_id, run_id=run.id, report_text=markdown + ) + return run_uuid, run.id + + +def test_generic_dashboard_lifecycle_filters_detail_and_custom_severity(env): + _write_custom_skill(env["home"], "api-hygiene") + client = TestClient(create_app()) + + with RunRepository() as repo: + p1 = repo.upsert_project("https://github.com/acme/api", "acme/api", "github") + p2 = repo.upsert_project("https://github.com/acme/web", "acme/web", "github") + _record_run( + repo, + env["reports_dir"], + project_id=p1, + skill_id="api-hygiene", + skill_name="Api Hygiene", + report_name="r1.md", + markdown=_RUN1_REPORT, + high=1, + medium=1, + ) + # Run 2 drops F2 and F3 -> they close automatically while F1 remains open + _record_run( + repo, + env["reports_dir"], + project_id=p1, + skill_id="api-hygiene", + skill_name="Api Hygiene", + report_name="r2.md", + markdown=_RUN2_REPORT, + high=1, + ) + # Run 3 re-introduces F2 and F3 -> both reopen! + _record_run( + repo, + env["reports_dir"], + project_id=p1, + skill_id="api-hygiene", + skill_name="Api Hygiene", + report_name="r3.md", + markdown=_RUN1_REPORT, + high=1, + medium=1, + ) + # Run 2 again closes F2 and F3 cleanly for open/closed tab verification + _record_run( + repo, + env["reports_dir"], + project_id=p1, + skill_id="api-hygiene", + skill_name="Api Hygiene", + report_name="r4.md", + markdown=_RUN2_REPORT, + high=1, + ) + # Second project with off-format report -> surfaces visible warning + _record_run( + repo, + env["reports_dir"], + project_id=p2, + skill_id="api-hygiene", + skill_name="Api Hygiene", + report_name="bad.md", + markdown=_MALFORMED_REPORT, + ) + + resp = client.get("/activities/api-hygiene") + assert resp.status_code == 200 + html = resp.text + assert "Open (1)" in html + assert "Closed (2)" in html + assert "Unbounded GraphQL depth" in html + assert "Overall risk rating distribution" in html + assert "Report did not follow the output contract" in html + assert "Findings trend (newest 5 runs)" in html + + # Closed tab shows F2 and custom-severity F3 ('Urgent' bucket present in filter options too) + closed_resp = client.get("/activities/api-hygiene?status=closed") + assert closed_resp.status_code == 200 + assert "Missing rate limit on reset" in closed_resp.text + assert "Urgent schema exposure" in closed_resp.text + assert 'value="urgent"' in closed_resp.text + + # Severity / verdict / query / project filters + assert "Urgent schema exposure" in client.get("/activities/api-hygiene?status=closed&severity=urgent").text + assert "Unbounded GraphQL depth" not in client.get("/activities/api-hygiene?q=NoMatchHere").text + assert "Unbounded GraphQL depth" in client.get("/activities/api-hygiene?verdict=Confirmed").text + assert "Unbounded GraphQL depth" not in client.get(f"/activities/api-hygiene?project_id={p2}").text + + # Detail page renders markdown body and escapes raw HTML/XSS + with RunRepository() as repo: + open_items = repo.list_generic_findings(skill_id="api-hygiene", status="open") + fp = open_items[0].fingerprint + top = build_top_findings(repo) + assert any(t.url == f"/activities/api-hygiene/findings/{fp}" for t in top) + + detail = client.get(f"/activities/api-hygiene/findings/{fp}") + assert detail.status_code == 200 + assert "Unbounded GraphQL depth" in detail.text + assert "<script>alert(1)</script>" not in detail.text + assert client.get("/activities/api-hygiene/findings/missing").status_code == 404 + + +def test_builtin_deployment_readiness_uses_generic_dashboard(env): + client = TestClient(create_app()) + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/svc", "acme/svc", "github") + _record_run( + repo, + env["reports_dir"], + project_id=pid, + skill_id="deployment-readiness", + skill_name="Deployment Readiness", + report_name="dr.md", + markdown=_RUN1_REPORT, + high=1, + medium=1, + ) + resp = client.get("/activities/deployment-readiness") + assert resp.status_code == 200 + assert "Findings register" in resp.text + assert "Unbounded GraphQL depth" in resp.text + + +def test_skill_added_after_app_start_appears_everywhere_live(env): + client = TestClient(create_app()) + # Create skill AFTER create_app() has already constructed routes & Jinja globals + _write_custom_skill(env["home"], "late-added-audit") + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/late", "acme/late", "github") + _record_run( + repo, + env["reports_dir"], + project_id=pid, + skill_id="late-added-audit", + skill_name="Late Added Audit", + report_name="late.md", + markdown=_RUN2_REPORT, + high=1, + ) + + overview = client.get("/") + assert overview.status_code == 200 + assert "/activities/late-added-audit" in overview.text + + proj = client.get(f"/projects/{pid}") + assert proj.status_code == 200 + assert "/activities/late-added-audit" in proj.text + + activity = client.get("/activities/late-added-audit") + assert activity.status_code == 200 + assert "Unbounded GraphQL depth" in activity.text + + +def test_custom_sast_output_routes_to_generic_dashboard_not_builtin_sast(env): + _write_custom_skill(env["home"], "my-sast", extra="output: sast\n") + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/acme/svc", "acme/svc", "github") + # Record a finding on the built-in SAST skill plus a distinct finding on my-sast + _, sast_run_id = _record_run( + repo, + env["reports_dir"], + project_id=pid, + skill_id="sast", + skill_name="SAST", + report_name="builtin-sast.md", + markdown=_RUN1_REPORT, + high=1, + run_lifecycle=False, + ) + repo.upsert_sast_finding( + project_id=pid, + fingerprint="builtin-sast-fp", + current_ref="S1", + title="Built-in SAST SQLi", + severity="high", + cwe=None, + owasp=None, + verdict=None, + location_file="app.py", + location_line=10, + cvss_vector=None, + cvss_score=None, + run_id=sast_run_id, + ) + _record_run( + repo, + env["reports_dir"], + project_id=pid, + skill_id="my-sast", + skill_name="My Sast", + report_name="my-sast.md", + markdown=_RUN2_REPORT, + high=1, + ) + client = TestClient(create_app()) + resp = client.get("/activities/my-sast") + assert resp.status_code == 200 + assert "Overall risk rating distribution" in resp.text + assert "Unbounded GraphQL depth" in resp.text + assert "Built-in SAST SQLi" not in resp.text + assert "Top vulnerability types" not in resp.text + + +def test_responsible_ai_does_not_render_generic_dashboard(env): + client = TestClient(create_app()) + resp = client.get("/activities/responsible-ai-compliance") + assert resp.status_code == 200 + assert "Overall risk rating distribution" not in resp.text + + +def test_existing_database_backfills_generic_findings_once(env): + db_path = env["db_path"] + report1 = env["reports_dir"] / "legacy1.md" + report2 = env["reports_dir"] / "legacy2.md" + report1.write_text(_RUN1_REPORT, encoding="utf-8") + report2.write_text(_RUN2_REPORT, encoding="utf-8") + + # Simulate pre-existing DB before #92 with two completed runs and no generic_findings rows + conn = sqlite3.connect(db_path) + conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8")) + conn.executescript(SCHEMA_INDEXES_PATH.read_text(encoding="utf-8")) + conn.execute( + "INSERT INTO projects (identifier, display_name, kind, first_seen_at, last_run_at) VALUES (?, ?, ?, ?, ?)", + ( + "https://github.com/acme/legacy", + "acme/legacy", + "github", + "2026-10-01T00:00:00+00:00", + "2026-10-02T00:01:00+00:00", + ), + ) + conn.execute( + "INSERT INTO runs (run_uuid, project_id, skill_id, skill_name, agent_id, started_at, finished_at, " + "status, report_path, high_count, medium_count) VALUES (?, 1, ?, ?, ?, ?, ?, 'success', ?, 1, 1)", + ( + "run-legacy-1", + "legacy-skill", + "Legacy Skill", + "claude", + "2026-10-01T00:00:00+00:00", + "2026-10-01T00:01:00+00:00", + str(report1), + ), + ) + conn.execute( + "INSERT INTO runs (run_uuid, project_id, skill_id, skill_name, agent_id, started_at, finished_at, " + "status, report_path, high_count, medium_count) VALUES (?, 1, ?, ?, ?, ?, ?, 'success', ?, 1, 0)", + ( + "run-legacy-2", + "legacy-skill", + "Legacy Skill", + "claude", + "2026-10-02T00:00:00+00:00", + "2026-10-02T00:01:00+00:00", + str(report2), + ), + ) + conn.commit() + conn.close() + + with RunRepository() as repo: + open_rows = repo.list_generic_findings(skill_id="legacy-skill", status="open") + closed_rows = repo.list_generic_findings(skill_id="legacy-skill", status="closed") + migrated = repo._conn.execute( + "SELECT 1 FROM schema_migrations WHERE key = 'generic_findings_backfill_v1'" + ).fetchone() + assert migrated is not None + assert len(open_rows) == 1 + assert len(closed_rows) == 2