diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index dd80e68..69d831f 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -300,6 +300,15 @@ records: code-free description of the vulnerable construct ("YAML loader without a safe loader applied to an uploaded config file"). Because it has no paths or identifiers, findings can be compared across repos. +- **`locations`** (SAST and secret scanning): every site the report's + Location cell names, as a list of `{"path", "start_line", "end_line"}`. + The cell may hold `path:line`, `path:start-end`, `path:line,line`, + backticked sites and comma- or semicolon-separated lists; a bare `:61` + reuses the previous path. `location_file`/`location_line` and the + fingerprint use the first site, so `all.js:8-9` one run and `all.js:8` + the next stay the same finding. Rows stored before this column existed + are re-derived when the store is opened, and open rows keyed on the + whole cell are rekeyed on the next run that reports them. | Skill | Identity (fingerprint) | |---|---| @@ -323,8 +332,11 @@ Use `--format sarif` to write a SARIF 2.1.0 document instead of JSON Lines `--no-locations` options apply to both formats. Export one project at a time when uploading to code scanning so paths belong to the checked-out repository. Relative paths should be relative to that repository; absolute paths are emitted -as `file:` URIs. Missing files or invalid line numbers omit the corresponding -location or region rather than inventing one. +as `file:` URIs. A finding with several sites gets one SARIF `locations[]` +entry per site, with `region.endLine` when the report gave a range; JSON +Lines records carry the same list as `locations`. Missing files or invalid +line numbers omit the corresponding location or region rather than +inventing one. ```bash secfoo findings export --format sarif --project 1 -o findings.sarif diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index b9b4011..fd0eb49 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -1861,7 +1861,21 @@ class FindingsFormat(str, Enum): # Lifecycle bookkeeping that means nothing outside this one SQLite file. _EXPORT_DROP_COLUMNS = {"id", "project_id", "first_seen_run_id", "last_seen_run_id", "closed_in_run_id"} -_EXPORT_LOCATION_COLUMNS = {"location_file", "location_line", "code_region_hash", "reachability_evidence"} +_EXPORT_LOCATION_COLUMNS = { + "location_file", "location_line", "locations", "code_region_hash", "reachability_evidence", +} + + +def _decoded_locations(value: object) -> list | None: + """The stored `locations` JSON (#112) as a list, so JSONL carries a real + array rather than a string; None when absent or unreadable.""" + if not isinstance(value, str) or not value: + return None + try: + sites = json.loads(value) + except ValueError: + return None + return sites if isinstance(sites, list) else None @findings_app.command(name="export") @@ -1905,6 +1919,8 @@ def findings_export( for column, value in row.items(): if column in _EXPORT_DROP_COLUMNS or (no_locations and column in _EXPORT_LOCATION_COLUMNS): continue + if column == "locations": + value = _decoded_locations(value) record[column] = value if skill_id == "sca-reachability" and not no_runtime: record["runtime"] = runtime.as_sarif() diff --git a/src/secfoo/report/sarif.py b/src/secfoo/report/sarif.py index f6dbdf8..0629c98 100644 --- a/src/secfoo/report/sarif.py +++ b/src/secfoo/report/sarif.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import re from pathlib import PureWindowsPath from urllib.parse import quote @@ -20,27 +21,69 @@ } -def _location(record: dict) -> dict | None: - path = str(record.get("location_file") or "").strip().replace("\\", "/") - if not path: - return None +def _uri(path: str) -> str: if PureWindowsPath(path).is_absolute(): - uri = PureWindowsPath(path).as_uri() - elif path.startswith("/"): - uri = "file://" + quote(path, safe="/") - else: - uri = quote(path, safe="/") - physical = {"artifactLocation": {"uri": uri}} + return PureWindowsPath(path).as_uri() + if path.startswith("/"): + return "file://" + quote(path, safe="/") + return quote(path, safe="/") + + +def _line(value: object) -> int | None: # Stored legacy/model-authored lines are not guaranteed to be numeric -- # or short: int() refuses more than 4300 digits (#121), and no source # file has a billion lines. - line = str(record.get("location_line") or "").strip() + line = str(value or "").strip() digits = line.lstrip("0") # "0000000042" is line 42; the length cap is on the value if re.fullmatch(r"[0-9]+", line) and 1 <= len(digits) <= 9: - physical["region"] = {"startLine": int(digits)} + return int(digits) + return None + + +def _physical(path: object, start: object, end: object = None) -> dict | None: + path = str(path or "").strip().replace("\\", "/") + if not path: + return None + physical: dict = {"artifactLocation": {"uri": _uri(path)}} + start_line = _line(start) + if start_line is not None: + physical["region"] = {"startLine": start_line} + end_line = _line(end) + if end_line is not None and end_line > start_line: + physical["region"]["endLine"] = end_line return {"physicalLocation": physical} +def _location(record: dict) -> dict | None: + return _physical(record.get("location_file"), record.get("location_line")) + + +def _sites(record: dict) -> list: + sites = record.get("locations") + if isinstance(sites, str): + try: + sites = json.loads(sites) + except ValueError: + return [] + return sites if isinstance(sites, list) else [] + + +def _locations(record: dict) -> list[dict]: + """One SARIF location per site of the finding (#112): the record's + `locations` list when it has one, else its location_file/location_line.""" + locations = [] + for site in _sites(record): + if isinstance(site, dict): + location = _physical(site.get("path"), site.get("start_line"), site.get("end_line")) + if location is not None and location not in locations: + locations.append(location) + if not locations: + location = _location(record) + if location is not None: + locations.append(location) + return locations + + def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> dict: """Build one run; group rules by skill, CWE and severity. @@ -91,9 +134,9 @@ def findings_to_sarif(records: list[dict], *, runtime_priority: bool = False) -> } if runtime: result["properties"] = {"secfoo": {"runtime": runtime}} - location = _location(record) - if location is not None: - result["locations"] = [location] + locations = _locations(record) + if locations: + result["locations"] = locations results.append(result) return { "$schema": SCHEMA_URI, diff --git a/src/secfoo/report/sast.py b/src/secfoo/report/sast.py index c68e36d..941bdfc 100644 --- a/src/secfoo/report/sast.py +++ b/src/secfoo/report/sast.py @@ -35,8 +35,10 @@ from __future__ import annotations import hashlib +import json import re from pathlib import Path +from typing import NamedTuple from secfoo.report.code_region import hash_code_region from secfoo.report.markdown import detail_blocks, example_finding_ids, prose_source @@ -65,9 +67,44 @@ # contract field. _CONSTRUCT_FIELD_RE = re.compile(r"\*\*Construct:\*\*\s*([^\n]+)") -# "`app/db.py:42`" -> ("app/db.py", "42"); the line group is optional since -# a location without one ("`app/db.py`") should still parse. -_LOCATION_RE = re.compile(r"`?(?P[^:`]+?)(?::(?P\d+))?`?\s*$") +# One site's trailing ":42", ":42-48" (hyphen or en/em dash) or ":42:7" +# (a column, ignored). Peeled off the end of a site repeatedly, so the +# leftmost number left over is the start line and the path never keeps a +# trailing ":range". +_LINE_TAIL_RE = re.compile(r"\s*:\s*(?P\d+)(?:\s*[-\u2013\u2014]\s*(?P\d+))?\s*$") +# A site that is only a line or range ("61", ":61", "61-70"), which reuses +# the previous site's path: "`app/data/user-dao.js:25, :61`". +_BARE_LINES_RE = re.compile(r":?\s*(?P\d+)(?:\s*[-\u2013\u2014]\s*(?P\d+))?") +# The single-site pattern used before #112, kept only to recompute the +# identity rows stored under it had (pre_112_fingerprint). +_PRE_112_LOCATION_RE = re.compile(r"`?(?P[^:`]+?)(?::(?P\d+))?`?\s*$") +# Sites are separated by commas or semicolons; a path never contains one. +_SITE_SEPARATOR_RE = re.compile(r"[,;]") + + +class SourceLocation(NamedTuple): + """One site of a finding: a path and an optional line range. Lines stay + strings, as in the location_line column; end_line is set only for a + real range (start < end).""" + + path: str + start_line: str | None = None + end_line: str | None = None + + def as_dict(self) -> dict[str, str | None]: + return {"path": self.path, "start_line": self.start_line, "end_line": self.end_line} + + +def _line_range(start: str | None, end: str | None) -> tuple[str | None, str | None]: + if start is None: + return None, None + start = start.lstrip("0") or "0" + end = end.lstrip("0") or "0" if end is not None else None + # A reversed or one-line range is just its start line. Compared as + # (length, text) since int() refuses very long digit strings (#121). + if end is None or (len(end), end) <= (len(start), start): + return start, None + return start, end def extract_findings_register_rows(report_markdown: str) -> list[dict[str, str]]: @@ -127,20 +164,86 @@ def extract_construct_by_id(report_markdown: str) -> dict[str, str]: return result +def parse_locations(location: str) -> list[SourceLocation]: + """Every site in a register Location cell, in order (#112). + + "`server.js:78-102`, `app/routes/session.js:116`" -> + [("server.js", "78", "102"), ("app/routes/session.js", "116", None)]. + Understands `path`, `path:line`, `path:start-end`, `path:line:col`, + backticked sites, and comma- or semicolon-separated lists; a site that + is only a line (":61", "61") reuses the previous site's path. Pieces + with no letter or digit (a trailing "…") are dropped. A cell with no + site at all yields []. + """ + sites: list[SourceLocation] = [] + for piece in _SITE_SEPARATOR_RE.split(location.replace("`", "")): + piece = piece.strip() + if not any(ch.isalnum() for ch in piece): + continue + bare = _BARE_LINES_RE.fullmatch(piece) + if bare: + if sites: + start, end = _line_range(bare.group("start"), bare.group("end")) + sites.append(SourceLocation(sites[-1].path, start, end)) + continue + path, start, end = piece, None, None + while match := _LINE_TAIL_RE.search(path): + start, end = match.group("start"), match.group("end") + path = path[: match.start()] + path = path.strip() + if not path: + continue + start, end = _line_range(start, end) + sites.append(SourceLocation(path, start, end)) + return sites + + def parse_location(location: str) -> tuple[str, str | None]: - """"`app/db.py:42`" -> ("app/db.py", "42"); a location with no line - number, or text that doesn't cleanly split into a single file:line - (e.g. a finding spanning several call sites, like - "`app.py:35`, `cli.py:308`"), degrades to (location_stripped, None) - rather than raising or silently dropping part of it -- backticks are - stripped either way since they're Markdown code-span syntax, never - part of a real path. + """The first site of a Location cell as (path, start_line): + "`app/db.py:42`" -> ("app/db.py", "42"), and + "`config/env/all.js:8-9`, `db-reset.js:15`" -> ("config/env/all.js", "8"). + This is what location_file/location_line and the fingerprint use; the + full list is parse_locations(). A cell with no parsable site degrades + to (text without backticks, None) rather than raising. """ + sites = parse_locations(location) + if not sites: + return location.strip().replace("`", ""), None + return sites[0].path, sites[0].start_line + + +def locations_json(location: str) -> str: + """parse_locations() as the JSON list stored in the `locations` column + ("[]" when the cell has no site; NULL in that column means a row stored + before #112 that the migration has not re-derived yet).""" + return json.dumps([site.as_dict() for site in parse_locations(location)]) + + +def pre_112_path(location: str) -> str | None: + """The path the pre-#112 parser stored for this cell, or None when it + is the same path parse_location() gives today. That parser could still + "match" a list: "app/db.py, app/cli.py" became one file named + "app/db.py, app/cli.py", so a regex match alone does not mean the + identity is unchanged.""" stripped = location.strip() - match = _LOCATION_RE.match(stripped) - if not match: - return stripped.replace("`", ""), None - return match.group("file").strip(), match.group("line") + match = _PRE_112_LOCATION_RE.match(stripped) + old_path = match.group("file").strip() if match else stripped.replace("`", "") + if _normalize_path(old_path) == _normalize_path(parse_location(location)[0]): + return None + return old_path + + +def pre_112_fingerprint(row: dict[str, str]) -> str | None: + """The fingerprint a multi-site or ranged location got before #112, + when the old parser took (most of) the cell as the path -- a path that + never exists, so no region hash was ever added. runner.py rekeys an + open row from it so an upgrade does not show those findings as closed + + new. None when the old parser read the same path as today.""" + old_path = pre_112_path(row["location"]) + if old_path is None: + return None + raw = "|".join([SKILL_ID, row.get("cwe", "").strip().lower(), _normalize_path(old_path)]) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() def _normalize_path(file_path: str) -> str: @@ -218,9 +321,11 @@ def findings_with_fingerprints( **row, "location_file": file_path, "location_line": line, + "locations": locations_json(row["location"]), "code_region_hash": region_hash, "fingerprint": fingerprint, "legacy_fingerprint": legacy_fingerprint, + "pre_112_fingerprint": pre_112_fingerprint(row), "description": descriptions.get(row["id"], ""), "recommendation": recommendations.get(row["id"], ""), "construct": constructs.get(row["id"], ""), diff --git a/src/secfoo/report/secret_scanning.py b/src/secfoo/report/secret_scanning.py index 71edecb..140ad87 100644 --- a/src/secfoo/report/secret_scanning.py +++ b/src/secfoo/report/secret_scanning.py @@ -15,7 +15,12 @@ from secfoo.report.code_region import hash_code_region from secfoo.report.markdown import detail_blocks, example_finding_ids, prose_source from secfoo.report.markdown import section as _extract_section -from secfoo.report.sast import _normalize_path, parse_location +from secfoo.report.sast import ( + _normalize_path, + locations_json, + parse_location, + pre_112_path, +) SKILL_ID = "secret-scanning" @@ -159,6 +164,15 @@ def fingerprint_for_row( return hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest() +def pre_112_fingerprint(row: dict[str, str]) -> str | None: + """report/sast.py's pre_112_fingerprint for this skill: the identity a + multi-site or ranged location had when the whole cell was the path.""" + old_path = pre_112_path(row["location"]) + if old_path is None: + return None + return fingerprint_for_row(row, file_path=old_path) + + def findings_with_fingerprints( report_markdown: str, *, workdir: Path | None = None ) -> list[dict[str, str | None]]: @@ -188,11 +202,13 @@ def findings_with_fingerprints( "evidence": redact_evidence(row.get("evidence")), "location_file": file_path, "location_line": line, + "locations": locations_json(row["location"]), "code_region_hash": region_hash, "construct": constructs.get(row["id"], ""), "fingerprint": fingerprint_for_row( row, file_path=file_path, region_hash=region_hash, line_bucket=line_bucket ), + "pre_112_fingerprint": pre_112_fingerprint(row), } ) return results diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index d6051e0..6fe8f04 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -221,13 +221,15 @@ def update_sast_findings( 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"], - ) + # legacy: stored before region hashes; pre-#112: a ranged or + # multi-site cell whose whole text was taken as the path. + for old_fp in (row.get("legacy_fingerprint"), row.get("pre_112_fingerprint")): + if old_fp and old_fp != row["fingerprint"]: + repo.rekey_open_sast_fingerprint( + project_id=project_id, + old_fingerprint=old_fp, + new_fingerprint=row["fingerprint"], + ) vector = row.get("cvss_vector", "").strip() score = None if vector: @@ -249,6 +251,7 @@ def update_sast_findings( verdict=row.get("verdict") or None, location_file=row["location_file"], location_line=row.get("location_line"), + locations=row.get("locations"), code_region_hash=row.get("code_region_hash"), cvss_vector=vector or None, cvss_score=score, @@ -325,6 +328,11 @@ def update_secret_findings( """update_sast_findings' lifecycle for the Secret Scanning register.""" seen_fingerprints = [] for row in secret_report.findings_with_fingerprints(report_text, workdir=workdir): + old_fp = row.get("pre_112_fingerprint") + if old_fp and old_fp != row["fingerprint"]: + repo.rekey_open_secret_fingerprint( + project_id=project_id, old_fingerprint=old_fp, new_fingerprint=row["fingerprint"] + ) repo.upsert_secret_finding( project_id=project_id, fingerprint=row["fingerprint"], @@ -333,6 +341,7 @@ def update_secret_findings( secret_type=row["secret_type"], location_file=row["location_file"], location_line=row.get("location_line"), + locations=row.get("locations"), code_region_hash=row.get("code_region_hash"), source=row.get("source") or None, validity=row.get("validity") or None, diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index c33510c..f9fb016 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -1,5 +1,6 @@ from __future__ import annotations +import json from dataclasses import dataclass @@ -184,8 +185,14 @@ class SastFindingRecord: review_note: str | None = None reviewed_by: str | None = None reviewed_at: str | None = None + locations: str | None = None project_display_name: str | None = None + def sites(self) -> list[dict]: + """Every site of this finding (#112): the `locations` JSON, or the + single location_file/location_line for a row that has none.""" + return _sites(self.locations, self.location_file, self.location_line) + @dataclass(frozen=True) class ScaFindingRecord: @@ -242,6 +249,7 @@ class SecretFindingRecord: last_seen_at: str closed_in_run_id: int | None closed_at: str | None + locations: str | None = None project_display_name: str | None = None @@ -255,3 +263,13 @@ class CostRow: output_tokens: int | None cost_usd: float | None unpriced_runs: int + + +def _sites(locations: str | None, location_file: str, location_line: str | None) -> list[dict]: + try: + sites = json.loads(locations) if locations else [] + except ValueError: + sites = [] + if not isinstance(sites, list) or not sites: + return [{"path": location_file, "start_line": location_line, "end_line": None}] + return [site for site in sites if isinstance(site, dict) and site.get("path")] diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 6817c8d..4059263 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -38,6 +38,7 @@ def use_db_path(path: Path): yield finally: _default_db_path.reset(token) +from secfoo.report.sast import locations_json, parse_locations from secfoo.report.severity import SeverityCounts, extract_overall_risk_rating from secfoo.storage.models import ( AssessmentRecord, @@ -106,6 +107,13 @@ def use_db_path(path: Path): "review_note": "ALTER TABLE sast_findings ADD COLUMN review_note TEXT", "reviewed_by": "ALTER TABLE sast_findings ADD COLUMN reviewed_by TEXT", "reviewed_at": "ALTER TABLE sast_findings ADD COLUMN reviewed_at TEXT", + # #112: every site of a multi-location finding; back-filled from + # location_file/location_line by _backfill_locations. + "locations": "ALTER TABLE sast_findings ADD COLUMN locations TEXT", +} + +_SECRET_FINDINGS_MIGRATIONS = { + "locations": "ALTER TABLE secret_findings ADD COLUMN locations TEXT", } SAST_REVIEW_STATUSES = ("confirmed", "false_positive", "accepted_risk") @@ -206,10 +214,44 @@ def _migrate(self) -> None: for column, ddl in _SAST_FINDINGS_MIGRATIONS.items(): if column not in existing_sast_cols: self._add_column(ddl) + existing_secret_cols = { + row["name"] for row in self._conn.execute("PRAGMA table_info(secret_findings)").fetchall() + } + for column, ddl in _SECRET_FINDINGS_MIGRATIONS.items(): + if column not in existing_secret_cols: + self._add_column(ddl) self._conn.commit() + self._backfill_locations() self._migrate_attachment_kind_check() self._migrate_runs_status_check() + def _backfill_locations(self) -> None: + """Re-derives `locations` for rows stored before #112. Those rows + hold the register cell as it was parsed then: a multi-site or ranged + cell ("server.js:78-102, app/routes/session.js:116") is the whole of + location_file with no line. Such a row also gets location_file/ + location_line set to its first site, so the dashboard and the + incremental-scan file scope see a real path; the fingerprint is left + alone (runner.py rekeys it when the finding is seen again). Only + NULL rows are touched, so this is a no-op once done.""" + for table in sorted(_FILE_SCOPED_TABLES): + rows = self._conn.execute( + f"SELECT id, location_file, location_line FROM {table} WHERE locations IS NULL" # nosec B608 -- table from a fixed set + ).fetchall() + for row in rows: + cell = row["location_file"] or "" + if row["location_line"]: + cell += f":{row['location_line']}" + sites = parse_locations(cell) + first_file, first_line = (sites[0].path, sites[0].start_line) if sites else ( + row["location_file"], row["location_line"]) + self._conn.execute( + f"UPDATE {table} SET locations = ?, location_file = ?, location_line = ? " # nosec B608 -- table from a fixed set + "WHERE id = ? AND locations IS NULL", + (locations_json(cell), first_file, first_line, row["id"]), + ) + 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 @@ -1457,6 +1499,7 @@ def upsert_sast_finding( description: str | None = None, recommendation: str | None = None, code_region_hash: str | None = None, + locations: str | None = None, language: str | None = None, framework: str | None = None, construct: str | None = None, @@ -1471,16 +1514,16 @@ 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, code_region_hash, language, framework, construct, " - "cvss_vector, cvss_score, " + "owasp, verdict, location_file, location_line, locations, code_region_hash, language, framework, " + "construct, cvss_vector, cvss_score, " "description, recommendation, status, first_seen_run_id, first_seen_at, last_seen_run_id, " "last_seen_at) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) " + "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, " + "locations = excluded.locations, code_region_hash = excluded.code_region_hash, " "language = excluded.language, framework = excluded.framework, construct = excluded.construct, " "cvss_vector = excluded.cvss_vector, cvss_score = excluded.cvss_score, " "description = excluded.description, recommendation = excluded.recommendation, status = 'open', " @@ -1488,7 +1531,7 @@ def upsert_sast_finding( "closed_in_run_id = NULL, closed_at = NULL", ( project_id, fingerprint, current_ref, title, severity, cwe, owasp, verdict, - location_file, location_line, code_region_hash, language, framework, construct, + location_file, location_line, locations, code_region_hash, language, framework, construct, cvss_vector, cvss_score, description, recommendation, run_id, now, run_id, now, ), ) @@ -1501,16 +1544,31 @@ def rekey_open_sast_fingerprint( No-op when the new key already exists or the old row is missing/closed. """ + self._rekey_open_fingerprint( + "sast_findings", project_id=project_id, old_fingerprint=old_fingerprint, new_fingerprint=new_fingerprint + ) + + def rekey_open_secret_fingerprint( + self, *, project_id: int, old_fingerprint: str, new_fingerprint: str + ) -> None: + """rekey_open_sast_fingerprint for secret_findings (#112).""" + self._rekey_open_fingerprint( + "secret_findings", project_id=project_id, old_fingerprint=old_fingerprint, new_fingerprint=new_fingerprint + ) + + def _rekey_open_fingerprint( + self, table: str, *, project_id: int, old_fingerprint: str, new_fingerprint: str + ) -> None: if old_fingerprint == new_fingerprint: return exists = self._conn.execute( - "SELECT 1 FROM sast_findings WHERE project_id = ? AND fingerprint = ?", + f"SELECT 1 FROM {table} WHERE project_id = ? AND fingerprint = ?", # nosec B608 -- table from a fixed set (project_id, new_fingerprint), ).fetchone() if exists: return self._conn.execute( - "UPDATE sast_findings SET fingerprint = ? " + f"UPDATE {table} SET fingerprint = ? " # nosec B608 -- table from a fixed set "WHERE project_id = ? AND fingerprint = ? AND status = 'open'", (new_fingerprint, project_id, old_fingerprint), ) @@ -1644,6 +1702,7 @@ def upsert_secret_finding( location_file: str, severity: str, location_line: str | None = None, + locations: str | None = None, code_region_hash: str | None = None, source: str | None = None, validity: str | None = None, @@ -1661,7 +1720,8 @@ def upsert_secret_finding( run_id=run_id, fields={ "current_ref": current_ref, "secret_type": secret_type, "location_file": location_file, - "location_line": location_line, "code_region_hash": code_region_hash, "source": source, + "location_line": location_line, "locations": locations, "code_region_hash": code_region_hash, + "source": source, "validity": validity, "severity": severity, "evidence": evidence, "exposure": exposure, "remediation": remediation, "language": language, "framework": framework, "construct": construct, diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index d687ba4..0360a10 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -228,6 +228,10 @@ CREATE TABLE IF NOT EXISTS sast_findings ( verdict TEXT, location_file TEXT NOT NULL, location_line TEXT, + -- Every site of the finding (#112), as a JSON list of + -- {"path", "start_line", "end_line"}; location_file/location_line are + -- the first one. See report/sast.py:parse_locations. + locations TEXT, code_region_hash TEXT, -- Stack + code-free construct description (see stack.py and the -- `**Construct:**` contract field): the fields that make a finding @@ -301,6 +305,7 @@ CREATE TABLE IF NOT EXISTS secret_findings ( secret_type TEXT NOT NULL, location_file TEXT NOT NULL, location_line TEXT, + locations TEXT, -- every site, as in sast_findings.locations code_region_hash TEXT, source TEXT, -- code / config / history / docs validity TEXT, -- Looks live / Unclear / Placeholder diff --git a/src/secfoo/web/templates/activities/sast_finding_detail.html b/src/secfoo/web/templates/activities/sast_finding_detail.html index a7bd1e5..cfd1b2f 100644 --- a/src/secfoo/web/templates/activities/sast_finding_detail.html +++ b/src/secfoo/web/templates/activities/sast_finding_detail.html @@ -13,7 +13,8 @@

{{ 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 %} + {% for site in finding.sites() %}· {{ site.path }}{% if site.start_line %}:{{ site.start_line }}{% if site.end_line %}-{{ site.end_line }}{% endif %}{% endif %} + {% endfor %}

diff --git a/tests/test_report/test_multi_location.py b/tests/test_report/test_multi_location.py new file mode 100644 index 0000000..a1bda66 --- /dev/null +++ b/tests/test_report/test_multi_location.py @@ -0,0 +1,336 @@ +"""#112: ranged and multi-site Location cells become real paths. + +Before #112, parse_location() only understood `file:line`, so +"server.js:78-102, app/routes/session.js:116" was stored whole as the +file name: SARIF got a percent-encoded URI GitHub cannot attach to a file, +and the fingerprint changed whenever an agent wrote `all.js:8` instead of +`all.js:8-9`. +""" + +from __future__ import annotations + +import hashlib +import json +import re +import sqlite3 +from pathlib import Path + +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +from jsonschema import Draft7Validator, FormatChecker + +from secfoo.report import sast, secret_scanning +from secfoo.report.sarif import findings_to_sarif +from secfoo.report.sast import ( + SourceLocation, + fingerprint_for_row, + parse_location, + parse_locations, +) +from secfoo.runner import update_sast_findings, update_secret_findings +from secfoo.storage.repository import RunRepository + +ROOT = Path(__file__).parents[2] +SAMPLE = ROOT / "examples" / "sample-output" / "nodegoat" +SCHEMA = json.loads((Path(__file__).parents[1] / "fixtures" / "sarif-schema-2.1.0.json").read_text()) +VALIDATOR = Draft7Validator(SCHEMA, format_checker=FormatChecker()) + + +# --- The four strings from the issue ------------------------------------- + +@pytest.mark.parametrize( + ("cell", "expected"), + [ + ("config/env/all.js:8-9", [("config/env/all.js", "8", "9")]), + ( + "server.js:78-102, app/routes/session.js:116, …", + [("server.js", "78", "102"), ("app/routes/session.js", "116", None)], + ), + ("app/data/user-dao.js:25, :61", [("app/data/user-dao.js", "25", None), ("app/data/user-dao.js", "61", None)]), + ( + "`server.js:135-137`, `app/views/layout.html:75`", + [("server.js", "135", "137"), ("app/views/layout.html", "75", None)], + ), + ], +) +def test_issue_examples_parse_into_every_site(cell, expected): + assert parse_locations(cell) == [SourceLocation(*site) for site in expected] + assert parse_location(cell) == (expected[0][0], expected[0][1]) + + +@pytest.mark.parametrize( + ("cell", "expected"), + [ + ("`app/db.py:42`", [("app/db.py", "42", None)]), + ("app/db.py", [("app/db.py", None, None)]), + ("a.py:10–12", [("a.py", "10", "12")]), # en dash + ("a.py:10 - 12", [("a.py", "10", "12")]), + ("a.py:12:5", [("a.py", "12", None)]), # line:column + ("a.py:9-3", [("a.py", "9", None)]), # reversed range is its start line + ("a.py:7-7", [("a.py", "7", None)]), + ("a.py:25,61", [("a.py", "25", None), ("a.py", "61", None)]), + ("a.py:1; b.py:2", [("a.py", "1", None), ("b.py", "2", None)]), + ("a.py:5, 80-90", [("a.py", "5", None), ("a.py", "80", "90")]), + ("a.py:0042", [("a.py", "42", None)]), + (r"C:\src\app.py:12", [(r"C:\src\app.py", "12", None)]), + ("", []), + ("…", []), + (":61", []), # a bare line with no path before it + ], +) +def test_other_location_shapes(cell, expected): + assert parse_locations(cell) == [SourceLocation(*site) for site in expected] + + +def test_a_cell_with_no_site_degrades_to_its_text(): + assert parse_location(" `…` ") == ("…", None) + + +# --- Properties ---------------------------------------------------------- + +_TRAILING_RANGE = re.compile(r":\s*\d+(\s*[-\u2013\u2014]\s*\d+)?\s*$") +_PATH = st.from_regex(r"[A-Za-z0-9_./-]{1,20}", fullmatch=True).filter(lambda p: any(c.isalnum() for c in p)) +_LINE = st.integers(min_value=1, max_value=99_999).map(str) + + +@settings(max_examples=300) +@given(st.text(alphabet=st.characters(codec="utf-8"), max_size=120)) +def test_parse_locations_never_leaves_separators_or_ranges_in_a_path(cell): + for site in parse_locations(cell): + assert site.path and site.path == site.path.strip() + assert not set(site.path) & {",", ";", "`"} + assert not _TRAILING_RANGE.search(site.path) + assert site.start_line is None or site.start_line.isdigit() + if site.end_line is not None: + assert (len(site.end_line), site.end_line) > (len(site.start_line), site.start_line) + path, _line = parse_location(cell) + assert "`" not in path + + +@settings(max_examples=200) +@given(st.lists(st.tuples(_PATH, _LINE, st.one_of(st.none(), _LINE)), min_size=1, max_size=5), st.booleans()) +def test_written_lists_round_trip(sites, backticks): + tick = "`" if backticks else "" + cell = ", ".join(f"{tick}{p}:{a}{'-' + b if b else ''}{tick}" for p, a, b in sites) + parsed = parse_locations(cell) + assert [(s.path, s.start_line) for s in parsed] == [(p, a) for p, a, _b in sites] + for site, (_p, a, b) in zip(parsed, sites): + assert site.end_line == (b if b is not None and int(b) > int(a) else None) + + +def test_fingerprint_is_the_same_for_a_range_and_its_first_line(): + """all.js:8-9 one run and all.js:8 the next is the same finding.""" + ranged = fingerprint_for_row({"cwe": "CWE-798", "location": "`config/env/all.js:8-9`"}) + single = fingerprint_for_row({"cwe": "CWE-798", "location": "`config/env/all.js:8`"}) + multi = fingerprint_for_row({"cwe": "CWE-798", "location": "`config/env/all.js:8`, `db-reset.js:15-18`"}) + assert ranged == single == multi + + +# --- The NodeGoat sample ------------------------------------------------- + +def _sample_records() -> list[dict]: + records = [] + for skill, module, report in ( + ("sast", sast, "sast-report.md"), + ("secret-scanning", secret_scanning, "secret-scanning-report.md"), + ): + for row in module.findings_with_fingerprints((SAMPLE / report).read_text(encoding="utf-8")): + records.append({**row, "skill_id": skill}) + return records + + +def test_nodegoat_sample_sarif_validates_and_every_result_has_a_real_uri(): + records = _sample_records() + assert len(records) == 18 + document = findings_to_sarif(records) + VALIDATOR.validate(document) + for result in document["runs"][0]["results"]: + assert result["locations"] + for location in result["locations"]: + uri = location["physicalLocation"]["artifactLocation"]["uri"] + # No encoded comma, colon, semicolon, space or backtick: one file per URI. + assert not re.search(r"%(2C|3A|3B|20|60)", uri, re.IGNORECASE), uri + region = location["physicalLocation"].get("region") + if region and "endLine" in region: + assert region["endLine"] > region["startLine"] + + +def test_nodegoat_multi_site_finding_gets_one_sarif_location_per_site(): + records = {r["id"]: r for r in _sample_records() if r["skill_id"] == "sast"} + xss = next(r for r in records.values() if "server.js:135-137" in r["location"]) + result = findings_to_sarif([xss])["runs"][0]["results"][0] + assert [loc["physicalLocation"] for loc in result["locations"]] == [ + {"artifactLocation": {"uri": "server.js"}, "region": {"startLine": 135, "endLine": 137}}, + {"artifactLocation": {"uri": "app/views/layout.html"}, "region": {"startLine": 75}}, + ] + + +def test_sarif_without_locations_falls_back_to_location_file(): + result = findings_to_sarif([{"skill_id": "sast", "location_file": "a.py", "location_line": "3"}]) + assert result["runs"][0]["results"][0]["locations"] == [ + {"physicalLocation": {"artifactLocation": {"uri": "a.py"}, "region": {"startLine": 3}}} + ] + + +# --- Storage, migration and lifecycle ------------------------------------ + +_REPORT = """# SAST + +## Findings Register + +| ID | Finding | Severity | CWE | OWASP | CVSS Vector | Location | Verdict | +|----|---------|----------|-----|-------|-------------|----------|---------| +| F1 | Hard-coded secret | High | CWE-798 | A07:2021 | AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N | `config/env/all.js:8-9`, `artifacts/db-reset.js:15-18` | Confirmed | +""" + +_SECRET_REPORT = (SAMPLE / "secret-scanning-report.md").read_text(encoding="utf-8") + + +def _project_and_run(repo: RunRepository) -> tuple[int, int]: + project_id = repo.upsert_project(identifier="/tmp/x", display_name="x", kind="local") + run_uuid = repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] + ) + return project_id, repo.get_run(run_uuid).id + + +def test_sast_rows_store_every_site(tmp_path): + repo = RunRepository(db_path=tmp_path / "db.sqlite") + project_id, run_id = _project_and_run(repo) + update_sast_findings(repo, project_id=project_id, run_id=run_id, report_text=_REPORT) + (row,) = repo.list_sast_findings() + assert (row.location_file, row.location_line) == ("config/env/all.js", "8") + assert row.sites() == [ + {"path": "config/env/all.js", "start_line": "8", "end_line": "9"}, + {"path": "artifacts/db-reset.js", "start_line": "15", "end_line": "18"}, + ] + repo.close() + + +def _store_as_before_112(repo: RunRepository, table: str) -> None: + """Drop the #112 column, as on a store created before it existed.""" + repo._conn.execute(f"ALTER TABLE {table} DROP COLUMN locations") + repo._conn.commit() + + +def test_migration_re_derives_locations_for_rows_stored_before_112(tmp_path): + db_path = tmp_path / "db.sqlite" + repo = RunRepository(db_path=db_path) + project_id, run_id = _project_and_run(repo) + repo.upsert_sast_finding( + project_id=project_id, fingerprint="old", current_ref="F12", title="XSS", severity="High", + cwe="CWE-79", owasp=None, verdict=None, + location_file="server.js:78-102, app/routes/session.js:116, …", location_line=None, + cvss_vector=None, cvss_score=None, run_id=run_id, + ) + repo.upsert_sast_finding( + project_id=project_id, fingerprint="plain", current_ref="F1", title="SQLi", severity="High", + cwe="CWE-89", owasp=None, verdict=None, location_file="app/db.py", location_line="42", + cvss_vector=None, cvss_score=None, run_id=run_id, + ) + repo.upsert_secret_finding( + project_id=project_id, fingerprint="s-old", run_id=run_id, current_ref="S1", secret_type="Password", + location_file="config/env/all.js:8-9", severity="High", + ) + _store_as_before_112(repo, "sast_findings") + _store_as_before_112(repo, "secret_findings") + repo.close() + + repo = RunRepository(db_path=db_path) + rows = {r.fingerprint: r for r in repo.list_sast_findings()} + assert (rows["old"].location_file, rows["old"].location_line) == ("server.js", "78") + assert json.loads(rows["old"].locations) == [ + {"path": "server.js", "start_line": "78", "end_line": "102"}, + {"path": "app/routes/session.js", "start_line": "116", "end_line": None}, + ] + assert (rows["plain"].location_file, rows["plain"].location_line) == ("app/db.py", "42") + assert json.loads(rows["plain"].locations) == [{"path": "app/db.py", "start_line": "42", "end_line": None}] + (secret,) = repo.list_secret_findings() + assert (secret.location_file, secret.location_line) == ("config/env/all.js", "8") + assert json.loads(secret.locations) == [{"path": "config/env/all.js", "start_line": "8", "end_line": "9"}] + repo.close() + + # Opening again is a no-op: nothing is NULL any more. + conn = sqlite3.connect(db_path) + assert conn.execute("SELECT COUNT(*) FROM sast_findings WHERE locations IS NULL").fetchone() == (0,) + conn.close() + + +def test_a_finding_stored_before_112_stays_open_when_seen_again(tmp_path): + """The upgrade must not show every multi-site finding as closed + new.""" + repo = RunRepository(db_path=tmp_path / "db.sqlite") + project_id, run_id = _project_and_run(repo) + row = sast.extract_findings_register_rows(_REPORT)[0] + repo.upsert_sast_finding( + project_id=project_id, fingerprint=sast.pre_112_fingerprint(row), current_ref="F1", + title="Hard-coded secret", severity="High", cwe="CWE-798", owasp=None, verdict=None, + location_file=row["location"].replace("`", ""), location_line=None, + cvss_vector=None, cvss_score=None, run_id=run_id, + ) + (before,) = repo.list_sast_findings() + + update_sast_findings(repo, project_id=project_id, run_id=run_id, report_text=_REPORT) + + (after,) = repo.list_sast_findings() + assert after.id == before.id + assert after.status == "open" + assert after.fingerprint == fingerprint_for_row(row) + assert after.first_seen_at == before.first_seen_at + repo.close() + + +def test_a_secret_stored_before_112_stays_open_when_seen_again(tmp_path): + repo = RunRepository(db_path=tmp_path / "db.sqlite") + project_id, run_id = _project_and_run(repo) + rows = secret_scanning.findings_with_fingerprints(_SECRET_REPORT) + ranged = [r for r in rows if r["pre_112_fingerprint"]] + assert ranged, "the sample should contain at least one ranged secret location" + for row in rows: + repo.upsert_secret_finding( + project_id=project_id, fingerprint=row["pre_112_fingerprint"] or row["fingerprint"], run_id=run_id, + current_ref=row["id"], secret_type=row["secret_type"], location_file=row["location"], + severity=row["severity"], + ) + ids_before = {r.id for r in repo.list_secret_findings()} + + update_secret_findings(repo, project_id=project_id, run_id=run_id, report_text=_SECRET_REPORT) + + after = repo.list_secret_findings() + assert {r.id for r in after} == ids_before + assert all(r.status == "open" for r in after) + repo.close() + + +@pytest.mark.parametrize( + ("cell", "old_path"), + [ + # The old regex matched these, but read the whole list as one file. + ("app/db.py, app/cli.py", "app/db.py, app/cli.py"), + ("app/db.py; app/cli.py", "app/db.py; app/cli.py"), + ("app/db.py, app/cli.py:12", "app/db.py, app/cli.py"), + ], +) +def test_an_unbackticked_list_the_old_parser_matched_is_still_rekeyed(cell, old_path): + assert sast.pre_112_path(cell) == old_path + # The key a stored row got: skill | cwe | whole path (no line, no region hash). + old_sast = hashlib.sha256(f"{sast.SKILL_ID}|cwe-89|{old_path}".encode()).hexdigest() + assert sast.pre_112_fingerprint({"cwe": "CWE-89", "location": cell}) == old_sast + old_secret = secret_scanning.fingerprint_for_row({"secret_type": "x"}, file_path=old_path) + assert secret_scanning.pre_112_fingerprint({"secret_type": "x", "location": cell}) == old_secret + + +def test_rekey_is_a_no_op_for_a_single_site_cell(): + assert sast.pre_112_fingerprint({"cwe": "CWE-89", "location": "`app/db.py:42`"}) is None + assert secret_scanning.pre_112_fingerprint({"secret_type": "x", "location": "`a.env:3`"}) is None + + +def test_jsonl_export_carries_locations_as_a_list(): + from secfoo.cli import _decoded_locations + + assert _decoded_locations('[{"path": "a.py", "start_line": "1", "end_line": null}]') == [ + {"path": "a.py", "start_line": "1", "end_line": None} + ] + assert _decoded_locations(None) is None + assert _decoded_locations("not json") is None + assert _decoded_locations('{"path": "a.py"}') is None diff --git a/tests/test_report/test_sast.py b/tests/test_report/test_sast.py index 11bd2a9..03b0803 100644 --- a/tests/test_report/test_sast.py +++ b/tests/test_report/test_sast.py @@ -133,17 +133,15 @@ def test_parse_location_handles_no_backticks(): assert parse_location("app/db.py:42") == ("app/db.py", "42") -def test_parse_location_strips_backticks_from_a_multi_location_cell(): +def test_parse_location_takes_the_first_site_of_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. + that exposes it). Before #112 the whole cell became the path; now the + first site is location_file/location_line and parse_locations() keeps + every site, so nothing is dropped. Backticks (Markdown code-span + syntax) are still stripped either way. """ - 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 parse_location("`web/app.py:35`, `cli.py:308`") == ("web/app.py", "35") def test_fingerprint_for_row_is_stable_for_identical_cwe_and_file_without_region_hash(): diff --git a/tests/test_web/test_run_ui.py b/tests/test_web/test_run_ui.py index 0fd7790..8c879c7 100644 --- a/tests/test_web/test_run_ui.py +++ b/tests/test_web/test_run_ui.py @@ -241,3 +241,23 @@ def test_documentation_coverage_omitted_when_empty(client): assert resp.status_code == 200 assert "Documentation coverage" not in resp.text assert "documentation sources" not in resp.text + + +def test_finding_detail_lists_every_site(client): + """#112: a multi-site finding shows each site, not one joined path.""" + repo = RunRepository() + project_id = repo.upsert_project("p", "Payments API", "local") + run_uuid = repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="claude", confluence_urls=[] + ) + repo.upsert_sast_finding( + project_id=project_id, fingerprint="fp2", current_ref="F6", title="Stored XSS", severity="High", + cwe="CWE-79", owasp=None, verdict="Confirmed", 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": null}]', + cvss_vector=None, cvss_score=None, run_id=repo.get_run(run_uuid).id, + ) + repo.close() + page = client.get("/activities/sast/findings/fp2").text + assert "server.js:135-137" in page + assert "app/views/layout.html:75" in page