Top findings
{% if f.cvss_vector | cvss_network_reachable %}External{% endif %}
{{ f.title }} {{ f.cwe or "unverified" }} |
- {{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %} |
+ {% if f.locations %}{{ f.locations[0] | fmt_location }}{% if f.locations | length > 1 %} (+{{ (f.locations | length) - 1 }} more){% endif %}{% else %}{{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %}{% endif %} |
{{ f.last_seen_at | fmt_time }} |
{% if f.cvss_score is not none %}
diff --git a/src/secfoo/web/templates/activities/sast_finding_detail.html b/src/secfoo/web/templates/activities/sast_finding_detail.html
index a7bd1e5..1a58c13 100644
--- a/src/secfoo/web/templates/activities/sast_finding_detail.html
+++ b/src/secfoo/web/templates/activities/sast_finding_detail.html
@@ -13,7 +13,7 @@ {{ finding.title }}
{{ finding.cwe or "unverified" }}{% if finding.owasp and finding.owasp != "unverified" %} · {{ finding.owasp }}{% endif %}
- · {{ finding.location_file }}{% if finding.location_line %}:{{ finding.location_line }}{% endif %}
+ · {% if finding.locations %}{% for loc in finding.locations %}{{ loc | fmt_location }}{% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ finding.location_file }}{% if finding.location_line %}:{{ finding.location_line }}{% endif %}{% endif %}
diff --git a/src/secfoo/web/templates/activities/sast_findings_list.html b/src/secfoo/web/templates/activities/sast_findings_list.html
index 69f1611..af2d5bf 100644
--- a/src/secfoo/web/templates/activities/sast_findings_list.html
+++ b/src/secfoo/web/templates/activities/sast_findings_list.html
@@ -51,7 +51,7 @@ All findings
{% if f.cvss_vector | cvss_network_reachable %}External{% endif %}
|
{{ f.title }} {{ f.cwe or "unverified" }} |
- {{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %} |
+ {% if f.locations %}{{ f.locations[0] | fmt_location }}{% if f.locations | length > 1 %} (+{{ (f.locations | length) - 1 }} more){% endif %}{% else %}{{ f.location_file }}{% if f.location_line %}:{{ f.location_line }}{% endif %}{% endif %} |
{{ f.last_seen_at | fmt_time }} |
{% if f.cvss_score is not none %}
diff --git a/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html b/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html
index 3620bf2..36a3be0 100644
--- a/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html
+++ b/src/secfoo/web/templates/activities/secret_scanning_finding_detail.html
@@ -10,7 +10,7 @@
{{ finding.secret_type }}
- {{ finding.project_display_name }} · {{ finding.source }} · {{ finding.location }}
+ {{ finding.project_display_name }} · {{ finding.source }} · {% if finding.locations %}{% for loc in finding.locations %}{{ loc | fmt_location }}{% if not loop.last %}, {% endif %}{% endfor %}{% else %}{{ finding.location }}{% endif %}
{% if finding.validity.lower() == 'looks live' %}
diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py
index 185585b..311676e 100644
--- a/src/secfoo/web/templating.py
+++ b/src/secfoo/web/templating.py
@@ -10,6 +10,7 @@
from secfoo.cvss import CvssError, parse_vector
from secfoo.cvss import rating as cvss_rating
from secfoo.report.architecture import classify_design_verdict
+from secfoo.report.sast import format_location_site
from secfoo.skills.loader import load_all_skills
TEMPLATES_DIR = Path(__file__).parent / "templates"
@@ -336,3 +337,4 @@ def https_url(value: str | None) -> str:
templates.env.filters["responsible_ai_risk_badge"] = responsible_ai_risk_badge_class
templates.env.filters["responsible_ai_status_badge"] = responsible_ai_status_badge_class
templates.env.filters["design_verdict_badge"] = design_verdict_badge_class
+templates.env.filters["fmt_location"] = format_location_site
diff --git a/tests/test_property_parsers.py b/tests/test_property_parsers.py
index 303649c..5cc2e7f 100644
--- a/tests/test_property_parsers.py
+++ b/tests/test_property_parsers.py
@@ -9,9 +9,12 @@
from __future__ import annotations
+import re
+
from hypothesis import given, settings
from hypothesis import strategies as st
+from secfoo.report.sast import parse_location, parse_locations
from secfoo.report.severity import (
SeverityCounts,
count_severities,
@@ -138,3 +141,91 @@ def test_normalize_severity_is_total_and_idempotent(value):
@given(st.sampled_from(sorted(_VALID_SEVERITIES) + ["informational"]), st.text(alphabet=" \t", max_size=4))
def test_normalize_severity_ignores_case_and_padding(word, pad):
assert normalize_severity(pad + word.upper() + pad) == normalize_severity(word)
+
+
+# --------------------------------------------------------------------------- #
+# report/sast.py location parser
+# --------------------------------------------------------------------------- #
+
+_TRAILING_RANGE_RE = re.compile(r":\s*(?:[Ll](?:ine)?s?\s*)?[-–—]?\s*\d+(?:\s*[-–—]\s*\d*)?\s*$")
+
+clean_segment = st.from_regex(r"[A-Za-z0-9_.\-]{1,12}", fullmatch=True).filter(
+ lambda seg: seg not in {"...", "."} and not seg.isdigit()
+)
+clean_path = st.lists(clean_segment, min_size=1, max_size=4).map("/".join)
+line_num = st.integers(min_value=1, max_value=9999)
+
+
+@st.composite
+def location_site_strategy(draw):
+ path = draw(clean_path)
+ kind = draw(st.sampled_from(["none", "single", "range"]))
+ if kind == "none":
+ return (path, None, None)
+ start = draw(line_num)
+ if kind == "single":
+ return (path, start, None)
+ end = draw(st.integers(min_value=start + 1, max_value=start + 500))
+ return (path, start, end)
+
+
+@given(st.text())
+@settings(max_examples=500)
+def test_parse_location_never_returns_delimiters_backticks_or_trailing_range(text):
+ path, line = parse_location(text)
+ assert "," not in path
+ assert ";" not in path
+ assert "`" not in path
+ assert not _TRAILING_RANGE_RE.search(path)
+ if line is not None:
+ assert line.isascii() and line.isdigit() and int(line) >= 1
+
+ for site_path, start_line, end_line in parse_locations(text):
+ assert site_path
+ assert "," not in site_path
+ assert ";" not in site_path
+ assert "`" not in site_path
+ assert not _TRAILING_RANGE_RE.search(site_path)
+ if start_line is None:
+ assert end_line is None
+ else:
+ assert start_line >= 1
+ if end_line is not None:
+ assert end_line > start_line
+
+
+@given(
+ sites=st.lists(location_site_strategy(), min_size=1, max_size=6),
+ separators=st.lists(st.sampled_from([", ", "; ", ",", ";"]), min_size=5, max_size=5),
+ backtick_each=st.booleans(),
+ use_bare_continuation=st.booleans(),
+)
+def test_parse_locations_round_trips_structured_sites(
+ sites, separators, backtick_each, use_bare_continuation
+):
+ tokens = []
+ expected = []
+ prev_path = None
+ for idx, (path, start, end) in enumerate(sites):
+ if use_bare_continuation and prev_path is not None and start is not None and idx % 2 == 1:
+ actual_path = prev_path
+ rendered = f":{start}-{end}" if end is not None else f":{start}"
+ else:
+ actual_path = path
+ if start is None:
+ rendered = path
+ elif end is None:
+ rendered = f"{path}:{start}"
+ else:
+ rendered = f"{path}:{start}-{end}"
+ prev_path = actual_path
+ expected.append((actual_path, start, end))
+ tokens.append(f"`{rendered}`" if backtick_each else rendered)
+
+ joined = tokens[0]
+ for idx, token in enumerate(tokens[1:]):
+ joined += separators[idx] + token
+
+ assert parse_locations(joined) == expected
+ first_path, first_start, _ = expected[0]
+ assert parse_location(joined) == (first_path, str(first_start) if first_start is not None else None)
diff --git a/tests/test_report/test_sarif.py b/tests/test_report/test_sarif.py
index f2e5782..ac52388 100644
--- a/tests/test_report/test_sarif.py
+++ b/tests/test_report/test_sarif.py
@@ -95,3 +95,91 @@ def test_cwe_tags_are_normalized_deduplicated_and_unknown_values_ignored():
rules = run["tool"]["driver"]["rules"]
assert rules[0]["properties"]["tags"] == ["security", "external/cwe/cwe-79", "external/cwe/cwe-89"]
assert rules[1]["properties"]["tags"] == ["security"]
+
+
+def test_multi_site_and_range_locations_emit_per_site_sarif_regions():
+ records = [
+ {
+ "skill_id": "sast",
+ "severity": "High",
+ "cwe": "CWE-79",
+ "title": "Autoescape disabled",
+ "location_file": "server.js",
+ "location_line": "135",
+ "locations": [
+ {"path": "server.js", "start_line": 135, "end_line": 137},
+ {"path": "app/views/layout.html", "start_line": 75, "end_line": None},
+ ],
+ },
+ {
+ "skill_id": "secret-scanning",
+ "severity": "Medium",
+ "secret_type": "Seeded passwords",
+ "location_file": "artifacts/db-reset.js",
+ "location_line": "18",
+ "locations": [
+ {"path": "artifacts/db-reset.js", "start_line": 18, "end_line": None},
+ {"path": "test/e2e/fixtures/users/*.json", "start_line": None, "end_line": None},
+ ],
+ },
+ ]
+ run = validate_sarif(findings_to_sarif(records))
+ assert run["results"][0]["locations"] == [
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": "server.js"},
+ "region": {"startLine": 135, "endLine": 137},
+ }
+ },
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": "app/views/layout.html"},
+ "region": {"startLine": 75},
+ }
+ },
+ ]
+ assert run["results"][1]["locations"] == [
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": "artifacts/db-reset.js"},
+ "region": {"startLine": 18},
+ }
+ },
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": "test/e2e/fixtures/users/%2A.json"},
+ }
+ },
+ ]
+
+
+def test_nodegoat_sample_sarif_validates_and_every_result_has_a_real_uri():
+ sample_dir = Path(__file__).parents[2] / "examples" / "sample-output" / "nodegoat"
+ sarif_doc = json.loads((sample_dir / "findings.sarif").read_text(encoding="utf-8"))
+ run = validate_sarif(sarif_doc)
+ assert len(run["results"]) == 18
+
+ for result in run["results"]:
+ assert result.get("locations"), f"missing locations on {result['ruleId']}"
+ for loc in result["locations"]:
+ physical = loc["physicalLocation"]
+ uri = physical["artifactLocation"]["uri"]
+ assert uri
+ assert "%3A" not in uri
+ assert "%2C" not in uri
+ assert "%3B" not in uri
+ assert "`" not in uri
+ assert "," not in uri
+ assert ";" not in uri
+
+ jsonl_records = [
+ json.loads(line)
+ for line in (sample_dir / "findings.jsonl").read_text(encoding="utf-8").splitlines()
+ if line.strip()
+ ]
+ assert len(jsonl_records) == 18
+ for record in jsonl_records:
+ assert record["locations"], f"missing locations in JSONL record {record['current_ref']}"
+ assert all(ch not in record["location_file"] for ch in (",", ";", "`", ":"))
+ rebuilt_run = validate_sarif(findings_to_sarif(jsonl_records))
+ assert [r["locations"] for r in rebuilt_run["results"]] == [r["locations"] for r in run["results"]]
diff --git a/tests/test_report/test_sast.py b/tests/test_report/test_sast.py
index 11bd2a9..b533520 100644
--- a/tests/test_report/test_sast.py
+++ b/tests/test_report/test_sast.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import pytest
+
from secfoo.report.sast import (
extract_description_by_id,
extract_findings_register_rows,
@@ -7,6 +9,7 @@
findings_with_fingerprints,
fingerprint_for_row,
parse_location,
+ parse_locations,
)
SAMPLE_REPORT = """\
@@ -134,16 +137,110 @@ def test_parse_location_handles_no_backticks():
def test_parse_location_strips_backticks_from_a_multi_location_cell():
- """A real finding can legitimately span more than one call site (e.g.
- a missing-auth finding citing both the app factory and the CLI flag
- that exposes it) -- the contract only anticipates one `file:line`, so
- this must degrade to the whole cell as one location string, not raise
- or silently drop part of it. Backticks (Markdown code-span syntax) are
- still stripped either way.
+ """A multi-site cell resolves to the primary site in `parse_location`
+ while `parse_locations` preserves every call site in order.
"""
file_path, line = parse_location("`web/app.py:35`, `cli.py:308`")
- assert file_path == "web/app.py:35, cli.py:308"
- assert line is None
+ assert file_path == "web/app.py"
+ assert line == "35"
+ assert parse_locations("`web/app.py:35`, `cli.py:308`") == [
+ ("web/app.py", 35, None),
+ ("cli.py", 308, None),
+ ]
+
+
+@pytest.mark.parametrize(
+ ("raw_location", "expected_sites", "expected_primary"),
+ [
+ (
+ "config/env/all.js:8-9",
+ [("config/env/all.js", 8, 9)],
+ ("config/env/all.js", "8"),
+ ),
+ (
+ "server.js:78-102, app/routes/session.js:116, …",
+ [("server.js", 78, 102), ("app/routes/session.js", 116, None)],
+ ("server.js", "78"),
+ ),
+ (
+ "app/data/user-dao.js:25, :61",
+ [("app/data/user-dao.js", 25, None), ("app/data/user-dao.js", 61, None)],
+ ("app/data/user-dao.js", "25"),
+ ),
+ (
+ "`server.js:135-137`, `app/views/layout.html:75`",
+ [("server.js", 135, 137), ("app/views/layout.html", 75, None)],
+ ("server.js", "135"),
+ ),
+ (
+ "`app/data/user-dao.js:25`, `:61`",
+ [("app/data/user-dao.js", 25, None), ("app/data/user-dao.js", 61, None)],
+ ("app/data/user-dao.js", "25"),
+ ),
+ (
+ "`artifacts/db-reset.js:18,27,35`; `test/e2e/fixtures/users/*.json`; `test/security/profile-test.js:37`",
+ [
+ ("artifacts/db-reset.js", 18, None),
+ ("artifacts/db-reset.js", 27, None),
+ ("artifacts/db-reset.js", 35, None),
+ ("test/e2e/fixtures/users/*.json", None, None),
+ ("test/security/profile-test.js", 37, None),
+ ],
+ ("artifacts/db-reset.js", "18"),
+ ),
+ (
+ "C:\\work\\app.js:10-20; /srv/app/db.py:42:7",
+ [("C:\\work\\app.js", 10, 20), ("/srv/app/db.py", 42, None)],
+ ("C:\\work\\app.js", "10"),
+ ),
+ (
+ "app/db.py:8-8, app/other.py:20-12",
+ [("app/db.py", 8, None), ("app/other.py", 12, 20)],
+ ("app/db.py", "8"),
+ ),
+ ],
+)
+def test_parse_locations_handles_ranges_lists_and_bare_continuations(
+ raw_location, expected_sites, expected_primary
+):
+ assert parse_locations(raw_location) == expected_sites
+ assert parse_location(raw_location) == expected_primary
+
+
+def test_fingerprint_and_code_region_match_between_line_and_line_range(tmp_path):
+ (tmp_path / "config" / "env").mkdir(parents=True)
+ source = "\n".join(f"const line{i} = {i};" for i in range(1, 30))
+ (tmp_path / "config" / "env" / "all.js").write_text(source, encoding="utf-8")
+
+ row_range = {"cwe": "CWE-798", "location": "`config/env/all.js:8-9`, `artifacts/db-reset.js:15-18`"}
+ row_single = {"cwe": "CWE-798", "location": "`config/env/all.js:8`"}
+ assert fingerprint_for_row(row_range) == fingerprint_for_row(row_single)
+
+ report_template = """\
+# SAST Report
+
+## 3. Findings Register
+| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict |
+|----|---------|----------|-----|-------|-------------|----------|---------|
+| F1 | Hardcoded secret | Medium | CWE-798 | A07:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N | {loc} | Confirmed |
+"""
+ r_range = findings_with_fingerprints(
+ report_template.format(loc="`config/env/all.js:8-9`, `artifacts/db-reset.js:15-18`"),
+ workdir=tmp_path,
+ )[0]
+ r_single = findings_with_fingerprints(
+ report_template.format(loc="`config/env/all.js:8`"),
+ workdir=tmp_path,
+ )[0]
+ assert r_range["location_file"] == "config/env/all.js"
+ assert r_range["location_line"] == "8"
+ assert r_range["locations"] == [
+ {"path": "config/env/all.js", "start_line": 8, "end_line": 9},
+ {"path": "artifacts/db-reset.js", "start_line": 15, "end_line": 18},
+ ]
+ assert r_range["code_region_hash"] is not None
+ assert r_range["code_region_hash"] == r_single["code_region_hash"]
+ assert r_range["fingerprint"] == r_single["fingerprint"]
def test_fingerprint_for_row_is_stable_for_identical_cwe_and_file_without_region_hash():
diff --git a/tests/test_report/test_structured_findings.py b/tests/test_report/test_structured_findings.py
index 143a196..c9c45cb 100644
--- a/tests/test_report/test_structured_findings.py
+++ b/tests/test_report/test_structured_findings.py
@@ -161,3 +161,32 @@ def test_secret_fingerprint_uses_the_code_region_when_the_repo_is_on_disk(tmp_pa
shifted = SECRET_REPORT.replace("ci.yml:14", "ci.yml:19").replace("ci.yml:90", "ci.yml:95")
after = {r["id"]: r for r in secret_scanning.findings_with_fingerprints(shifted, workdir=tmp_path)}
assert after["S1"]["fingerprint"] == with_repo["S1"]["fingerprint"]
+
+
+def test_secret_multi_site_and_range_locations_parse_and_fingerprint_on_first_path(tmp_path):
+ (tmp_path / "config" / "env").mkdir(parents=True)
+ (tmp_path / "config" / "env" / "development.js").write_text(
+ "\n".join(f"const x{i} = {i};" for i in range(1, 20)), encoding="utf-8"
+ )
+ multi_report = """\
+# Secret Scanning Report
+
+## 3. Findings Register
+| ID | Secret type | Location | Source | Validity | Severity |
+|----|-------------|----------|--------|----------|----------|
+| S1 | OWASP ZAP API key | `config/env/development.js:6-7`, `config/env/test.js:6` | config | Unclear | Medium |
+"""
+ single_report = multi_report.replace(
+ "`config/env/development.js:6-7`, `config/env/test.js:6`",
+ "`config/env/development.js:6`",
+ )
+ multi_row = secret_scanning.findings_with_fingerprints(multi_report, workdir=tmp_path)[0]
+ single_row = secret_scanning.findings_with_fingerprints(single_report, workdir=tmp_path)[0]
+ assert multi_row["location_file"] == "config/env/development.js"
+ assert multi_row["location_line"] == "6"
+ assert multi_row["locations"] == [
+ {"path": "config/env/development.js", "start_line": 6, "end_line": 7},
+ {"path": "config/env/test.js", "start_line": 6, "end_line": None},
+ ]
+ assert multi_row["code_region_hash"] is not None
+ assert multi_row["fingerprint"] == single_row["fingerprint"]
diff --git a/tests/test_storage/test_structured_findings_storage.py b/tests/test_storage/test_structured_findings_storage.py
index 9c6f661..2a61927 100644
--- a/tests/test_storage/test_structured_findings_storage.py
+++ b/tests/test_storage/test_structured_findings_storage.py
@@ -2,6 +2,9 @@
import sqlite3
+from secfoo.report.sast import fingerprint_for_row as sast_fp
+from secfoo.report.secret_scanning import fingerprint_for_row as sec_fp
+from secfoo.runner import update_sast_findings
from secfoo.storage.repository import RunRepository
@@ -43,10 +46,10 @@ def test_sca_finding_lifecycle_open_refresh_close(tmp_path):
def test_secret_finding_reopens_and_keeps_first_seen(tmp_path):
repo = RunRepository(db_path=tmp_path / "db.sqlite")
project_id, run_id = _project_and_run(repo)
- kwargs = dict(
- project_id=project_id, fingerprint="s1", run_id=run_id, current_ref="S1", secret_type="API token",
- location_file="deploy/ci.yml", severity="High", evidence="TOKENJ4F...",
- )
+ kwargs = {
+ "project_id": project_id, "fingerprint": "s1", "run_id": run_id, "current_ref": "S1", "secret_type": "API token",
+ "location_file": "deploy/ci.yml", "severity": "High", "evidence": "TOKENJ4F...",
+ }
repo.upsert_secret_finding(**kwargs)
first_seen = repo.list_secret_findings()[0].first_seen_at
repo.close_stale_findings(
@@ -98,12 +101,368 @@ def test_pre_existing_sast_table_gains_stack_columns(tmp_path):
repo = RunRepository(db_path=db_path)
columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(sast_findings)")}
+ secret_columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(secret_findings)")}
run_columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(runs)")}
repo.close()
- assert {"language", "framework", "construct", "code_region_hash"} <= columns
+ assert {"language", "framework", "construct", "code_region_hash", "locations"} <= columns
+ assert "locations" in secret_columns
assert "memory_enabled" in run_columns
+def test_migration_re_derives_locations_for_existing_sast_and_secret_rows(tmp_path):
+ db_path = tmp_path / "legacy.sqlite"
+ conn = sqlite3.connect(db_path)
+ conn.executescript(
+ """
+ CREATE TABLE projects (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ identifier TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_run_at TEXT NOT NULL
+ );
+ CREATE TABLE runs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ run_uuid TEXT NOT NULL UNIQUE,
+ project_id INTEGER NOT NULL,
+ skill_id TEXT NOT NULL,
+ skill_name TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ confluence_urls TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL,
+ exit_code INTEGER,
+ started_at TEXT NOT NULL,
+ finished_at TEXT,
+ duration_seconds REAL,
+ report_path TEXT,
+ prompt_path TEXT,
+ stderr_excerpt TEXT
+ );
+ CREATE TABLE sast_findings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id INTEGER NOT NULL,
+ fingerprint TEXT NOT NULL,
+ current_ref TEXT NOT NULL,
+ title TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ cwe TEXT,
+ owasp TEXT,
+ verdict TEXT,
+ location_file TEXT NOT NULL,
+ location_line TEXT,
+ code_region_hash TEXT,
+ language TEXT,
+ framework TEXT,
+ construct TEXT,
+ cvss_vector TEXT,
+ cvss_score REAL,
+ description TEXT,
+ recommendation TEXT,
+ status TEXT NOT NULL,
+ first_seen_run_id INTEGER NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_seen_run_id INTEGER NOT NULL,
+ last_seen_at TEXT NOT NULL,
+ closed_in_run_id INTEGER,
+ closed_at TEXT,
+ UNIQUE (project_id, fingerprint)
+ );
+ CREATE TABLE secret_findings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id INTEGER NOT NULL,
+ fingerprint TEXT NOT NULL,
+ current_ref TEXT NOT NULL,
+ secret_type TEXT NOT NULL,
+ location_file TEXT NOT NULL,
+ location_line TEXT,
+ code_region_hash TEXT,
+ source TEXT,
+ validity TEXT,
+ severity TEXT NOT NULL,
+ evidence TEXT,
+ exposure TEXT,
+ remediation TEXT,
+ language TEXT,
+ framework TEXT,
+ construct TEXT,
+ status TEXT NOT NULL,
+ first_seen_run_id INTEGER NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_seen_run_id INTEGER NOT NULL,
+ last_seen_at TEXT NOT NULL,
+ closed_in_run_id INTEGER,
+ closed_at TEXT,
+ UNIQUE (project_id, fingerprint)
+ );
+ INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z');
+ INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at)
+ VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z');
+ INSERT INTO sast_findings (
+ project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line,
+ status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at
+ ) VALUES
+ (1, 'fp-f7', 'F7', 'Plaintext passwords', 'Medium', 'CWE-256',
+ 'app/data/user-dao.js:25, :61', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'),
+ (1, 'fp-f6', 'F6', 'Autoescape off', 'High', 'CWE-79',
+ 'server.js:135-137, app/views/layout.html:75', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z'),
+ (1, 'fp-single', 'F1', 'SQLi', 'High', 'CWE-89',
+ 'app/db.py', '42', 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z');
+ INSERT INTO secret_findings (
+ project_id, fingerprint, current_ref, secret_type, location_file, location_line,
+ source, validity, severity, status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at
+ ) VALUES
+ (1, 'fp-s5', 'S5', 'Seeded passwords',
+ 'artifacts/db-reset.js:18,27,35; test/e2e/fixtures/users/*.json; test/security/profile-test.js:37',
+ NULL, 'code', 'Looks live', 'Medium', 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z');
+ """
+ )
+ conn.close()
+
+ with RunRepository(db_path=db_path) as repo:
+ sast_by_ref = {r.current_ref: r for r in repo.list_sast_findings()}
+ secret_by_ref = {r.current_ref: r for r in repo.list_secret_findings()}
+ exported = {(skill, row["current_ref"]): row for skill, row in repo.list_structured_findings()}
+
+ assert sast_by_ref["F7"].location_file == "app/data/user-dao.js"
+ assert sast_by_ref["F7"].location_line == "25"
+ assert sast_by_ref["F7"].locations == [
+ {"path": "app/data/user-dao.js", "start_line": 25, "end_line": None},
+ {"path": "app/data/user-dao.js", "start_line": 61, "end_line": None},
+ ]
+ assert sast_by_ref["F6"].location_file == "server.js"
+ assert sast_by_ref["F6"].location_line == "135"
+ assert sast_by_ref["F6"].locations == [
+ {"path": "server.js", "start_line": 135, "end_line": 137},
+ {"path": "app/views/layout.html", "start_line": 75, "end_line": None},
+ ]
+ assert sast_by_ref["F1"].location_file == "app/db.py"
+ assert sast_by_ref["F1"].location_line == "42"
+ assert sast_by_ref["F1"].locations == [
+ {"path": "app/db.py", "start_line": 42, "end_line": None},
+ ]
+ assert secret_by_ref["S5"].location_file == "artifacts/db-reset.js"
+ assert secret_by_ref["S5"].location_line == "18"
+ assert secret_by_ref["S5"].locations == [
+ {"path": "artifacts/db-reset.js", "start_line": 18, "end_line": None},
+ {"path": "artifacts/db-reset.js", "start_line": 27, "end_line": None},
+ {"path": "artifacts/db-reset.js", "start_line": 35, "end_line": None},
+ {"path": "test/e2e/fixtures/users/*.json", "start_line": None, "end_line": None},
+ {"path": "test/security/profile-test.js", "start_line": 37, "end_line": None},
+ ]
+ assert isinstance(exported[("sast", "F6")]["locations"], list)
+ assert isinstance(exported[("secret-scanning", "S5")]["locations"], list)
+ assert sast_by_ref["F7"].fingerprint == sast_fp({"cwe": "CWE-256", "location": "app/data/user-dao.js:25, :61"})
+ assert sast_by_ref["F6"].fingerprint == sast_fp({"cwe": "CWE-79", "location": "server.js:135-137, app/views/layout.html:75"})
+ assert secret_by_ref["S5"].fingerprint == sec_fp({"secret_type": "Seeded passwords"}, file_path="artifacts/db-reset.js")
+
+
+def test_migration_collapses_duplicate_findings_preserving_review(tmp_path):
+ db_path = tmp_path / "legacy.sqlite"
+ conn = sqlite3.connect(db_path)
+ conn.executescript(
+ """
+ CREATE TABLE projects (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ identifier TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_run_at TEXT NOT NULL
+ );
+ CREATE TABLE runs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ run_uuid TEXT NOT NULL UNIQUE,
+ project_id INTEGER NOT NULL,
+ skill_id TEXT NOT NULL,
+ skill_name TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ confluence_urls TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL,
+ exit_code INTEGER,
+ started_at TEXT NOT NULL,
+ finished_at TEXT,
+ duration_seconds REAL,
+ report_path TEXT,
+ prompt_path TEXT,
+ stderr_excerpt TEXT
+ );
+ CREATE TABLE sast_findings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id INTEGER NOT NULL,
+ fingerprint TEXT NOT NULL,
+ current_ref TEXT NOT NULL,
+ title TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ cwe TEXT,
+ owasp TEXT,
+ verdict TEXT,
+ location_file TEXT NOT NULL,
+ location_line TEXT,
+ code_region_hash TEXT,
+ language TEXT,
+ framework TEXT,
+ construct TEXT,
+ cvss_vector TEXT,
+ cvss_score REAL,
+ description TEXT,
+ recommendation TEXT,
+ status TEXT NOT NULL,
+ first_seen_run_id INTEGER NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_seen_run_id INTEGER NOT NULL,
+ last_seen_at TEXT NOT NULL,
+ closed_in_run_id INTEGER,
+ closed_at TEXT,
+ review_status TEXT,
+ review_note TEXT,
+ reviewed_by TEXT,
+ reviewed_at TEXT,
+ UNIQUE (project_id, fingerprint)
+ );
+ INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z');
+ INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at)
+ VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z');
+ INSERT INTO sast_findings (
+ project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line,
+ status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at,
+ review_status, review_note, reviewed_by, reviewed_at
+ ) VALUES
+ (1, 'old-fp-1', 'F1', 'Missing HttpOnly', 'Medium', 'CWE-1004',
+ 'server.js:78-102', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z',
+ NULL, NULL, NULL, NULL),
+ (1, 'old-fp-2', 'F2', 'Missing HttpOnly cookie flag', 'Medium', 'CWE-1004',
+ 'server.js:104-113', NULL, 'open', 1, '2026-11-14T01:00:00Z', 1, '2026-11-14T01:00:00Z',
+ 'confirmed', 'Cookie flag verified missing', 'secops', '2026-11-15T10:00:00Z');
+ """
+ )
+ conn.close()
+
+ with RunRepository(db_path=db_path) as repo:
+ open_findings = repo.list_sast_findings(status="open")
+ closed_findings = repo.list_sast_findings(status="closed")
+
+ assert len(open_findings) == 1
+ assert open_findings[0].review_status == "confirmed"
+ assert open_findings[0].review_note == "Cookie flag verified missing"
+ assert open_findings[0].reviewed_by == "secops"
+ assert open_findings[0].reviewed_at == "2026-11-15T10:00:00Z"
+ assert open_findings[0].location_file == "server.js"
+ assert open_findings[0].locations == [{"path": "server.js", "start_line": 104, "end_line": 113}]
+
+ assert len(closed_findings) == 1
+ assert ":merged:" in closed_findings[0].fingerprint
+ assert closed_findings[0].status == "closed"
+
+
+def test_migration_rescan_causes_no_churn(tmp_path):
+ db_path = tmp_path / "rescan.sqlite"
+ conn = sqlite3.connect(db_path)
+ conn.executescript(
+ """
+ CREATE TABLE projects (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ identifier TEXT NOT NULL UNIQUE,
+ display_name TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_run_at TEXT NOT NULL
+ );
+ CREATE TABLE runs (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ run_uuid TEXT NOT NULL UNIQUE,
+ project_id INTEGER NOT NULL,
+ skill_id TEXT NOT NULL,
+ skill_name TEXT NOT NULL,
+ agent_id TEXT NOT NULL,
+ confluence_urls TEXT NOT NULL DEFAULT '[]',
+ status TEXT NOT NULL,
+ exit_code INTEGER,
+ started_at TEXT NOT NULL,
+ finished_at TEXT,
+ duration_seconds REAL,
+ report_path TEXT,
+ prompt_path TEXT,
+ stderr_excerpt TEXT
+ );
+ CREATE TABLE sast_findings (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ project_id INTEGER NOT NULL,
+ fingerprint TEXT NOT NULL,
+ current_ref TEXT NOT NULL,
+ title TEXT NOT NULL,
+ severity TEXT NOT NULL,
+ cwe TEXT,
+ owasp TEXT,
+ verdict TEXT,
+ location_file TEXT NOT NULL,
+ location_line TEXT,
+ code_region_hash TEXT,
+ language TEXT,
+ framework TEXT,
+ construct TEXT,
+ cvss_vector TEXT,
+ cvss_score REAL,
+ description TEXT,
+ recommendation TEXT,
+ status TEXT NOT NULL,
+ first_seen_run_id INTEGER NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_seen_run_id INTEGER NOT NULL,
+ last_seen_at TEXT NOT NULL,
+ closed_in_run_id INTEGER,
+ closed_at TEXT,
+ review_status TEXT,
+ review_note TEXT,
+ reviewed_by TEXT,
+ reviewed_at TEXT,
+ UNIQUE (project_id, fingerprint)
+ );
+ INSERT INTO projects VALUES (1, '/tmp/nodegoat', 'NodeGoat', 'local', '2026-11-14T00:00:00Z', '2026-11-14T00:00:00Z');
+ INSERT INTO runs (id, run_uuid, project_id, skill_id, skill_name, agent_id, status, started_at)
+ VALUES (1, 'run-1', 1, 'sast', 'SAST', 'claude', 'success', '2026-11-14T00:00:00Z');
+ INSERT INTO sast_findings (
+ project_id, fingerprint, current_ref, title, severity, cwe, location_file, location_line,
+ status, first_seen_run_id, first_seen_at, last_seen_run_id, last_seen_at,
+ review_status, review_note, reviewed_by, reviewed_at
+ ) VALUES
+ (1, 'old-fp-1', 'F1', 'Missing HttpOnly', 'Medium', 'CWE-1004',
+ 'server.js:78-102', NULL, 'open', 1, '2026-11-14T00:00:00Z', 1, '2026-11-14T00:00:00Z',
+ 'confirmed', 'Reviewed and accepted', 'secops', '2026-11-15T10:00:00Z');
+ """
+ )
+ conn.close()
+
+ # Step 1: Migration runs automatically when RunRepository opens
+ with RunRepository(db_path=db_path) as repo:
+ migrated = repo.list_sast_findings(status="open")
+ assert len(migrated) == 1
+ assert migrated[0].review_status == "confirmed"
+
+ # Step 2: Next run scans the project and finds the vulnerability with new range/multi-site format
+ run_uuid = repo.create_run(
+ project_id=1, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]
+ )
+ run_id = repo.get_run(run_uuid).id
+ report_text = """# SAST Report
+## Findings Register
+| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict |
+|----|---------|----------|-----|-------|-------------|----------|---------|
+| F1 | Missing HttpOnly cookie flag | Medium | CWE-1004 | A05:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N | `server.js:78-102, :104-113` | Confirmed |
+"""
+ update_sast_findings(repo, project_id=1, run_id=run_id, report_text=report_text)
+
+ after_scan_open = repo.list_sast_findings(status="open")
+ after_scan_closed = repo.list_sast_findings(status="closed")
+
+ assert len(after_scan_open) == 1
+ assert len(after_scan_closed) == 0
+ assert after_scan_open[0].review_status == "confirmed"
+ assert after_scan_open[0].review_note == "Reviewed and accepted"
+ assert after_scan_open[0].reviewed_by == "secops"
+ assert after_scan_open[0].last_seen_run_id == run_id
+
+
def test_complete_run_records_memory_flag(tmp_path):
repo = RunRepository(db_path=tmp_path / "db.sqlite")
project_id = repo.upsert_project(identifier="/tmp/x", display_name="x", kind="local")
@@ -112,8 +471,10 @@ def test_complete_run_records_memory_flag(tmp_path):
untouched = repo.create_run(
project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[]
)
- common = dict(status="success", exit_code=0, duration_seconds=1.0, report_path=None, prompt_path=None,
- stderr_excerpt=None)
+ common = {
+ "status": "success", "exit_code": 0, "duration_seconds": 1.0, "report_path": None, "prompt_path": None,
+ "stderr_excerpt": None,
+ }
repo.complete_run(on, memory_enabled=True, **common)
repo.complete_run(off, memory_enabled=False, **common)
repo.complete_run(untouched, **common)
diff --git a/tests/test_web/test_sast_finding_route.py b/tests/test_web/test_sast_finding_route.py
index a5c10b1..a00aacc 100644
--- a/tests/test_web/test_sast_finding_route.py
+++ b/tests/test_web/test_sast_finding_route.py
@@ -154,6 +154,27 @@ def test_sast_finding_detail_renders_for_a_real_finding(client):
assert "AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N" in resp.text
+def test_sast_finding_detail_renders_every_site_and_secondary_file_is_searchable(client):
+ _, fingerprint = _seed_finding(
+ fingerprint="fp-multi",
+ title="Global template autoescape disabled",
+ location_file="server.js",
+ location_line="135",
+ locations=[
+ {"path": "server.js", "start_line": 135, "end_line": 137},
+ {"path": "app/views/layout.html", "start_line": 75, "end_line": None},
+ ],
+ )
+ detail = client.get(f"/activities/sast/findings/{fingerprint}")
+ assert detail.status_code == 200
+ assert "server.js:135-137" in detail.text
+ assert "app/views/layout.html:75" in detail.text
+
+ search_resp = client.get("/activities/sast/findings?q=layout.html")
+ assert search_resp.status_code == 200
+ assert "Global template autoescape disabled" in search_resp.text
+
+
def test_sast_finding_detail_404s_for_unknown_fingerprint(client):
resp = client.get("/activities/sast/findings/does-not-exist")
assert resp.status_code == 404
diff --git a/tests/test_web/test_secret_scanning_route.py b/tests/test_web/test_secret_scanning_route.py
index de46951..06b0853 100644
--- a/tests/test_web/test_secret_scanning_route.py
+++ b/tests/test_web/test_secret_scanning_route.py
@@ -138,6 +138,38 @@ def test_secret_scanning_finding_detail_404s_for_unknown_key(client, tmp_path):
assert resp.status_code == 404
+def test_secret_scanning_finding_detail_renders_every_site(client, tmp_path):
+ multi_site_report = """\
+# Secret Scanning Report
+
+## 3. Findings Register
+| ID | Secret type | Location | Source | Validity | Severity |
+|----|-------------|----------|--------|----------|----------|
+| S1 | Seeded passwords | `artifacts/db-reset.js:18,27,35`; `test/e2e/fixtures/users/*.json`; `test/security/profile-test.js:37` | code | Looks live | Medium |
+
+## 4. Detailed Findings
+
+### [MEDIUM] S1: Seeded passwords
+- **Evidence:** Admin_12...
+- **Remediation:** Rotate seeded credentials.
+"""
+ _seed(tmp_path, report_text=multi_site_report)
+ dashboard_resp = client.get("/activities/secret-scanning")
+ match = re.search(r"/activities/secret-scanning/findings/([0-9a-f]+)", dashboard_resp.text)
+ assert match, dashboard_resp.text
+
+ resp = client.get(f"/activities/secret-scanning/findings/{match.group(1)}")
+ assert resp.status_code == 200
+ for expected in (
+ "artifacts/db-reset.js:18",
+ "artifacts/db-reset.js:27",
+ "artifacts/db-reset.js:35",
+ "test/e2e/fixtures/users/*.json",
+ "test/security/profile-test.js:37",
+ ):
+ assert expected in resp.text
+
+
def test_secret_scanning_findings_list_filters_by_severity(client, tmp_path):
_seed(tmp_path) # one High finding
|