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
17 changes: 11 additions & 6 deletions .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
# `fail-on` has findings or a scanner job broke. Report-only = `fail-on: ""`.
#
# Callers need `permissions: contents: read, security-events: write`.
# On public repositories results also go to the Security tab (code scanning);
# private repositories without GitHub Advanced Security get the summary and
# the artifacts only.
# On public repositories results also go to the Security tab (code
# scanning), without the vulnerabilities the VEX file accepts, so the tab and
# the report agree; private repositories without GitHub Advanced Security get
# the summary and the artifacts only.
name: security

on:
Expand Down Expand Up @@ -134,7 +135,7 @@ on:
type: string
default: security
code-scanning:
description: Upload results to the Security tab on public repositories.
description: Upload results to the Security tab on public repositories (without the vulnerabilities the VEX file accepts).
type: boolean
default: true
scheduled-full:
Expand Down Expand Up @@ -300,8 +301,10 @@ jobs:
retention-days: 90
- id: cs
if: always() && inputs.code-scanning && !github.event.repository.private
env:
VEX: ${{ inputs.vex-file }}
run: |
python3 -I "$HARNESS/scripts/sarif-summary.py" upload-copy --dir "$RUNNER_TEMP/findings" --out "$RUNNER_TEMP/code-scanning"
python3 -I "$HARNESS/scripts/sarif-summary.py" upload-copy --dir "$RUNNER_TEMP/findings" --out "$RUNNER_TEMP/code-scanning" --vex "$VEX"
echo "files=$(find "$RUNNER_TEMP/code-scanning" -name '*.sarif' | wc -l)" >> "$GITHUB_OUTPUT"
- uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
if: always() && steps.cs.outputs.files > 0
Expand Down Expand Up @@ -597,8 +600,10 @@ jobs:
retention-days: 90
- id: cs
if: always() && inputs.code-scanning && !github.event.repository.private
env:
VEX: ${{ inputs.vex-file }}
run: |
python3 -I "$HARNESS/scripts/sarif-summary.py" upload-copy --dir "$RUNNER_TEMP/findings" --out "$RUNNER_TEMP/code-scanning"
python3 -I "$HARNESS/scripts/sarif-summary.py" upload-copy --dir "$RUNNER_TEMP/findings" --out "$RUNNER_TEMP/code-scanning" --vex "$VEX"
echo "files=$(find "$RUNNER_TEMP/code-scanning" -name '*.sarif' | wc -l)" >> "$GITHUB_OUTPUT"
- uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0
if: always() && steps.cs.outputs.files > 0
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ repository-local `integration` job next to the gate.
Every run writes a summary table to the job summary and keeps the raw reports
as artifacts (`security-findings-*`, `security-sbom`) for 90 days. A workflow that
calls `security.yml` more than once per run gives each call its own `artifact-prefix`. Public repositories also get
the results in their Security tab.
the results in their Security tab, without the vulnerabilities the VEX file
accepts, so the tab and the report agree.

## Central logic, thin callers

Expand Down
57 changes: 40 additions & 17 deletions scripts/sarif-summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

sarif-summary.py report --dir DIR [--fail-on CATS] [--vex FILE] [--trivyignore FILE]
[--jobs JSON] [--summary FILE] [--output FILE]
sarif-summary.py upload-copy --dir DIR --out DIR
sarif-summary.py upload-copy --dir DIR --out DIR [--vex FILE]

`report` reads every *.sarif and licenses*.json below DIR, sorts each finding
into one category, drops findings an OpenVEX statement marks not_affected or
Expand All @@ -17,8 +17,11 @@
semgrep-other, other. `vuln-high` in --fail-on blocks high and critical.

`upload-copy` writes SARIF copies for GitHub code scanning: results without a
source location are dropped (code scanning rejects them), and only the first
run per tool is kept.
source location are dropped (code scanning rejects them), so are
vulnerabilities a valid statement in the --vex file accepts (the report does
not count them either), and only the first run per tool is kept. A run whose
results are all accepted is still written, empty: that upload closes the
alerts of earlier uploads.

Standard library only; run with `python3 -I`.
"""
Expand Down Expand Up @@ -136,6 +139,23 @@ def location_of(result):
return ""


def rule_of(rules, rule_list, result):
rule = rules.get(result.get("ruleId"))
if rule is None and isinstance(result.get("ruleIndex"), int) and result["ruleIndex"] < len(rule_list):
rule = rule_list[result["ruleIndex"]]
return rule or {}


def vex_match(category, rule, result, vex):
"""The (vuln id, VEX entry) covering a vulnerability finding, or None."""
if not category.startswith("vuln"):
return None
for vid in finding_ids(rule, result):
if vid in vex:
return vid, vex[vid]
return None


def load_vex(path):
"""Return ({vuln id: (status, justification, valid_until)}, warnings)."""
entries, warnings = {}, []
Expand Down Expand Up @@ -201,10 +221,7 @@ def collect(directory, vex):
# without a status, or accepted, takes the result out.
if any((s or {}).get("status", "accepted") == "accepted" for s in result.get("suppressions") or []):
continue
rule = rules.get(result.get("ruleId"))
if rule is None and isinstance(result.get("ruleIndex"), int) and result["ruleIndex"] < len(rule_list):
rule = rule_list[result["ruleIndex"]]
rule = rule or {}
rule = rule_of(rules, rule_list, result)
category = classify(tool, rule, result)
item = {
"tool": tool,
Expand All @@ -213,12 +230,7 @@ def collect(directory, vex):
"location": location_of(result),
"message": " ".join(((result.get("message") or {}).get("text") or "").split())[:140],
}
match = None
if category.startswith("vuln"):
for vid in finding_ids(rule, result):
if vid in vex:
match = (vid, vex[vid])
break
match = vex_match(category, rule, result, vex)
if match and match[1][2] >= now:
item["vex"] = f"{match[0]}: {match[1][0]} ({match[1][1]})"
suppressed.append(item)
Expand Down Expand Up @@ -327,28 +339,38 @@ def cmd_report(args):

def cmd_upload_copy(args):
os.makedirs(args.out, exist_ok=True)
vex, _ = load_vex(args.vex)
now = today()
seen_tools = set()
for path in sorted(glob.glob(os.path.join(args.dir, "**", "*.sarif"), recursive=True)):
with open(path, encoding="utf-8") as fh:
doc = json.load(fh)
runs = []
runs, accepted = [], 0
for run in doc.get("runs") or []:
tool = ((run.get("tool") or {}).get("driver") or {}).get("name") or "unknown"
tool, rules, rule_list = rule_index(run)
results = run.get("results") or []
located = [r for r in results if location_of(r)]
if results and not located:
continue
if tool in seen_tools:
continue
seen_tools.add(tool)
run["results"] = located
kept = []
for result in located:
rule = rule_of(rules, rule_list, result)
match = vex_match(classify(tool, rule, result), rule, result, vex)
if match and match[1][2] >= now:
accepted += 1
continue
kept.append(result)
run["results"] = kept
runs.append(run)
if runs:
doc["runs"] = runs
name = os.path.basename(path)
with open(os.path.join(args.out, name), "w", encoding="utf-8") as fh:
json.dump(doc, fh)
print(f"upload copy: {name} ({sum(len(r['results']) for r in runs)} located results)")
print(f"upload copy: {name} ({sum(len(r['results']) for r in runs)} located results, {accepted} accepted left out)")
return 0


Expand All @@ -366,6 +388,7 @@ def main():
up = sub.add_parser("upload-copy")
up.add_argument("--dir", required=True)
up.add_argument("--out", required=True)
up.add_argument("--vex")
args = parser.parse_args()
return cmd_report(args) if args.cmd == "report" else cmd_upload_copy(args)

Expand Down
38 changes: 38 additions & 0 deletions scripts/test_sarif_summary.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,44 @@ def test_drops_locationless_and_duplicate_runs(self):
subprocess.run([sys.executable, "-I", SCRIPT, "upload-copy", "--dir", c.dir, "--out", out], check=True, capture_output=True)
self.assertEqual(sorted(os.listdir(out)), ["govulncheck-code.sarif", "trivy.sarif"])

def upload(self, c, vex=None):
out = os.path.join(c.tmp.name, "cs")
cmd = [sys.executable, "-I", SCRIPT, "upload-copy", "--dir", c.dir, "--out", out]
if vex:
cmd += ["--vex", vex]
subprocess.run(cmd, check=True, capture_output=True, env={**os.environ, "SUMMARY_TODAY": TODAY})
copies = {}
for name in os.listdir(out):
with open(os.path.join(out, name)) as fh:
copies[name] = [r["ruleId"] for r in json.load(fh)["runs"][0]["results"]]
return copies

def test_vex_accepted_results_are_left_out(self):
c = self.case()
c.add("gv.sarif", sarif("govulncheck", [{"id": "GO-1"}, {"id": "GO-2"}, {"id": "GO-3"}],
[result("GO-1", "error"), result("GO-2", "error", line=2), result("GO-3", "error", line=3)]))
suppressed = result("r1")
suppressed["suppressions"] = [{"kind": "inSource"}]
c.add("s.sarif", sarif("Semgrep OSS", [{"id": "r1"}], [suppressed, result("r1", line=2)]))
vex = c.file("vex.json", json.dumps({"statements": [
{"vulnerability": {"name": "GO-1"}, "status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path", "timestamp": "2026-06-01T00:00:00Z"},
{"vulnerability": {"name": "GO-3"}, "status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path", "timestamp": "2025-09-01T00:00:00Z"}]}))
copies = self.upload(c, vex)
self.assertEqual(copies["gv.sarif"], ["GO-2", "GO-3"], "a valid VEX statement leaves the result out, an expired one does not")
self.assertEqual(copies["s.sarif"], ["r1", "r1"], "in-source suppressions stay as they are")
self.assertEqual(self.upload(c)["gv.sarif"], ["GO-1", "GO-2", "GO-3"], "without --vex nothing is accepted")

def test_run_with_only_accepted_results_is_uploaded_empty(self):
# The empty upload closes the alerts of earlier uploads.
c = self.case()
c.add("gv.sarif", sarif("govulncheck", [{"id": "GO-1"}], [result("GO-1", "error")]))
vex = c.file("vex.json", json.dumps({"statements": [
{"vulnerability": {"name": "GO-1"}, "status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path", "timestamp": "2026-06-01T00:00:00Z"}]}))
self.assertEqual(self.upload(c, vex), {"gv.sarif": []})


if __name__ == "__main__":
unittest.main(verbosity=1)
Loading