diff --git a/README.md b/README.md index 250fb32e..5eaffee2 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,33 @@ with ProoflineClient() as client: Use `async for` with `AsyncProoflineClient`. Each yielded page retains its raw text, decoded rows, and metadata; CSV pages retain their individual headers. Pass `cursor=` to resume an export. Iteration stops only when the server omits the next cursor, including when an intermediate page has no rows. Empty or repeated continuation cursors raise `ProoflineError` with type `urn:proofline:sdk:invalid-pagination`, and the page that carries such a cursor is never yielded. The default bound is 100 pages; set `max_pages` to an integer from 1 to 1000. Exhausting that bound while a cursor remains raises `urn:proofline:sdk:pagination-limit`, so a partial export cannot silently appear complete. Stop iteration early when only a prefix is needed. +## GitLab Code Quality + +`review_codequality` turns a completed code review into the JSON list GitLab's Code Quality report reads. `SERIOUS` is `critical` and `WARNING` is `minor`. A `RESOLVED` finding is left out. A file line is included only for a `repository_file` reference that was a verified read of the review's head commit. A review that is not `COMPLETED` raises `ProoflineError`, so an unfinished review is not uploaded as a clean report. + +```python +import json +from pathlib import Path + +from proofline import ProoflineClient, review_codequality + +with ProoflineClient() as client: + outcome = client.wait_for_review(organization_id, review_id) + Path("gl-code-quality-report.json").write_text( + json.dumps(review_codequality(outcome)), + encoding="utf-8", + ) +``` + +```yaml +proofline: + script: python review.py + artifacts: + when: always + reports: + codequality: gl-code-quality-report.json +``` + ## Coverage uploads To upload coverage reports from CI, use a repository-restricted token with `coverage:write` and current repository write access. Name the full commit SHA that the tests ran on. Send 1 to 50 LCOV, Cobertura XML, JaCoCo XML, or Go cover reports in a JSON body of at most 30 MiB. diff --git a/proofline/__init__.py b/proofline/__init__.py index 48902066..ed16bab6 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,6 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ConfigurationProblem, ProoflineError, RevisionResponse, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .codequality import review_codequality from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -69,6 +70,7 @@ "ReviewFilters", "ReviewOutcome", "ReviewPage", + "review_codequality", "RevisionResponse", "RunNowMode", "RunNowRefusal", diff --git a/proofline/codequality.py b/proofline/codequality.py new file mode 100644 index 00000000..5e584c16 --- /dev/null +++ b/proofline/codequality.py @@ -0,0 +1,141 @@ +"""GitLab Code Quality reports for a completed code review.""" + +from __future__ import annotations + +import re +from typing import Any + +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, Unset +from ._transport import ProoflineError +from .outcomes import ReviewOutcome + +_SEVERITY = {"SERIOUS": "critical", "WARNING": "minor"} +_HEX_HEAD = re.compile(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})") +_BIDI = frozenset("\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069") + + +def review_codequality(outcome: ReviewOutcome) -> list[dict[str, Any]]: + """Return GitLab Code Quality JSON for a completed code review. + + ``SERIOUS`` becomes ``critical`` and ``WARNING`` becomes ``minor``. A + ``RESOLVED`` finding is left out. A location is included only for a + ``repository_file`` reference that was a verified read of the review's + head commit. Any other outcome status raises ``ProoflineError``, so an + unfinished review is not uploaded as a clean report. + """ + + if not isinstance(outcome, ReviewOutcome): + raise TypeError("outcome must be a ReviewOutcome") + if outcome.status != "COMPLETED" or outcome.review is None: + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "A review that is not COMPLETED cannot be exported as Code Quality.", + ) + code = outcome.review.code_assessment + if not isinstance(code, CustomerCodeAssessment): + return [] + head = _head(outcome.review, code) + rows: list[dict[str, Any]] = [] + for finding in code.findings: + row = _row(finding, head) + if row is not None: + rows.append(row) + return rows + + +def _head(review: object, code: CustomerCodeAssessment) -> str: + head = code.head_commit_sha + if not isinstance(head, str) or not _HEX_HEAD.fullmatch(head): + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The code assessment names no head commit.", + ) + recorded = getattr(review, "head_commit_sha", None) + if isinstance(recorded, str) and recorded and recorded.lower() != head.lower(): + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The code assessment is pinned to another head commit.", + ) + return head.lower() + + +def _text(value: object) -> str | None: + if isinstance(value, Unset) or value is UNSET or not isinstance(value, str): + return None + text = value.strip() + return text or None + + +def _valid_path(path: str) -> bool: + if path.startswith(("/", "\\")): + return False + 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 _line(value: object) -> int | None: + if isinstance(value, bool) or isinstance(value, Unset) or type(value) is not int: + return None + if value < 1: + return None + return value + + +def _location(finding: CustomerFinding, head: str) -> tuple[str, int, int] | None: + for ref in finding.evidence_refs: + if not isinstance(ref, CustomerEvidenceRef) or ref.kind != "repository_file": + continue + if ref.provenance_status != "VERIFIED_REPOSITORY_READ": + continue + if isinstance(ref.companion_repository, str) and ref.companion_repository: + continue + commit = ref.commit_sha + if not isinstance(commit, str) or not _HEX_HEAD.fullmatch(commit): + continue + if commit.lower() != head: + continue + path = _text(ref.repository_path) + start = _line(ref.start_line) + if path is None or not _valid_path(path) or start is None: + continue + end = ref.end_line + if isinstance(end, Unset) or end is None: + end = start + elif _line(end) is None or end < start: + continue + return path, start, end + return None + + +def _row(finding: CustomerFinding, head: str) -> dict[str, Any] | None: + if not isinstance(finding, CustomerFinding): + return None + if finding.severity not in _SEVERITY: + raise ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + f"Finding {finding.id} has an unsupported severity; Code Quality export refused.", + ) + if finding.lifecycle_state == "RESOLVED": + return None + claim = _text(finding.claim) + check_name = _text(finding.risk_domain) + located = _location(finding, head) + if claim is None or check_name is None or located is None: + return None + path, start, end = located + fingerprint = _text(finding.finding_fingerprint) or str(finding.id) + return { + "description": claim, + "check_name": check_name, + "fingerprint": fingerprint, + "severity": _SEVERITY[finding.severity], + "location": {"path": path, "lines": {"begin": start, "end": end}}, + } diff --git a/tests/test_codequality.py b/tests/test_codequality.py new file mode 100644 index 00000000..a25a3bc2 --- /dev/null +++ b/tests/test_codequality.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +from types import SimpleNamespace +from uuid import UUID + +import pytest + +from proofline._generated.models.customer_code_assessment import CustomerCodeAssessment +from proofline._generated.models.customer_evidence_ref import CustomerEvidenceRef +from proofline._generated.models.customer_finding import CustomerFinding +from proofline._transport import ProoflineError +from proofline.codequality import review_codequality +from proofline.outcomes import ReviewOutcome + +FINDING_ID = UUID("11111111-1111-4111-8111-111111111111") +ASSESSMENT_ID = UUID("22222222-2222-4222-8222-222222222222") +HEAD = "b" * 40 + + +def finding(**overrides: object) -> CustomerFinding: + values: dict[str, object] = { + "claim": "The bucket policy allows a public read.", + "comment_reactions": [], + "evidence_refs": [file_ref()], + "id": FINDING_ID, + "impact": "Objects can be read without authentication.", + "lifecycle_state": "NEW", + "risk_domain": "terraform", + "rule_refs": [], + "severity": "SERIOUS", + "symbols": [], + "finding_fingerprint": "bucket-public-read", + } + values.update(overrides) + return CustomerFinding(**values) # type: ignore[arg-type] + + +def file_ref(**overrides: object) -> CustomerEvidenceRef: + values: dict[str, object] = { + "kind": "repository_file", + "label": "terraform/bucket.tf:12", + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": "terraform/bucket.tf", + "start_line": 12, + "end_line": 14, + "commit_sha": HEAD, + } + values.update(overrides) + return CustomerEvidenceRef(**values) # type: ignore[arg-type] + + +def outcome( + findings: list[CustomerFinding] | None, + *, + status: str = "COMPLETED", +) -> ReviewOutcome: + code = None + if findings is not None: + code = CustomerCodeAssessment( + base_commit_sha="a" * 40, + findings=findings, + head_commit_sha=HEAD, + id=ASSESSMENT_ID, + status="COMPLETED", + ) + review = SimpleNamespace(code_assessment=code, head_commit_sha=HEAD) + return ReviewOutcome( + status=status, # type: ignore[arg-type] + review_url="https://proofline.sh/reviews/1", + review=review, + ) + + +def test_serious_finding_becomes_a_gitlab_code_quality_entry() -> None: + rows = review_codequality(outcome([finding()])) + assert rows == [ + { + "description": "The bucket policy allows a public read.", + "check_name": "terraform", + "fingerprint": "bucket-public-read", + "severity": "critical", + "location": {"path": "terraform/bucket.tf", "lines": {"begin": 12, "end": 14}}, + } + ] + + +def test_warning_is_minor_and_uses_the_finding_id_without_a_fingerprint() -> None: + rows = review_codequality(outcome([finding(severity="WARNING", finding_fingerprint=None)])) + assert rows[0]["severity"] == "minor" + assert rows[0]["fingerprint"] == str(FINDING_ID) + + +def test_a_finding_without_a_verified_head_file_is_left_out() -> None: + bare = finding( + evidence_refs=[ + CustomerEvidenceRef( + kind="workflow_run", + label="ci", + provenance_status="RECORDED_READ", + ) + ] + ) + other_commit = finding(evidence_refs=[file_ref(commit_sha="c" * 40)]) + unresolved = finding(evidence_refs=[file_ref(provenance_status="LEGACY_UNSTRUCTURED")]) + parent = finding(evidence_refs=[file_ref(repository_path="../bucket.tf")]) + resolved = finding(lifecycle_state="RESOLVED") + rows = review_codequality( + outcome([bare, other_commit, unresolved, parent, resolved, finding()]) + ) + assert [row["fingerprint"] for row in rows] == ["bucket-public-read"] + + +def test_no_code_assessment_is_an_empty_report() -> None: + assert review_codequality(outcome(None)) == [] + + +def test_a_mismatched_head_is_refused() -> None: + review = outcome([finding()]) + review.review.head_commit_sha = "d" * 40 + with pytest.raises(ProoflineError): + review_codequality(review) + + +def test_unfinished_review_is_refused() -> None: + with pytest.raises(ProoflineError): + review_codequality(outcome([finding()], status="INCOMPLETE")) + + +def test_unknown_severity_is_refused() -> None: + with pytest.raises(ProoflineError): + review_codequality(outcome([finding(severity="NOTE")])) + + +def test_outcome_type_is_required() -> None: + with pytest.raises(TypeError): + review_codequality("review") # type: ignore[arg-type]