Skip to content
Open
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
2 changes: 2 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -86,4 +87,5 @@
"UploadedReport",
"__version__",
"models",
"review_sarif",
]
332 changes: 332 additions & 0 deletions proofline/sarif.py
Original file line number Diff line number Diff line change
@@ -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],
}
Loading