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
16 changes: 14 additions & 2 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
|---|---|
Expand All @@ -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
Expand Down
18 changes: 17 additions & 1 deletion src/secfoo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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()
Expand Down
73 changes: 58 additions & 15 deletions src/secfoo/report/sarif.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import json
import re
from pathlib import PureWindowsPath
from urllib.parse import quote
Expand All @@ -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.

Expand Down Expand Up @@ -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,
Expand Down
133 changes: 119 additions & 14 deletions src/secfoo/report/sast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<file>[^:`]+?)(?::(?P<line>\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<start>\d+)(?:\s*[-\u2013\u2014]\s*(?P<end>\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<start>\d+)(?:\s*[-\u2013\u2014]\s*(?P<end>\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<file>[^:`]+?)(?::(?P<line>\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]]:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"], ""),
Expand Down
18 changes: 17 additions & 1 deletion src/secfoo/report/secret_scanning.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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]]:
Expand Down Expand Up @@ -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
Loading
Loading