diff --git a/README.md b/README.md index 250fb32e..9eb5f24a 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..391daa34 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -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 @@ -67,6 +68,7 @@ "RerunResponse", "ReviewFilters", "ReviewOutcome", + "review_junit", "ReviewPage", "RunNowMode", "RunNowRefusal", diff --git a/proofline/junit.py b/proofline/junit.py new file mode 100644 index 00000000..11e252ae --- /dev/null +++ b/proofline/junit.py @@ -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 ````. +""" + +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 ````s, open findings + below it are ````, 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 ```` 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" diff --git a/tests/test_junit.py b/tests/test_junit.py new file mode 100644 index 00000000..55f52243 --- /dev/null +++ b/tests/test_junit.py @@ -0,0 +1,203 @@ +"""JUnit XML keeps findings, locations and incompleteness visible to CI.""" + +from __future__ import annotations + +import xml.etree.ElementTree as ET +from typing import Any +from uuid import UUID + +import pytest + +from proofline import ProoflineError, review_junit +from proofline._generated.models import CustomerReviewDetail +from proofline.outcomes import ReviewOutcome, outcome + +from .fixtures import REVIEW, assessment, code_assessment, finding, review + +HEAD = "a" * 40 +URL = "https://proofline.sh/reviews/synthetic" + + +def ref( + path: str = "app/main.py", start: int = 12, end: int | None = 14, **overrides: Any +) -> dict[str, Any]: + return { + "kind": "repository_file", + "label": path, + "provenance_status": "VERIFIED_REPOSITORY_READ", + "commit_sha": HEAD, + "repository_path": path, + "start_line": start, + "end_line": end, + **overrides, + } + + +def item( + claim: str, + severity: str = "SERIOUS", + lifecycle: str = "NEW", + refs: list[dict[str, Any]] | None = None, + number: int = 0, +) -> dict[str, Any]: + return { + **finding(), + "id": str(UUID(int=0x10 + number)), + "claim": claim, + "severity": severity, + "risk_domain": "logic", + "lifecycle_state": lifecycle, + "evidence_refs": refs if refs is not None else [], + } + + +def code_review(findings: list[dict[str, Any]], status: str = "COMPLETED") -> CustomerReviewDetail: + code = {**code_assessment(status), "findings": findings} + body = { + **review(), + "assessment_count": 0, + "assessments": [], + "code_assessment": code, + "head_commit_sha": HEAD, + "base_commit_sha": "b" * 40, + } + return CustomerReviewDetail.from_dict(body) + + +def env_review(findings: list[dict[str, Any]], **assessment_overrides: Any) -> CustomerReviewDetail: + body = {**review(), "head_commit_sha": HEAD} + body["assessments"] = [{**assessment(), "findings": findings, **assessment_overrides}] + return CustomerReviewDetail.from_dict(body) + + +def render(result: ReviewOutcome | None, **kwargs: Any) -> ET.Element: + assert result is not None + document = review_junit(result, **kwargs) + assert document.startswith(" list[ET.Element]: + found = [s for s in root.findall("testsuite") if s.get("name") == suite] + assert len(found) == 1, [s.get("name") for s in root.findall("testsuite")] + return found[0].findall("testcase") + + +def test_open_findings_fail_with_head_locations() -> None: + detail = code_review( + [ + item("Unchecked None on the refund path", refs=[ref(), ref()], number=1), + item("Retry loop never backs off", severity="WARNING", number=2), + ] + ) + root = render(outcome(detail, URL, review_id=REVIEW)) + assert root.get("failures") == "2" and root.get("errors") == "0" + first, second = cases(root, "Code") + assert first.get("classname") == "proofline.logic" + assert first.get("file") == "app/main.py" and first.get("line") == "12" + failure = first.find("failure") + assert failure is not None and failure.get("type") == "SERIOUS" + assert failure.text is not None and failure.text.count("Location: app/main.py:12-14") == 1 + assert URL in failure.text + assert second.find("failure") is not None and second.get("file") is None + review_case = cases(root, "Proofline review")[0] + assert review_case.find("error") is None + + +@pytest.mark.parametrize( + "override", + [ + {"commit_sha": "c" * 40}, + {"provenance_status": "UNVERIFIED"}, + {"repository_path": "../etc/passwd"}, + {"repository_path": "app/‮main.py"}, + {"start_line": 0}, + {"end_line": 3}, + {"kind": "log_excerpt"}, + {"companion_repository": "other/repo"}, + ], +) +def test_location_needs_a_verified_read_at_the_head(override: dict[str, Any]) -> None: + detail = code_review([item("Claim", refs=[ref(**override)])]) + case = cases(render(outcome(detail, URL)), "Code")[0] + assert case.get("file") is None and case.find("failure") is not None + + +def test_threshold_skips_lower_findings_and_resolved_ones_pass() -> None: + detail = code_review( + [ + item("Serious", "SERIOUS", number=1), + item("Warning", "WARNING", number=2), + item("Note", "NOTE", number=3), + item("Fixed", "CRITICAL", lifecycle="RESOLVED", number=4), + ] + ) + result = outcome(detail, URL) + default = {c.get("name"): c for c in cases(render(result), "Code")} + assert default["Warning"].find("failure") is not None + assert default["Note"].find("skipped") is not None + assert ( + default["Fixed"].find("failure") is None and default["Fixed"].find("system-out") is not None + ) + strict = {c.get("name"): c for c in cases(render(result, fail_on="SERIOUS"), "Code")} + assert strict["Warning"].find("skipped") is not None + assert strict["Serious"].find("failure") is not None + noisy = render(result, fail_on="NOTE") + assert noisy.get("failures") == "3" and noisy.get("skipped") == "0" + + +def test_an_incomplete_review_is_never_green() -> None: + detail = env_review( + [], + status="INCOMPLETE", + incompleteness_kind="ENVIRONMENT_UNREACHABLE", + checks={ + "families": [ + { + "name": "iam", + "files": [], + "outcome": "UNRESOLVED", + "lifecycle": "GATING", + "unresolved_reason": "NEEDS_EVIDENCE", + } + ], + "receipt_recorded": True, + "status": "BLOCKED", + }, + ) + result = outcome(detail, URL) + assert result is not None and result.status == "INCOMPLETE" + root = render(result) + assert int(root.get("errors", "0")) >= 2 + gap = cases(root, "Synthetic environment")[0].find("error") + assert gap is not None and "ENVIRONMENT_UNREACHABLE" in (gap.text or "") + assert "Check iam: UNRESOLVED (GATING), NEEDS_EVIDENCE" in (gap.text or "") + assert cases(root, "Proofline review")[0].find("error") is not None + + +def test_a_completed_review_without_findings_passes() -> None: + root = render(outcome(env_review([]), URL)) + assert (root.get("tests"), root.get("failures"), root.get("errors")) == ("1", "0", "0") + + +def test_a_timed_out_wait_without_a_review_is_an_error() -> None: + root = render(ReviewOutcome("TIMED_OUT", URL, reason="The wait deadline passed.")) + error = cases(root, "Proofline review")[0].find("error") + assert error is not None and error.get("type") == "TIMED_OUT" + assert error.get("message") == "The wait deadline passed." + + +def test_markup_and_control_characters_stay_well_formed() -> None: + claim = 'Unescaped