diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 6455a4f..cdc73ee 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -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: @@ -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: @@ -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 @@ -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 diff --git a/README.md b/README.md index 56fc73d..cf5d2f3 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/scripts/sarif-summary.py b/scripts/sarif-summary.py index 36bc238..99a251c 100755 --- a/scripts/sarif-summary.py +++ b/scripts/sarif-summary.py @@ -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 @@ -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`. """ @@ -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 = {}, [] @@ -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, @@ -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) @@ -327,13 +339,15 @@ 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: @@ -341,14 +355,22 @@ def cmd_upload_copy(args): 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 @@ -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) diff --git a/scripts/test_sarif_summary.py b/scripts/test_sarif_summary.py index a01e5f9..3fa4ab3 100644 --- a/scripts/test_sarif_summary.py +++ b/scripts/test_sarif_summary.py @@ -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)