diff --git a/proofline/__init__.py b/proofline/__init__.py index a98bd2d2..0eb1517e 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -39,6 +39,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome +from .sarif import review_sarif __all__ = [ "AgentSession", @@ -86,4 +87,5 @@ "UploadedReport", "__version__", "models", + "review_sarif", ] diff --git a/proofline/sarif.py b/proofline/sarif.py new file mode 100644 index 00000000..5d703e2e --- /dev/null +++ b/proofline/sarif.py @@ -0,0 +1,332 @@ +"""Render a Proofline review outcome as a SARIF 2.1.0 document for CI code scanning.""" + +from __future__ import annotations + +import re +from collections.abc import Iterable +from typing import Any +from urllib.parse import quote + +from ._generated.models.customer_code_assessment import CustomerCodeAssessment +from ._generated.models.customer_evidence_ref import CustomerEvidenceRef +from ._generated.models.customer_finding import CustomerFinding +from ._generated.types import Unset +from ._transport import VERSION +from .outcomes import AssessmentGap, ReviewOutcome + +SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json" +SARIF_VERSION = "2.1.0" +_WITHHELD_MARKER = "[withheld: environment value]" +_SEVERITY_TO_LEVEL: dict[str, str] = { + "SERIOUS": "error", + "CRITICAL": "error", + "HIGH": "error", + "WARNING": "warning", + "MEDIUM": "warning", +} +_SEVERITY_RANK: dict[str, int] = { + "SERIOUS": 0, + "CRITICAL": 0, + "HIGH": 1, + "WARNING": 2, + "MEDIUM": 2, +} +_RULE_SLUG_RE = re.compile(r"[^a-z0-9._-]+") + + +def _opt_str(value: object) -> str | None: + if isinstance(value, Unset) or not isinstance(value, str): + return None + stripped = value.strip() + return stripped or None + + +def _opt_positive_int(value: object) -> int | None: + if isinstance(value, Unset) or type(value) is not int or value < 1: + return None + return value + + +def _normalize_relative_uri(path: str) -> str | None: + normalized = path.replace("\\", "/").lstrip("/") + if not normalized: + return None + parts = [part for part in normalized.split("/") if part not in ("", ".")] + if not parts or any(part == ".." for part in parts): + return None + return "/".join(quote(part, "-_.~:@!$&'()*+,;=") for part in parts) + + +def _rule_id_for(finding: CustomerFinding) -> str: + for ref in finding.rule_refs: + key = _opt_str(ref.key) + if key is not None: + return key + domain = _RULE_SLUG_RE.sub("-", finding.risk_domain.strip().lower()).strip("-") + return f"proofline/{domain or 'finding'}" + + +def _physical_location(ref: CustomerEvidenceRef) -> dict[str, Any] | None: + raw_path = _opt_str(ref.repository_path) + if raw_path is None: + return None + uri = _normalize_relative_uri(raw_path) + if uri is None: + return None + location: dict[str, Any] = {"artifactLocation": {"uri": uri}} + start = _opt_positive_int(ref.start_line) + if start is not None: + region: dict[str, Any] = {"startLine": start} + end = _opt_positive_int(ref.end_line) + if end is not None and end >= start: + region["endLine"] = end + location["region"] = region + return location + + +def _format_message(finding: CustomerFinding) -> str: + parts = [finding.claim.strip()] + impact = finding.impact.strip() + if impact: + parts.append(f"Impact: {impact}") + remediation = _opt_str(finding.remediation) + if remediation is not None: + parts.append(f"Remediation: {remediation}") + return "\n\n".join(part for part in parts if part) + + +def _gap_notifications(outcome: ReviewOutcome) -> list[dict[str, Any]]: + notifications: list[dict[str, Any]] = [] + level = "warning" if outcome.status == "INCOMPLETE" else "error" + if outcome.status != "COMPLETED": + msg = f"Proofline review ended with status {outcome.status}." + if outcome.reason: + msg = f"{msg} Reason: {outcome.reason}" + notifications.append( + { + "descriptor": {"id": f"proofline/outcome/{outcome.status.lower()}"}, + "level": level, + "message": {"text": msg}, + "properties": { + "outcome_status": outcome.status, + "reason": outcome.reason, + "review_url": outcome.review_url, + }, + } + ) + for gap in outcome.gaps: + notifications.append(_format_gap_notification(gap, level=level)) + return notifications + + +def _format_gap_notification(gap: AssessmentGap, *, level: str) -> dict[str, Any]: + details = [f"Assessment {gap.assessment_id or 'unknown'} status={gap.status}."] + if gap.incompleteness_kind: + details.append(f"incompleteness_kind={gap.incompleteness_kind}") + if gap.reason_codes: + details.append(f"reason_codes={','.join(gap.reason_codes)}") + if gap.release_evidence_gap: + details.append(f"release_evidence_gap={gap.release_evidence_gap}") + if gap.checks: + check_summary = ", ".join(f"{chk.name}:{chk.outcome}" for chk in gap.checks) + details.append(f"checks=[{check_summary}]") + return { + "descriptor": {"id": "proofline/assessment/gap"}, + "level": level, + "message": {"text": " ".join(details)}, + "properties": { + "assessment_id": str(gap.assessment_id) if gap.assessment_id is not None else None, + "status": gap.status, + "incompleteness_kind": gap.incompleteness_kind, + "reason_codes": list(gap.reason_codes), + "release_evidence_gap": gap.release_evidence_gap, + "checks": [ + { + "name": chk.name, + "outcome": chk.outcome, + "lifecycle": chk.lifecycle, + "unresolved_reason": chk.unresolved_reason, + } + for chk in gap.checks + ], + }, + } + + +def _iter_findings( + outcome: ReviewOutcome, +) -> Iterable[tuple[CustomerFinding, str, str, str]]: + review = outcome.review + if review is None: + return () + collected: list[tuple[CustomerFinding, str, str, str]] = [] + if review.assessments: + for assessment in review.assessments: + aid = str(assessment.id) + env_name = assessment.environment_display_name + for finding in assessment.findings: + collected.append((finding, aid, env_name, "env")) + return collected + code = review.code_assessment + if isinstance(code, CustomerCodeAssessment): + aid = str(code.id) + for finding in code.findings: + collected.append((finding, aid, "code", "code")) + return collected + + +def review_sarif( + outcome: ReviewOutcome, + *, + include_resolved: bool = False, +) -> dict[str, Any]: + """Render a `ReviewOutcome` as a deterministic SARIF 2.1.0 document. + + Preserves Proofline's incompleteness semantics: `invocations[0].executionSuccessful` + is `True` only when `outcome.status == "COMPLETED"` and `outcome.gaps` is empty. + Non-completed or gap-bearing outcomes emit explicit `toolExecutionNotifications` + so CI pipelines never interpret an incomplete run as zero risk. + """ + if not isinstance(outcome, ReviewOutcome): + raise TypeError("outcome must be a ReviewOutcome instance.") + + rules_by_id: dict[str, dict[str, Any]] = {} + results_with_keys: list[tuple[tuple[int, str, int, str], dict[str, Any]]] = [] + notifications = _gap_notifications(outcome) + + for finding, assessment_id, env_name, lane in _iter_findings(outcome): + if finding.risk_domain == _WITHHELD_MARKER: + notifications.append( + { + "descriptor": {"id": "proofline/finding/withheld"}, + "level": "warning", + "message": { + "text": ( + f"Finding {finding.id} carries withheld environment" + " metadata and was omitted." + ) + }, + "properties": {"finding_id": str(finding.id), "assessment_id": assessment_id}, + } + ) + continue + if not include_resolved and finding.lifecycle_state.upper() == "RESOLVED": + continue + + rule_id = _rule_id_for(finding) + if rule_id not in rules_by_id: + rules_by_id[rule_id] = { + "id": rule_id, + "name": rule_id, + "shortDescription": {"text": f"Proofline {finding.risk_domain} finding"}, + "properties": {"risk_domain": finding.risk_domain}, + } + + primary_loc: dict[str, Any] | None = None + related_locs: list[dict[str, Any]] = [] + for ref in finding.evidence_refs: + phys = _physical_location(ref) + if phys is None: + continue + if primary_loc is None and ref.kind == "repository_file": + primary_loc = {"physicalLocation": phys} + else: + related_locs.append( + { + "id": len(related_locs) + 1, + "message": {"text": ref.label or ref.kind}, + "physicalLocation": phys, + } + ) + + severity_upper = finding.severity.upper() + level = _SEVERITY_TO_LEVEL.get(severity_upper, "note") + entry: dict[str, Any] = { + "ruleId": rule_id, + "level": level, + "message": {"text": _format_message(finding)}, + } + if primary_loc is not None: + entry["locations"] = [primary_loc] + if related_locs: + entry["relatedLocations"] = related_locs + + fingerprint = _opt_str(finding.finding_fingerprint) + if fingerprint is not None: + entry["partialFingerprints"] = {"proofline/findingFingerprint/v1": fingerprint} + + props: dict[str, Any] = { + "finding_id": str(finding.id), + "severity": finding.severity, + "risk_domain": finding.risk_domain, + "lifecycle_state": finding.lifecycle_state, + "assessment_id": assessment_id, + "environment_display_name": env_name, + "lane": lane, + } + comment_url = _opt_str(finding.github_comment_url) + if comment_url is not None: + props["github_comment_url"] = comment_url + if not isinstance(finding.evidence_class, Unset) and finding.evidence_class is not None: + props["evidence_class"] = str(finding.evidence_class) + if finding.evidence_refs: + props["evidence_refs"] = [ + { + "kind": ref.kind, + "label": ref.label, + "provenance_status": ref.provenance_status, + } + for ref in finding.evidence_refs + ] + entry["properties"] = props + + sort_uri = "" + sort_line = 0 + if primary_loc is not None: + phys_loc = primary_loc["physicalLocation"] + sort_uri = str(phys_loc["artifactLocation"]["uri"]) + sort_line = int(phys_loc.get("region", {}).get("startLine", 0)) + sort_key = (_SEVERITY_RANK.get(severity_upper, 9), sort_uri, sort_line, str(finding.id)) + results_with_keys.append((sort_key, entry)) + + results_with_keys.sort(key=lambda item: item[0]) + execution_ok = outcome.status == "COMPLETED" and not outcome.gaps + + invocation_props: dict[str, Any] = { + "outcome_status": outcome.status, + "review_url": outcome.review_url, + } + if outcome.review is not None: + invocation_props["review_id"] = str(outcome.review.id) + head_sha = _opt_str(outcome.review.head_commit_sha) + if head_sha is not None: + invocation_props["head_commit_sha"] = head_sha + base_sha = _opt_str(outcome.review.base_commit_sha) + if base_sha is not None: + invocation_props["base_commit_sha"] = base_sha + + invocation: dict[str, Any] = { + "executionSuccessful": execution_ok, + "properties": invocation_props, + } + if notifications: + invocation["toolExecutionNotifications"] = notifications + + run: dict[str, Any] = { + "tool": { + "driver": { + "name": "Proofline", + "version": VERSION, + "informationUri": "https://proofline.sh", + "rules": [rules_by_id[rid] for rid in sorted(rules_by_id)], + } + }, + "invocations": [invocation], + "results": [entry for _, entry in results_with_keys], + } + + return { + "$schema": SARIF_SCHEMA, + "version": SARIF_VERSION, + "runs": [run], + } diff --git a/tests/test_sarif.py b/tests/test_sarif.py new file mode 100644 index 00000000..25b14b10 --- /dev/null +++ b/tests/test_sarif.py @@ -0,0 +1,157 @@ +"""Tests for SARIF 2.1.0 rendering of Proofline review outcomes.""" + +from __future__ import annotations + +import json +from uuid import UUID + +import pytest + +from proofline import AssessmentGap, CheckGap, CustomerReviewDetail, ReviewOutcome, review_sarif +from tests import fixtures + + +def _review_with_findings( + findings: list[dict[str, object]], *, lane: str = "env" +) -> CustomerReviewDetail: + raw = fixtures.review("COMPLETED") + if lane == "env": + raw["assessments"][0]["findings"] = findings + raw["finding_count"] = len(findings) + else: + raw["assessments"] = [] + raw["assessment_count"] = 0 + code = fixtures.code_assessment("COMPLETED") + code["findings"] = findings + raw["code_assessment"] = code + raw["finding_count"] = len(findings) + return CustomerReviewDetail.from_dict(raw) + + +def test_review_sarif_renders_completed_env_findings_and_locations() -> None: + f1 = fixtures.finding() + f1["severity"] = "SERIOUS" + f1["finding_fingerprint"] = "fp-abc-123" + f1["remediation"] = "Move blocking I/O onto an executor." + f1["evidence_refs"] = [ + { + "kind": "repository_file", + "label": "src/handler.py:12-18", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "/src/handler.py", + "start_line": 12, + "end_line": 18, + }, + { + "kind": "repository_file", + "label": "src/db.py:4", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "src/db.py", + "start_line": 4, + "end_line": 4, + }, + ] + f2 = fixtures.finding() + f2["id"] = "00000000-0000-4000-8000-000000000099" + f2["severity"] = "WARNING" + f2["rule_refs"] = [] + f2["lifecycle_state"] = "RESOLVED" + + review = _review_with_findings([f1, f2], lane="env") + outcome = ReviewOutcome( + status="COMPLETED", + review_url="https://proofline.sh/r/1", + review=review, + ) + + doc = review_sarif(outcome) + assert doc["version"] == "2.1.0" + run = doc["runs"][0] + assert run["invocations"][0]["executionSuccessful"] is True + assert "toolExecutionNotifications" not in run["invocations"][0] + assert len(run["results"]) == 1 + + res = run["results"][0] + assert res["ruleId"] == "no-sync-io-in-handlers" + assert res["level"] == "error" + assert res["partialFingerprints"] == {"proofline/findingFingerprint/v1": "fp-abc-123"} + loc = res["locations"][0]["physicalLocation"] + assert loc["artifactLocation"]["uri"] == "src/handler.py" + assert loc["region"] == {"startLine": 12, "endLine": 18} + assert len(res["relatedLocations"]) == 1 + assert res["relatedLocations"][0]["physicalLocation"]["artifactLocation"]["uri"] == "src/db.py" + assert "Remediation: Move blocking I/O" in res["message"]["text"] + + # Deterministic JSON output + assert json.dumps(doc, sort_keys=True) == json.dumps(review_sarif(outcome), sort_keys=True) + + # include_resolved=True surfaces RESOLVED findings too + doc_all = review_sarif(outcome, include_resolved=True) + assert len(doc_all["runs"][0]["results"]) == 2 + assert doc_all["runs"][0]["results"][1]["level"] == "warning" + assert doc_all["runs"][0]["results"][1]["ruleId"] == "proofline/security" + assert "partialFingerprints" not in doc_all["runs"][0]["results"][1] + + +def test_review_sarif_marks_incomplete_and_gap_outcomes_unsuccessful() -> None: + gap = AssessmentGap( + assessment_id=UUID("00000000-0000-4000-8000-000000000004"), + status="INCOMPLETE", + reason_codes=("WORLD_UNAVAILABLE",), + incompleteness_kind="EVIDENCE_UNAVAILABLE", + checks=(CheckGap(name="iam-policy", outcome="UNKNOWN", lifecycle="GATING"),), + ) + outcome = ReviewOutcome( + status="INCOMPLETE", + review_url="https://proofline.sh/r/2", + review=None, + gaps=(gap,), + reason="Infrastructure state could not be read.", + ) + + doc = review_sarif(outcome) + inv = doc["runs"][0]["invocations"][0] + assert inv["executionSuccessful"] is False + notes = inv["toolExecutionNotifications"] + assert len(notes) == 2 + assert notes[0]["descriptor"]["id"] == "proofline/outcome/incomplete" + assert notes[1]["descriptor"]["id"] == "proofline/assessment/gap" + assert "WORLD_UNAVAILABLE" in notes[1]["message"]["text"] + assert doc["runs"][0]["results"] == [] + + +def test_review_sarif_supports_code_lane_rejects_traversal_and_withheld() -> None: + f_ok = fixtures.finding() + f_ok["severity"] = "WARNING" + f_ok["evidence_refs"] = [ + { + "kind": "repository_file", + "label": "../escape.py:1", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "../escape.py", + "start_line": 1, + } + ] + f_withheld = fixtures.finding() + f_withheld["id"] = "00000000-0000-4000-8000-000000000088" + f_withheld["risk_domain"] = "[withheld: environment value]" + + review = _review_with_findings([f_ok, f_withheld], lane="code") + outcome = ReviewOutcome( + status="COMPLETED", + review_url="https://proofline.sh/r/3", + review=review, + ) + + doc = review_sarif(outcome) + run = doc["runs"][0] + assert len(run["results"]) == 1 + assert "locations" not in run["results"][0] + assert run["results"][0]["properties"]["lane"] == "code" + notes = run["invocations"][0]["toolExecutionNotifications"] + assert any(n["descriptor"]["id"] == "proofline/finding/withheld" for n in notes) + + +def test_review_sarif_rejects_invalid_input_type() -> None: + with pytest.raises(TypeError): + review_sarif("not-an-outcome") # type: ignore[arg-type]