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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,9 @@ the [CLI reference](https://secfoo.com/docs/cli.html) for more.
- **Review architecture and threat-model a system** against secure
design principles, STRIDE/LINDDUN, and CSA CCM v4 domain conformance
- **Find code and dependency vulnerabilities** — SAST and SCA reachability
triage, tracked as an Open/Closed Findings register across rescans, not
just a one-off report
triage; SAST uses an Open/Closed register keyed by skill + CWE + file +
a hash of the vulnerable source region (not agent wording), so rescans
stay stable when the model paraphrases
- **Catch exposed credentials** across source, config, git history, and
linked Confluence pages
- **Review LLM prompts and agent tool definitions** for injection and
Expand Down
32 changes: 32 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,38 @@ text on every request — there is no persistent per-finding lifecycle.
Findings link to a detail page keyed by `(project, finding ID, type,
location)` so duplicate rows in a report remain addressable.

### SAST Open/Closed finding identity

The SAST activity dashboard (`/activities/sast`) is the one program view
with a **persistent per-finding lifecycle** (`sast_findings` table). After
each successful local `sast` run, secfoo parses the report's **Findings
Register** (structured columns the skill contract requires) and upserts by
fingerprint; findings not seen again are closed.

**Fingerprint (no embedding or title matching):**

| Input | Used for identity? |
|-------|-------------------|
| Skill id (`sast`) | Yes |
| CWE (register column) | Yes |
| Normalized file path (Location column) | Yes |
| Source **code-region hash** (±4 lines at reported line, from repo on disk) | Yes, when `workdir` is available |
| Title, description, recommendation | No — refreshed each run for display |
| Per-run `F1`, `F2` ids | No |
| Exact line number | No — except cloud-ingest fallback (below) |

When the scan target is on disk (`secfoo run`), `report/code_region.py`
hashes a small normalized window of source at the line in the Location
column. Two distinct issues in the same file (same CWE) get different keys
even if the agent rephrases titles. When only the report is available
(e.g. `secfoo cloud sync` ingest), identity falls back to CWE + path, with
a coarse line-bucket only if multiple register rows in **one** report share
the same CWE and file.

Open rows keyed with the legacy fingerprint are **rekeyed** automatically
on the first rescan that computes a region hash. There is no post-hoc
embedding similarity on finding text.

## Install

Pick whichever fits how you work — they're all the same tool underneath.
Expand Down
65 changes: 65 additions & 0 deletions src/secfoo/report/code_region.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""Hash a small window of source around a reported line for stable SAST identity.

Used by report/sast.py fingerprinting so two distinct issues in the same file
(CWE + path) stay separate even when the agent paraphrases titles, while the
same underlying code region keeps a stable key across rescans.
"""

from __future__ import annotations

import hashlib
import re
from pathlib import Path

# Lines before/after the reported line (inclusive window).
_CONTEXT_LINES = 4

# Collapse horizontal whitespace so formatting-only edits don't churn the hash.
_WS_RE = re.compile(r"[ \t]+")


def _normalize_snippet_line(line: str) -> str:
return _WS_RE.sub(" ", line.rstrip())


def hash_code_region(workdir: Path, file_path: str, line: str | int | None) -> str | None:
"""Return SHA-256 hex of normalized source around `line`, or None if unavailable."""
if line is None:
return None
try:
center = int(str(line).strip())
except ValueError:
return None
if center < 1:
return None

rel = file_path.strip().lstrip("./")
if not rel or rel.startswith("..") or "/../" in rel:
return None

root = workdir.resolve()
target = (root / rel).resolve()
try:
target.relative_to(root)
except ValueError:
return None
if not target.is_file():
return None

try:
text = target.read_text(encoding="utf-8", errors="replace")
except OSError:
return None
if "\x00" in text:
return None

lines = text.splitlines()
start = max(center - 1 - _CONTEXT_LINES, 0)
end = min(center - 1 + _CONTEXT_LINES + 1, len(lines))
if start >= len(lines):
return None

window = "\n".join(_normalize_snippet_line(line) for line in lines[start:end])
if not window.strip():
return None
return hashlib.sha256(window.encode("utf-8")).hexdigest()
86 changes: 52 additions & 34 deletions src/secfoo/report/sast.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,34 @@
a stable identity for "the same bug" across two separate runs, which this
report's own `Fn` IDs cannot provide -- they restart at F1 every run.

The fingerprint is CWE + normalized file path, deliberately NOT the
finding's title or its line number:

- Line number is unstable -- any unrelated edit elsewhere in the file can
shift it even when the vulnerable line itself never moved.
- Title is prose the model regenerates from scratch each run; keying on it
would turn harmless rephrasing ("SQL Injection via raw query" one run,
"SQLi in user search endpoint" the next) into a false "this finding was
fixed, and a new one was found" -- silently dropping a still-open bug off
the Open list. That failure mode (false "closed") is strictly worse than
the alternative (a genuinely-fixed finding lingers one extra scan as
"open" before nothing re-matches it and it correctly closes), so the
fingerprint deliberately biases toward over-matching.

Known failure modes of this approximation, worth remembering when reading
the resulting Open/Closed lists: a CWE reclassification between runs (a
partial fix that changes which CWE best describes what remains) looks like
close+reopen, not "the same finding, narrowed"; a file rename looks like
close+reopen, not "the same finding, moved"; two distinct findings sharing
both CWE and file collide onto one fingerprint unless the per-run
collision guard below (a coarse line-bucket, added only when a run's own
findings actually collide) keeps them apart.
The fingerprint is skill id + CWE + normalized file path + a hash of the
source *code region* around the reported line (when the scan target is
available on disk). It is deliberately NOT the finding's title,
description, or raw line number:

- Title/description are prose the model regenerates each run; keying on them
would treat paraphrase as "fixed + new finding."
- Line number alone is unstable when unrelated edits shift line numbers.
- When `workdir` is passed (local `secfoo run`), `code_region.hash_code_region`
hashes a small normalized window of actual source at the reported line so
two distinct issues in the same file stay separate even with the same CWE.
- When `workdir` is unavailable (e.g. cloud ingest with report only), the
fingerprint falls back to CWE + path plus the same-run line-bucket collision
guard documented below.

Known failure modes: CWE reclassification or file rename still look like
close+reopen; a fix that changes the hashed snippet closes correctly; cloud-
only ingest without the repo on disk cannot compute a region hash.
"""

from __future__ import annotations

import hashlib
import re
from pathlib import Path

from secfoo.report.architecture import _extract_section
from secfoo.report.code_region import hash_code_region

SKILL_ID = "sast"

Expand Down Expand Up @@ -133,21 +131,34 @@ def _normalize_path(file_path: str) -> str:
return file_path.strip().lstrip("./").lower()


def fingerprint_for_row(row: dict[str, str], *, line_bucket: str | None = None) -> str:
"""CWE + normalized file path (see module docstring for why not title
or line), optionally widened with a coarse line-bucket suffix when the
caller has detected this row would otherwise collide with another
finding of the same CWE in the same file within the same run.
"""
def fingerprint_for_row(
row: dict[str, str],
*,
line_bucket: str | None = None,
region_hash: str | None = None,
) -> str:
"""Stable cross-run identity from contract fields + optional source hash."""
file_path, _line = parse_location(row["location"])
cwe = row.get("cwe", "").strip().lower()
raw = f"{cwe}|{_normalize_path(file_path)}"
if line_bucket is not None:
raw += f"|{line_bucket}"
parts = [SKILL_ID, cwe, _normalize_path(file_path)]
if region_hash:
parts.append(region_hash)
elif line_bucket is not None:
parts.append(f"linebucket:{line_bucket}")
raw = "|".join(parts)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def findings_with_fingerprints(report_markdown: str) -> list[dict[str, str]]:
def legacy_fingerprint_for_row(row: dict[str, str], *, line_bucket: str | None = None) -> str:
"""Pre-region-hash identity (CWE + path [+ line bucket]). Used to rekey open rows on upgrade."""
return fingerprint_for_row(row, line_bucket=line_bucket, region_hash=None)


def findings_with_fingerprints(
report_markdown: str,
*,
workdir: Path | None = None,
) -> list[dict[str, str]]:
"""One dict per Findings Register row, joined with its Detailed
Findings block (description/recommendation) and its fingerprint --
computed with the per-run collision guard: only rows that share both
Expand Down Expand Up @@ -175,17 +186,24 @@ def findings_with_fingerprints(report_markdown: str) -> list[dict[str, str]]:
for index, row in enumerate(rows):
file_path, line = parsed_locations[index]
key = (row.get("cwe", "").strip().lower(), _normalize_path(file_path))
region_hash = None
if workdir is not None and line is not None:
region_hash = hash_code_region(workdir, file_path, line)

line_bucket = None
if len(groups[key]) > 1 and line is not None:
if region_hash is None and len(groups[key]) > 1 and line is not None:
line_bucket = str(int(line) // 20)
fingerprint = fingerprint_for_row(row, line_bucket=line_bucket)
fingerprint = fingerprint_for_row(row, line_bucket=line_bucket, region_hash=region_hash)
legacy_fingerprint = legacy_fingerprint_for_row(row, line_bucket=line_bucket)

results.append(
{
**row,
"location_file": file_path,
"location_line": line,
"code_region_hash": region_hash,
"fingerprint": fingerprint,
"legacy_fingerprint": legacy_fingerprint,
"description": descriptions.get(row["id"], ""),
"recommendation": recommendations.get(row["id"], ""),
}
Expand Down
25 changes: 22 additions & 3 deletions src/secfoo/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,14 @@ def _try_osv_enrich(repo: RunRepository, report_text: str) -> None:
pass


def update_sast_findings(repo: RunRepository, *, project_id: int, run_id: int, report_text: str) -> None:
def update_sast_findings(
repo: RunRepository,
*,
project_id: int,
run_id: int,
report_text: str,
workdir: Path | None = None,
) -> None:
"""Matches this run's Findings Register against the project's
currently-open sast_findings rows by fingerprint (report/sast.py),
upserting seen-again/new findings and closing whatever was open but
Expand All @@ -129,9 +136,16 @@ def update_sast_findings(repo: RunRepository, *, project_id: int, run_id: int, r
in the tenant's `runs` table with a real report but never update
Open/Closed Findings at all.
"""
findings = findings_with_fingerprints(report_text)
findings = findings_with_fingerprints(report_text, workdir=workdir)
seen_fingerprints = []
for row in findings:
legacy_fp = row.get("legacy_fingerprint")
if legacy_fp and legacy_fp != row["fingerprint"]:
repo.rekey_open_sast_fingerprint(
project_id=project_id,
old_fingerprint=legacy_fp,
new_fingerprint=row["fingerprint"],
)
vector = row.get("cvss_vector", "").strip()
score = None
if vector:
Expand All @@ -153,6 +167,7 @@ def update_sast_findings(repo: RunRepository, *, project_id: int, run_id: int, r
verdict=row.get("verdict") or None,
location_file=row["location_file"],
location_line=row.get("location_line"),
code_region_hash=row.get("code_region_hash"),
cvss_vector=vector or None,
cvss_score=score,
description=row.get("description") or None,
Expand Down Expand Up @@ -260,7 +275,11 @@ def _run_single_skill(
try:
completed_run = repo.get_run(run_uuid)
update_sast_findings(
repo, project_id=project_id, run_id=completed_run.id, report_text=report_text
repo,
project_id=project_id,
run_id=completed_run.id,
report_text=report_text,
workdir=target_ctx.local_path,
)
except Exception:
logger.exception("Failed to update SAST finding lifecycle for run %s", run_uuid)
Expand Down
1 change: 1 addition & 0 deletions src/secfoo/storage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ class SastFindingRecord:
location_line: str | None
cvss_vector: str | None
cvss_score: float | None
code_region_hash: str | None
status: str
first_seen_run_id: int
first_seen_at: str
Expand Down
45 changes: 40 additions & 5 deletions src/secfoo/storage/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,10 @@ def use_db_path(path: Path):
"assessment_uuid": "ALTER TABLE assessments ADD COLUMN assessment_uuid TEXT",
}

_SAST_FINDINGS_MIGRATIONS = {
"code_region_hash": "ALTER TABLE sast_findings ADD COLUMN code_region_hash TEXT",
}

_ASSESSMENT_UPDATE_FIELDS = {
"assessment_type", "status", "application_id", "sar_number", "reviewer", "review_date", "notes",
}
Expand Down Expand Up @@ -124,6 +128,12 @@ def _migrate(self) -> None:
for column, ddl in _ASSESSMENTS_MIGRATIONS.items():
if column not in existing_assessment_cols:
self._conn.execute(ddl)
existing_sast_cols = {
row["name"] for row in self._conn.execute("PRAGMA table_info(sast_findings)").fetchall()
}
for column, ddl in _SAST_FINDINGS_MIGRATIONS.items():
if column not in existing_sast_cols:
self._conn.execute(ddl)
self._conn.commit()
self._migrate_attachment_kind_check()

Expand Down Expand Up @@ -1187,6 +1197,7 @@ def upsert_sast_finding(
run_id: int,
description: str | None = None,
recommendation: str | None = None,
code_region_hash: str | None = None,
) -> None:
"""Inserts a newly-seen finding as open, or -- on a conflicting
(project_id, fingerprint) -- refreshes it from this run's report
Expand All @@ -1198,25 +1209,49 @@ def upsert_sast_finding(
now = _now()
self._conn.execute(
"INSERT INTO sast_findings (project_id, fingerprint, current_ref, title, severity, cwe, "
"owasp, verdict, location_file, location_line, cvss_vector, cvss_score, description, "
"recommendation, status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) "
"owasp, verdict, location_file, location_line, code_region_hash, cvss_vector, cvss_score, "
"description, recommendation, status, first_seen_run_id, first_seen_at, last_seen_run_id, "
"last_seen_at) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) "
"ON CONFLICT(project_id, fingerprint) DO UPDATE SET "
"current_ref = excluded.current_ref, title = excluded.title, severity = excluded.severity, "
"cwe = excluded.cwe, owasp = excluded.owasp, verdict = excluded.verdict, "
"location_file = excluded.location_file, location_line = excluded.location_line, "
"code_region_hash = excluded.code_region_hash, "
"cvss_vector = excluded.cvss_vector, cvss_score = excluded.cvss_score, "
"description = excluded.description, recommendation = excluded.recommendation, 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, fingerprint, current_ref, title, severity, cwe, owasp, verdict,
location_file, location_line, cvss_vector, cvss_score, description, recommendation,
run_id, now, run_id, now,
location_file, location_line, code_region_hash, cvss_vector, cvss_score,
description, recommendation, run_id, now, run_id, now,
),
)
self._conn.commit()

def rekey_open_sast_fingerprint(
self, *, project_id: int, old_fingerprint: str, new_fingerprint: str
) -> None:
"""Upgrade an open row from a legacy fingerprint to a region-aware key.

No-op when the new key already exists or the old row is missing/closed.
"""
if old_fingerprint == new_fingerprint:
return
exists = self._conn.execute(
"SELECT 1 FROM sast_findings WHERE project_id = ? AND fingerprint = ?",
(project_id, new_fingerprint),
).fetchone()
if exists:
return
self._conn.execute(
"UPDATE sast_findings SET fingerprint = ? "
"WHERE project_id = ? AND fingerprint = ? AND status = 'open'",
(new_fingerprint, project_id, old_fingerprint),
)
self._conn.commit()

def close_stale_sast_findings(
self, *, project_id: int, run_id: int, seen_fingerprints: list[str], closed_at: str
) -> None:
Expand Down
Loading
Loading