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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,31 @@ the wait returns `TIMED_OUT` immediately.

`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head.

## JUnit report for CI

GitLab merge request test reports, Jenkins, Azure DevOps, CircleCI and Buildkite read JUnit XML. `review_junit` turns the outcome of `wait_for_review` into that format, so findings appear beside the test results a team already watches. It needs no extra request.

```python
from pathlib import Path

from proofline import review_junit

outcome = client.wait_for_review(organization_id, review_id, head_commit_sha=head_commit_sha)
Path("proofline-junit.xml").write_text(review_junit(outcome, fail_on="SERIOUS"), encoding="utf-8")
```

```yaml
# .gitlab-ci.yml
proofline:
script: python review.py
artifacts:
when: always
reports:
junit: proofline-junit.xml
```

Each assessment is a test suite, named `Code` or after its environment, and each finding is a test case. An open finding at or above `fail_on` (default `WARNING`; `NOTE`, `WARNING`, `SERIOUS`, `CRITICAL`) is a failure, an open finding below it is skipped, and a `RESOLVED` finding passes. A test case carries `file` and `line` only for a verified repository read at the review's head commit, the same rule the CLI's SARIF output uses. Every assessment gap, and any outcome other than `COMPLETED`, is an error, so a review that did not finish never produces a passing report. An unsupported severity raises `ProoflineError`.

## Review exports

`export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`.
Expand Down
2 changes: 2 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from ._transport import ProoflineError, RunNowRefusal
from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters
from .exports import ExportDataset, ExportFormat, ExportPage
from .junit import review_junit
from .knowledge import KnowledgeResult
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome

Expand Down Expand Up @@ -67,6 +68,7 @@
"RerunResponse",
"ReviewFilters",
"ReviewOutcome",
"review_junit",
"ReviewPage",
"RunNowMode",
"RunNowRefusal",
Expand Down
221 changes: 221 additions & 0 deletions proofline/junit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
"""JUnit XML for one review outcome, for CI systems that read test reports.

GitLab merge request test reports, Jenkins, Azure DevOps, CircleCI and Buildkite
show JUnit XML natively, so a review's findings can appear next to the test
results a team already reads. Each assessment becomes a test suite and each
finding a test case. A review that did not complete never renders as a passing
report: every recorded gap becomes an ``<error>``.
"""

from __future__ import annotations

import re
import xml.etree.ElementTree as ET
from collections.abc import Iterable
from typing import Literal

from ._generated.models.customer_evidence_ref import CustomerEvidenceRef
from ._generated.models.customer_finding import CustomerFinding
from ._generated.types import Unset
from ._transport import ProoflineError
from .outcomes import AssessmentGap, ReviewOutcome, _code_assessment, text

Severity = Literal["NOTE", "WARNING", "SERIOUS", "CRITICAL"]
_RANK: dict[str, int] = {"NOTE": 0, "WARNING": 1, "SERIOUS": 2, "CRITICAL": 3}
_HEX_HEAD = re.compile(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})")
# Characters XML 1.0 cannot carry at all; ElementTree would write them as-is.
_XML_ILLEGAL = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f￾￿]")
_BIDI = frozenset("‎‏‪‫‬‭‮⁦⁧⁨⁩")
_NAME_LIMIT = 200


def _clean(value: object) -> str:
return _XML_ILLEGAL.sub("�", value) if isinstance(value, str) else ""


def _one_line(value: object) -> str:
return " ".join(_clean(value).split())


def _short(value: str) -> str:
return value if len(value) <= _NAME_LIMIT else value[: _NAME_LIMIT - 1] + "…"


def _valid_path(path: str) -> bool:
return not any(part in ("", ".", "..") for part in path.split("/")) and not any(
ch in _BIDI or ch in "\\:" or ord(ch) < 0x20 or ord(ch) == 0x7F for ch in path
)


def _location(reference: CustomerEvidenceRef, head: str | None) -> tuple[str, int, int] | None:
"""The file and lines a reference places a finding on, under the CLI's SARIF rules."""
if head is None or reference.kind != "repository_file":
return None
if isinstance(reference.companion_repository, str) and reference.companion_repository:
return None
if reference.provenance_status != "VERIFIED_REPOSITORY_READ":
return None
commit = reference.commit_sha
if not isinstance(commit, str) or not _HEX_HEAD.fullmatch(commit) or commit.lower() != head:
return None
path = reference.repository_path
start = reference.start_line
if not isinstance(path, str) or not _valid_path(path):
return None
if not isinstance(start, int) or isinstance(start, bool) or start < 1:
return None
end = reference.end_line
end = start if isinstance(end, Unset) or end is None else end
if not isinstance(end, int) or isinstance(end, bool) or end < start:
return None
return path, start, end


def _counts(suite: ET.Element) -> None:
cases = suite.findall("testcase")
suite.set("tests", str(len(cases)))
for tag, attribute in (("failure", "failures"), ("error", "errors"), ("skipped", "skipped")):
suite.set(attribute, str(sum(1 for case in cases if case.find(tag) is not None)))


def _suite(parent: ET.Element, name: str) -> ET.Element:
return ET.SubElement(parent, "testsuite", name=_short(_one_line(name)) or "Assessment")


def _case(suite: ET.Element, classname: str, name: str, seen: dict[str, int]) -> ET.Element:
name = _short(_one_line(name)) or "Untitled finding"
seen[name] = seen.get(name, 0) + 1
if seen[name] > 1:
name = f"{name} #{seen[name]}"
return ET.SubElement(suite, "testcase", classname=classname, name=name)


def _finding_case(
suite: ET.Element,
finding: CustomerFinding,
head: str | None,
fail_rank: int,
review_url: str,
seen: dict[str, int],
) -> None:
severity = finding.severity
if severity not in _RANK:
raise ProoflineError(
0,
"urn:proofline:sdk:invalid-response",
f"Finding {finding.id} has an unsupported severity; JUnit export refused.",
)
domain = _one_line(finding.risk_domain) or "finding"
case = _case(suite, f"proofline.{domain}", finding.claim, seen)
locations = []
for reference in finding.evidence_refs:
found = _location(reference, head)
if found is not None and found not in locations:
locations.append(found)
if locations:
case.set("file", locations[0][0])
case.set("line", str(locations[0][1]))
lines = [f"Severity: {severity}", f"Lifecycle: {_one_line(finding.lifecycle_state)}"]
lines.append(f"Impact: {_clean(finding.impact)}")
remediation = text(finding.remediation)
if remediation:
lines.append(f"Remediation: {_clean(remediation)}")
lines.extend(
f"Location: {path}:{start}" + ("" if end == start else f"-{end}")
for path, start, end in locations
)
lines.append(f"Finding: {finding.id}")
lines.append(f"Review: {review_url}")
body = "\n".join(lines)
if finding.lifecycle_state == "RESOLVED":
ET.SubElement(case, "system-out").text = body
elif _RANK[severity] >= fail_rank:
failure = ET.SubElement(case, "failure", type=severity)
failure.set("message", _short(_one_line(finding.claim)) or severity)
failure.text = body
else:
skipped = ET.SubElement(case, "skipped")
skipped.set("message", f"{severity} is below the failure threshold")
skipped.text = body


def _gap_case(suite: ET.Element, gap: AssessmentGap, seen: dict[str, int]) -> None:
case = _case(suite, "proofline.assessment", "Assessment completed", seen)
reasons = ", ".join(gap.reason_codes) or gap.status
error = ET.SubElement(case, "error", type=_one_line(gap.status) or "UNKNOWN")
error.set("message", _short(_one_line(reasons)))
lines = [f"Status: {gap.status}", f"Reasons: {reasons}"]
if gap.incompleteness_kind:
lines.append(f"Incompleteness: {gap.incompleteness_kind}")
if gap.release_evidence_gap:
lines.append(f"Release evidence gap: {gap.release_evidence_gap}")
lines.extend(
f"Check {check.name}: {check.outcome} ({check.lifecycle})"
+ (f", {check.unresolved_reason}" if check.unresolved_reason else "")
for check in gap.checks
)
error.text = _clean("\n".join(lines))


def review_junit(result: ReviewOutcome, *, fail_on: Severity = "WARNING") -> str:
"""Render ``result`` as a JUnit XML document.

Open findings at or above ``fail_on`` become ``<failure>``s, open findings
below it are ``<skipped>``, and resolved findings pass. Locations are given
only for verified repository reads at the review's head commit, the same
rule the CLI's SARIF output uses. Any assessment gap, and any outcome other
than ``COMPLETED``, becomes an ``<error>`` so an incomplete review cannot
look green in CI.
"""
if fail_on not in _RANK:
raise ValueError(f"fail_on must be one of {', '.join(_RANK)}")
fail_rank = _RANK[fail_on]
root = ET.Element("testsuites", name="Proofline review")
review = result.review
head_text = text(review.head_commit_sha) if review is not None else None
head = head_text.lower() if head_text and _HEX_HEAD.fullmatch(head_text) else None

summary = _suite(root, "Proofline review")
review_case = ET.SubElement(
summary, "testcase", classname="proofline.review", name="Review completed"
)
if result.status != "COMPLETED":
error = ET.SubElement(review_case, "error", type=result.status)
error.set("message", _short(_one_line(result.reason or result.status)))
error.text = _clean(f"Outcome: {result.status}\nReview: {result.review_url}")

gaps_by_assessment: dict[object, list[AssessmentGap]] = {}
for gap in result.gaps:
gaps_by_assessment.setdefault(gap.assessment_id, []).append(gap)
suites: list[tuple[str, object, Iterable[CustomerFinding]]] = []
if review is not None:
code = _code_assessment(review)
if code is not None:
suites.append(("Code", code.id, code.findings))
for assessment in review.assessments:
suites.append((assessment.environment_display_name, assessment.id, assessment.findings))
used: set[object] = set()
for name, assessment_id, findings in suites:
suite = _suite(root, name)
seen: dict[str, int] = {}
for finding in findings:
_finding_case(suite, finding, head, fail_rank, result.review_url, seen)
for gap in gaps_by_assessment.get(assessment_id, ()):
_gap_case(suite, gap, seen)
used.add(assessment_id)
seen_summary: dict[str, int] = {"Review completed": 1}
for assessment_id, gaps in gaps_by_assessment.items():
if assessment_id in used:
continue
for gap in gaps:
_gap_case(summary, gap, seen_summary)

for suite in root.findall("testsuite"):
_counts(suite)
for attribute in ("tests", "failures", "errors", "skipped"):
root.set(
attribute,
str(sum(int(suite.get(attribute, "0")) for suite in root.findall("testsuite"))),
)
ET.indent(root)
return ET.tostring(root, encoding="unicode", xml_declaration=True) + "\n"
Loading