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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 210 additions & 0 deletions src/secfoo/report/generic.py
Original file line number Diff line number Diff line change
@@ -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<id>[A-Za-z]+\d+)`?\s*\|(?P<title>[^|]*)\|(?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)
64 changes: 63 additions & 1 deletion src/secfoo/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
22 changes: 22 additions & 0 deletions src/secfoo/storage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading