diff --git a/README.md b/README.md index 721949da..a1b42973 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,31 @@ if outcome.status != "COMPLETED": `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. +## Reviewing local changes + +`request_patch_review_from_git` reviews a checkout's unpushed changes, as `proofline review` does in the CLI. Nothing is pushed: GitHub needs only the base commit. + +```python +from proofline import NoLocalChanges, SecretInPatch + +try: + requested = client.request_patch_review_from_git(organization_id, repository_id, cwd=".") +except NoLocalChanges: + print("Nothing to review.") +except SecretInPatch as refusal: + print(refusal) # names the path, line and kind of credential, never the credential +else: + outcome = client.wait_for_review(organization_id, requested.review_id) +``` + +By default the patch compares tracked work-tree files, staged or not, with the merge-base of `HEAD` and its upstream branch, or with `origin`'s default branch when there is no upstream. `selection="staged"` reads only the index and `selection="untracked"` also adds untracked files Git does not ignore. `base=` names another base, and `base=` with `head=` reviews only the committed range. Revisions resolve once to full commit SHAs. `verify_finding_ids` re-verifies up to 20 open findings against the patch, and `trigger_source` names the Git hook that sent it. + +Git runs once under fixed options, so personal configuration such as `diff.noprefix`, `color.ui`, `diff.relative`, `diff.external` or copy detection cannot change the patch. Selected bytes are collected in a copied index, so the repository's index is never modified, and Git takes no optional locks, so the call can run inside a commit hook. The async client runs Git in a worker thread. + +Each refusal raises a `LocalChangesError`, a `ValueError`, before any request: no changes (`NoLocalChanges`), a binary change, symbolic link, submodule or unresolved conflict, text or paths that are not UTF-8, more than 3,000 files, or a patch over 5 MiB. Every uploaded line is then checked as the CLI checks it. `SecretInPatch` refuses a `.env` or `.env.*` path, a private-key marker, or a listed credential shape (AWS access-key IDs, GitHub, Slack, Google, Stripe live, model-provider and Proofline tokens) on an added, removed or context line or a hunk heading. Pass an exact repository-relative path in `allow_paths` to skip it. The check recognizes only these shapes: finding none says nothing else about the patch. + +`read_local_changes` and `check_secrets` are exported for callers who build the request themselves; `LocalPatch.request()` returns the `PatchReviewRequest` body. + ## 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..e6672cb5 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -36,6 +36,16 @@ from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult +from .local_changes import ( + LocalChangesError, + LocalPatch, + LocalSelection, + NoLocalChanges, + PatchPath, + SecretInPatch, + check_secrets, + read_local_changes, +) from .outcomes import AssessmentGap, CheckGap, ReviewOutcome __all__ = [ @@ -57,6 +67,11 @@ "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", + "LocalChangesError", + "LocalPatch", + "LocalSelection", + "NoLocalChanges", + "PatchPath", "PatchReviewRequest", "PatchReviewResponse", "PatchTriggerSource", @@ -74,10 +89,13 @@ "RunNowResponse", "ScanRequestBody", "ScanResponse", + "SecretInPatch", "SecretStr", "StartSession", "StopResponse", "UploadedReport", "__version__", + "check_secrets", "models", + "read_local_changes", ] diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..94298e90 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,8 +3,10 @@ from __future__ import annotations import math +import os from asyncio import sleep as async_sleep -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Sequence +from functools import partial from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -12,6 +14,7 @@ from urllib.parse import quote from uuid import UUID +import anyio import httpx2 from pydantic import SecretStr @@ -57,6 +60,7 @@ from ._generated.models.finding_fix_prompt_type_1 import FindingFixPromptType1 from ._generated.models.patch_review_request import PatchReviewRequest from ._generated.models.patch_review_response import PatchReviewResponse +from ._generated.models.patch_trigger_source import PatchTriggerSource from ._generated.models.repository_guidance import RepositoryGuidance from ._generated.models.repository_names import RepositoryNames from ._generated.models.rerun_response import RerunResponse @@ -75,6 +79,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient +from .local_changes import LocalSelection, patch_review_request_from_git from .outcomes import ReviewOutcome, outcome T = TypeVar("T") @@ -468,6 +473,38 @@ def request_patch_review( body=body, ) + def request_patch_review_from_git( + self, + organization_id: UUID, + repository_id: UUID, + *, + cwd: str | os.PathLike[str] = ".", + base: str | None = None, + head: str | None = None, + selection: LocalSelection = "tracked", + remote: str = "origin", + allow_paths: Sequence[str] = (), + verify_finding_ids: Sequence[UUID] = (), + trigger_source: PatchTriggerSource | None = None, + ) -> PatchReviewResponse: + """Review a checkout's local changes the way `proofline review` does. + + Reads one Git snapshot under fixed options, refuses binary, symlink, submodule, + conflicted, non-UTF-8 and oversized changes, and refuses `.env` paths and known + credential shapes on any uploaded line, all before a request. Nothing is pushed. + """ + body = patch_review_request_from_git( + cwd, + base=base, + head=head, + selection=selection, + remote=remote, + allow_paths=allow_paths, + verify_finding_ids=verify_finding_ids, + trigger_source=trigger_source, + ) + return self.request_patch_review(organization_id, repository_id, body=body) + def upload_coverage_reports( self, organization_id: UUID, repository_id: UUID, *, body: CoverageUploadRequest ) -> CoverageUploadResponse: @@ -859,6 +896,40 @@ async def request_patch_review( body=body, ) + async def request_patch_review_from_git( + self, + organization_id: UUID, + repository_id: UUID, + *, + cwd: str | os.PathLike[str] = ".", + base: str | None = None, + head: str | None = None, + selection: LocalSelection = "tracked", + remote: str = "origin", + allow_paths: Sequence[str] = (), + verify_finding_ids: Sequence[UUID] = (), + trigger_source: PatchTriggerSource | None = None, + ) -> PatchReviewResponse: + """Review a checkout's local changes the way `proofline review` does. + + Git runs in a worker thread, so the event loop is never blocked. The same local + refusals as the synchronous client apply before any request. + """ + body = await anyio.to_thread.run_sync( + partial( + patch_review_request_from_git, + cwd, + base=base, + head=head, + selection=selection, + remote=remote, + allow_paths=allow_paths, + verify_finding_ids=verify_finding_ids, + trigger_source=trigger_source, + ) + ) + return await self.request_patch_review(organization_id, repository_id, body=body) + async def upload_coverage_reports( self, organization_id: UUID, repository_id: UUID, *, body: CoverageUploadRequest ) -> CoverageUploadResponse: diff --git a/proofline/local_changes.py b/proofline/local_changes.py new file mode 100644 index 00000000..a578d7fa --- /dev/null +++ b/proofline/local_changes.py @@ -0,0 +1,521 @@ +"""Local Git changes as a patch review request, with the CLI's secret preflight. + +`read_local_changes` builds the patch exactly as `proofline review` does: one Git snapshot +under fixed options, so personal Git configuration (prefixes, colour, external diff drivers, +copy detection, relative paths) cannot change what the server receives. Selected work-tree +bytes are collected in a copied index, so the repository's own index is never modified. + +`check_secrets` refuses a patch that touches a `.env` path or carries a known credential shape +or private-key marker on any uploaded line, before any byte leaves the checkout. It recognizes +the CLI's listed shapes only; finding none says nothing else about the patch. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Literal +from uuid import UUID + +from ._generated.models.patch_review_request import PatchReviewRequest +from ._generated.models.patch_trigger_source import PatchTriggerSource + +LocalSelection = Literal["tracked", "staged", "untracked"] + +MAX_PATCH_BYTES = 5 << 20 +MAX_PATCH_FILES = 3_000 +MAX_VERIFY_FINDINGS = 20 +_SYMLINK = "120000" +_SUBMODULE = "160000" + + +class LocalChangesError(ValueError): + """The local changes cannot be sent for review. Nothing was requested.""" + + +class NoLocalChanges(LocalChangesError): + """The selected local changes match their base, so there is nothing to review.""" + + +class SecretInPatch(LocalChangesError): + """An uploaded line or path matches a credential shape. The secret itself is never kept.""" + + def __init__( + self, + message: str, + *, + path: str, + kind: str, + line: int | None = None, + coordinate: str | None = None, + ) -> None: + super().__init__(message) + self.path = path + self.kind = kind + self.line = line + self.coordinate = coordinate + + +@dataclass(frozen=True) +class PatchPath: + """One changed file: `old` is None for an addition and `new` is None for a deletion.""" + + old: str | None + new: str | None + + +@dataclass(frozen=True) +class LocalPatch: + """A patch against one exact base commit, as the server's patch review takes it.""" + + base_commit_sha: str + patch: str + paths: tuple[PatchPath, ...] = field(repr=False) + + @property + def files(self) -> int: + return len(self.paths) + + def request( + self, + *, + verify_finding_ids: Sequence[UUID] = (), + trigger_source: PatchTriggerSource | None = None, + ) -> PatchReviewRequest: + """The request body for `request_patch_review`.""" + if isinstance(verify_finding_ids, (str, bytes)): + raise ValueError("verify_finding_ids must be a list of finding UUIDs.") + findings = [UUID(str(finding)) for finding in verify_finding_ids] + if len(findings) > MAX_VERIFY_FINDINGS: + raise ValueError(f"Re-verify at most {MAX_VERIFY_FINDINGS} findings in one request.") + if trigger_source is not None: + trigger_source = PatchTriggerSource(trigger_source) + return PatchReviewRequest( + base_commit_sha=self.base_commit_sha, + patch=self.patch, + trigger_source=trigger_source, + verify_finding_ids=findings, + ) + + +# --------------------------------------------------------------------------- Git + + +def _git(root: Path, *args: str, index: Path | None = None) -> bytes: + environment = dict(os.environ) + # A hook may run beside a commit that holds index.lock; reads never take it. + environment["GIT_OPTIONAL_LOCKS"] = "0" + if index is not None: + environment["GIT_INDEX_FILE"] = str(index) + try: + completed = subprocess.run( + ["git", "-C", str(root), *args], + capture_output=True, + env=environment, + check=False, + ) + except OSError as error: + raise LocalChangesError(f"Could not run git: {error}") from None + if completed.returncode != 0: + stderr = completed.stderr.decode("utf-8", "replace").strip() + raise LocalChangesError(f"git {args[0]} failed: {stderr}") + return completed.stdout + + +def _line(root: Path, *args: str) -> str: + return _git(root, *args).decode("utf-8", "replace").strip() + + +def _commit_sha(raw: str) -> str: + sha = raw.strip().lower() + if len(sha) not in (40, 64) or any(character not in "0123456789abcdef" for character in sha): + raise LocalChangesError(f"{raw!r} is not a full commit SHA.") + return sha + + +def _resolve(root: Path, revision: str) -> str: + # A revision that starts with "-" would be read as an option. + if not isinstance(revision, str) or not revision or revision.startswith("-"): + raise LocalChangesError(f"{revision!r} names no commit in this checkout.") + try: + return _commit_sha( + _line(root, "rev-parse", "--verify", "--quiet", f"{revision}^{{commit}}") + ) + except LocalChangesError: + raise LocalChangesError(f"{revision!r} names no commit in this checkout.") from None + + +def _merge_base(root: Path, remote: str) -> str: + for target in ("@{upstream}", f"refs/remotes/{remote}/HEAD"): + try: + _line(root, "rev-parse", "--verify", "--quiet", target) + except LocalChangesError: + continue + return _commit_sha(_line(root, "merge-base", "HEAD", target)) + raise LocalChangesError( + "The checkout has no base to review against: pass base=, set an upstream branch with " + f"`git branch --set-upstream-to`, or run `git remote set-head {remote} --auto`." + ) + + +def _copy_index(root: Path, index: Path) -> None: + current = _line(root, "rev-parse", "--path-format=absolute", "--git-path", "index") + try: + shutil.copyfile(current, index) + except FileNotFoundError: + pass # A repository with nothing staged yet has no index. + except OSError as error: + raise LocalChangesError(f"Could not copy the Git index: {error}") from None + + +def _field(output: bytes, start: int) -> tuple[bytes, int]: + end = output.find(b"\0", start) + if end < 0: + raise LocalChangesError("Could not read the patch's Git path metadata.") + return output[start:end], end + 1 + + +def _path(output: bytes, start: int) -> tuple[str, int]: + raw, start = _field(output, start) + if not raw: + raise LocalChangesError("Could not read the patch's Git path metadata.") + try: + return raw.decode("utf-8"), start + except UnicodeDecodeError: + raise LocalChangesError( + "A changed path is not UTF-8, which Proofline cannot review." + ) from None + + +def _split_raw(output: bytes) -> tuple[list[PatchPath], bytes]: + """Separates `--raw -z` records from the unchanged text patch that follows them.""" + paths: list[PatchPath] = [] + start = 0 + while start < len(output): + header, start = _field(output, start) + if not header: + break + fields = header.decode("ascii", "replace").split(" ") + if not fields[0].startswith(":") or len(fields) != 5 or not fields[4]: + raise LocalChangesError("Could not read the patch's Git path metadata.") + modes, status = (fields[0][1:], fields[1]), fields[4][0] + first, start = _path(output, start) + if status == "U": + raise LocalChangesError(f"{first!r} has an unresolved merge conflict.") + if _SYMLINK in modes: + raise LocalChangesError( + f"{first!r} is a symbolic link; Proofline reviews text changes only." + ) + if _SUBMODULE in modes: + raise LocalChangesError( + f"{first!r} is a submodule; Proofline reviews text changes only." + ) + if status == "A": + paths.append(PatchPath(None, first)) + elif status == "D": + paths.append(PatchPath(first, None)) + elif status in "MT": + paths.append(PatchPath(first, first)) + elif status == "R": + second, start = _path(output, start) + paths.append(PatchPath(first, second)) + else: + raise LocalChangesError(f"{first!r} has a change Proofline cannot review ({status}).") + return paths, output[start:] + + +def _lines(text: str) -> list[str]: + """Lines as the CLI reads them: split on LF only, one trailing CR dropped per line.""" + parts = text.split("\n") + if parts and parts[-1] == "": + parts.pop() + return [part[:-1] if part.endswith("\r") else part for part in parts] + + +def _diff(root: Path, base: str, head: str | None, index: Path | None) -> LocalPatch: + args = [ + "--literal-pathspecs", + "-c", "core.quotePath=false", + # The server accepts renames and refuses copies, whatever local configuration asks. + "-c", "diff.renames=true", + "-c", "diff.suppressBlankEmpty=false", + "diff", + ] # fmt: skip + if head is None: + args.append("--cached") + args += [ + "--raw", "-z", "--patch", "--find-renames", "--no-relative", "--no-ext-diff", + "--no-textconv", "--no-color", "--submodule=short", "--src-prefix=a/", "--dst-prefix=b/", + base, + ] # fmt: skip + if head is not None: + args.append(head) + args.append("--") + paths, raw_patch = _split_raw(_git(root, *args, index=index)) + if len(raw_patch) > MAX_PATCH_BYTES: + mebibytes = -(-len(raw_patch) // (1 << 20)) + raise LocalChangesError( + f"The local changes make a {mebibytes} MiB patch; Proofline reviews up to 5 MiB." + ) + if len(paths) > MAX_PATCH_FILES: + raise LocalChangesError( + f"The local changes include {len(paths)} files; Proofline reviews up to 3,000." + ) + try: + patch = raw_patch.decode("utf-8") + except UnicodeDecodeError: + raise LocalChangesError( + "The local changes include text that is not UTF-8, which Proofline cannot review." + ) from None + blocks = 0 + in_header = False + for line in _lines(patch): + if line.startswith("diff --git "): + blocks += 1 + in_header = True + elif line.startswith("@@ "): + in_header = False + elif in_header and (line.startswith("Binary files ") or line == "GIT binary patch"): + name = paths[blocks - 1].new or paths[blocks - 1].old if blocks <= len(paths) else "?" + raise LocalChangesError( + f"{name!r} is a binary change; Proofline reviews text changes only." + ) + if blocks != len(paths): + raise LocalChangesError("Could not read the patch's Git path metadata.") + return LocalPatch(base, patch, tuple(paths)) + + +def read_local_changes( + cwd: str | os.PathLike[str] = ".", + *, + base: str | None = None, + head: str | None = None, + selection: LocalSelection = "tracked", + remote: str = "origin", +) -> LocalPatch: + """Build the patch `proofline review` would send for this checkout. + + Without `head`, `selection` picks the local bytes: "tracked" (the default) reads tracked + work-tree files, staged or not; "staged" reads only the index; "untracked" also adds + untracked files Git does not ignore. With `head`, only the committed range `base..head` + is read. `base` defaults to the merge-base of HEAD with its upstream branch, or with + `remote`'s default branch. Revisions resolve once to full commit SHAs. + """ + if selection not in ("tracked", "staged", "untracked"): + raise ValueError("selection must be tracked, staged or untracked.") + if head is not None and (base is None or selection != "tracked"): + raise ValueError("A committed range needs base and head, and takes no selection.") + if not isinstance(remote, str) or not remote or remote.startswith("-") or "/" in remote: + raise ValueError("remote must name one Git remote, such as origin.") + try: + root = Path(_line(Path(cwd), "rev-parse", "--show-toplevel")) + except LocalChangesError as error: + raise LocalChangesError( + f"{os.fspath(cwd)!r} is not inside a Git checkout: {error}" + ) from None + if head is not None: + assert base is not None + return _diff(root, _resolve(root, base), _resolve(root, head), None) + base_sha = _resolve(root, base) if base is not None else _merge_base(root, remote) + with tempfile.TemporaryDirectory(prefix="proofline-index-") as scratch: + index = Path(scratch) / "index" + _copy_index(root, index) + add = {"tracked": "--update", "staged": None, "untracked": "--all"}[selection] + if add is not None: + _git(root, "-c", "advice.addEmbeddedRepo=false", "add", add, index=index) + return _diff(root, base_sha, None, index) + + +# ----------------------------------------------------------------- secret preflight + + +def _token_byte(character: str) -> bool: + return character.isascii() and (character.isalnum() or character in "_-.") + + +def _alphanumeric(character: str) -> bool: + return character.isascii() and character.isalnum() + + +def _upper_or_digit(character: str) -> bool: + return character.isascii() and (character.isupper() or character.isdigit()) + + +def _base32(character: str) -> bool: + return character.isascii() and (character.isupper() or character in "234567") + + +@dataclass(frozen=True) +class _TokenShape: + kind: str + prefixes: tuple[str, ...] + minimum: int + body: Callable[[str], bool] + + +# The CLI's credential prefixes (src/preflight.rs). When two rows match, the first names it. +_TOKEN_SHAPES = ( + _TokenShape("an AWS access-key ID", ("AKIA", "ASIA"), 16, _upper_or_digit), + _TokenShape("a GitHub token", ("ghp_", "gho_", "ghu_", "ghs_", "ghr_"), 36, _alphanumeric), + _TokenShape("a GitHub token", ("github_pat_",), 82, _token_byte), + _TokenShape("a GitHub token", ("ghs_",), 36, _token_byte), + _TokenShape( + "a Slack token", + ("xoxb-", "xoxa-", "xoxp-", "xoxr-", "xoxs-", "xoxe-", "xoxe.", "xapp-"), + 8, + _token_byte, + ), + _TokenShape("a Google API key", ("AIza",), 35, _token_byte), + _TokenShape("a Stripe live key", ("sk_live_", "rk_live_"), 24, _alphanumeric), + _TokenShape("a model-provider key", ("sk-",), 48, _alphanumeric), + _TokenShape( + "a model-provider key", ("sk-proj-", "sk-svcacct-", "sk-admin-", "sk-ant-"), 40, _token_byte + ), + _TokenShape("a Proofline token", ("plp_", "plo_", "pld_"), 52, _base32), +) + + +def _has_token(text: str, shape: _TokenShape) -> bool: + for prefix in shape.prefixes: + start = text.find(prefix) + while start >= 0: + body = text[start + len(prefix) : start + len(prefix) + shape.minimum] + if len(body) == shape.minimum and all(shape.body(character) for character in body): + return True + start = text.find(prefix, start + len(prefix)) + return False + + +def secret_shape(text: str) -> str | None: + """The kind of credential `text` carries, or None when it matches no listed shape.""" + if ("-----BEGIN " in text or "-----END " in text) and ( + "PRIVATE KEY-----" in text or "PRIVATE KEY BLOCK-----" in text + ): + return "a private-key marker" + for shape in _TOKEN_SHAPES: + if _has_token(text, shape): + return shape.kind + return None + + +def _hunk_start(field: str, prefix: str) -> int: + if not field.startswith(prefix): + raise LocalChangesError("Could not map the local patch to file paths and lines.") + try: + return int(field[1:].split(",")[0]) + except ValueError: + raise LocalChangesError("Could not map the local patch to file paths and lines.") from None + + +def check_secrets(changes: LocalPatch, allow_paths: Sequence[str] = ()) -> None: + """Refuse a patch that touches a `.env` path or carries a listed credential shape. + + Every uploaded line is read: added, removed and context lines, and hunk headings. A path in + `allow_paths` (exact and repository-relative) is skipped. Raises `SecretInPatch` naming the + path, line and kind of credential, never the credential itself. + """ + if isinstance(allow_paths, (str, bytes)): + raise ValueError("allow_paths must be a list of exact repository-relative paths.") + allowed = list(allow_paths) + for path in allowed: + if ( + not isinstance(path, str) + or path.startswith("/") + or any(part in ("", ".", "..") for part in path.split("/")) + ): + raise ValueError( + f"allow_paths entry {path!r} is not an exact repository-relative path." + ) + files = iter(changes.paths) + current: PatchPath | None = None + old = new = 0 + in_hunk = False + + def inspect(path: str | None, line: int, coordinate: str, text: str) -> None: + if path is None: + raise LocalChangesError("Could not map the local patch to file paths and lines.") + if path in allowed: + return + kind = secret_shape(text) + if kind is not None: + raise SecretInPatch( + f"The local patch contains {kind} at {path!r}:{line} ({coordinate}); remove it " + "before upload, or pass that exact path in allow_paths.", + path=path, + kind=kind, + line=line, + coordinate=coordinate, + ) + + for number, line in enumerate(_lines(changes.patch), start=1): + if line.startswith("diff --git "): + current = next(files, None) + if current is None: + raise LocalChangesError("Could not map the local patch to file paths and lines.") + for changed in (current.old, current.new): + if ( + changed is not None + and changed not in allowed + and any( + part == ".env" or part.startswith(".env.") for part in changed.split("/") + ) + ): + raise SecretInPatch( + f"The local patch includes the sensitive .env path {changed!r}; remove it " + "before upload, or pass that exact path in allow_paths.", + path=changed, + kind="a .env path", + ) + in_hunk = False + continue + if current is None: + raise LocalChangesError("Could not map the local patch to file paths and lines.") + if line.startswith("@@ "): + # A section heading can quote a line outside the hunk; name its patch line. + inspect(current.new or current.old, number, "patch line", line) + fields = line.split() + if len(fields) < 4 or fields[0] != "@@" or fields[3] != "@@": + raise LocalChangesError("Could not map the local patch to file paths and lines.") + old, new = _hunk_start(fields[1], "-"), _hunk_start(fields[2], "+") + in_hunk = True + elif in_hunk: + if line.startswith("+"): + inspect(current.new, new, "new line", line[1:]) + new += 1 + elif line.startswith("-"): + inspect(current.old, old, "base line", line[1:]) + old += 1 + elif line.startswith(" "): + inspect(current.new or current.old, new, "new line", line[1:]) + old += 1 + new += 1 + elif not line.startswith("\\ No newline at end of file"): + raise LocalChangesError("Could not map the local patch to file paths and lines.") + if next(files, None) is not None: + raise LocalChangesError("Could not map the local patch to file paths and lines.") + + +def patch_review_request_from_git( + cwd: str | os.PathLike[str] = ".", + *, + base: str | None = None, + head: str | None = None, + selection: LocalSelection = "tracked", + remote: str = "origin", + allow_paths: Sequence[str] = (), + verify_finding_ids: Sequence[UUID] = (), + trigger_source: PatchTriggerSource | None = None, +) -> PatchReviewRequest: + """Read, check and package local changes. Raises before anything is sent.""" + changes = read_local_changes(cwd, base=base, head=head, selection=selection, remote=remote) + if not changes.files: + raise NoLocalChanges( + f"Nothing to review: the selected local changes match {changes.base_commit_sha}." + ) + check_secrets(changes, allow_paths) + return changes.request(verify_finding_ids=verify_finding_ids, trigger_source=trigger_source) diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..88dc52dd 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -42,7 +42,14 @@ def main() -> None: raise SystemExit("ReviewFilters differs from the list_reviews query parameters.") for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "request_patch_review_from_git", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_local_changes.py b/tests/test_local_changes.py new file mode 100644 index 00000000..f13fb51b --- /dev/null +++ b/tests/test_local_changes.py @@ -0,0 +1,474 @@ +from __future__ import annotations + +import inspect +import json +import subprocess +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any +from uuid import UUID + +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + LocalChangesError, + LocalPatch, + NoLocalChanges, + PatchPath, + ProoflineClient, + ProoflineError, + SecretInPatch, + check_secrets, + read_local_changes, +) +from proofline import local_changes as local_module +from proofline._generated.models.patch_trigger_source import PatchTriggerSource + +from .fixtures import ORG, REPOSITORY, REVIEW, TOKEN +from .http_server import Reply, Request, Server + +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) +Client = ProoflineClient | AsyncProoflineClient +FINDING = UUID("00000000-0000-4000-8000-0000000000f1") + + +def git(root: Path, *args: str) -> str: + completed = subprocess.run( + ["git", "-C", str(root), *args], capture_output=True, text=True, check=True + ) + return completed.stdout.strip() + + +@pytest.fixture +def repo(tmp_path: Path) -> Path: + root = tmp_path / "repo" + root.mkdir() + git(root, "init", "-q", "-b", "main") + git(root, "config", "user.email", "sdk@example.invalid") + git(root, "config", "user.name", "SDK test") + git(root, "config", "commit.gpgsign", "false") + (root / "keep.txt").write_text("one\ntwo\n") + (root / "old.txt").write_text("rename me\n" * 8) + (root / "gone.txt").write_text("going\n") + (root / "src").mkdir() + (root / "src" / "app.py").write_text("print('hi')\n") + git(root, "add", "-A") + git(root, "commit", "-q", "-m", "base") + return root + + +def head_of(root: Path) -> str: + return git(root, "rev-parse", "HEAD") + + +def paths(patch: LocalPatch) -> list[tuple[str | None, str | None]]: + return [(path.old, path.new) for path in patch.paths] + + +# A credential built at run time, so this file never contains one literally. +def credential(prefix: str, body: str) -> str: + return "".join([prefix, body]) + + +# ----------------------------------------------------------------------------- git + + +def test_selections_pick_their_bytes_and_leave_the_index_unchanged(repo: Path) -> None: + (repo / "keep.txt").write_text("one\ntwo\nthree\n") + git(repo, "mv", "old.txt", "new.txt") + (repo / "gone.txt").unlink() + (repo / "added.txt").write_text("staged\n") + git(repo, "add", "added.txt") + (repo / "loose.txt").write_text("untracked\n") + index = (repo / ".git" / "index").read_bytes() + + tracked = read_local_changes(repo, base="HEAD") + staged = read_local_changes(repo, base="HEAD", selection="staged") + untracked = read_local_changes(repo, base="HEAD", selection="untracked") + + assert paths(tracked) == [ + (None, "added.txt"), + ("gone.txt", None), + ("keep.txt", "keep.txt"), + ("old.txt", "new.txt"), + ] + assert paths(staged) == [(None, "added.txt"), ("old.txt", "new.txt")] + # Git orders files by path, so the untracked file sorts before the rename's new name. + assert paths(untracked) == [ + (None, "added.txt"), + ("gone.txt", None), + ("keep.txt", "keep.txt"), + (None, "loose.txt"), + ("old.txt", "new.txt"), + ] + assert tracked.base_commit_sha == head_of(repo) + assert (repo / ".git" / "index").read_bytes() == index + + +def test_personal_git_configuration_cannot_change_the_patch(repo: Path) -> None: + for key, value in { + "diff.noprefix": "true", + "diff.mnemonicPrefix": "true", + "color.ui": "always", + "color.diff": "always", + "diff.relative": "true", + "diff.renames": "copies", + "diff.external": "this-command-does-not-exist", + "core.quotePath": "true", + }.items(): + git(repo, "config", key, value) + (repo / "copy.txt").write_text((repo / "old.txt").read_text()) + (repo / "src" / "app.py").write_text("print('changed')\n") + (repo / "naïve.txt").write_text("unicode path\n") + git(repo, "add", "-A") + + patch = read_local_changes(repo / "src", base="HEAD") + + assert "\x1b[" not in patch.patch + assert "copy from" not in patch.patch + assert "diff --git a/src/app.py b/src/app.py" in patch.patch + assert "diff --git a/naïve.txt b/naïve.txt" in patch.patch + assert paths(patch) == [(None, "copy.txt"), (None, "naïve.txt"), ("src/app.py", "src/app.py")] + + +def test_default_base_is_the_merge_base_with_the_remote_default_branch(repo: Path) -> None: + base = head_of(repo) + git(repo, "update-ref", "refs/remotes/origin/main", base) + git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + (repo / "keep.txt").write_text("committed locally\n") + git(repo, "commit", "-q", "-am", "local work") + (repo / "src" / "app.py").write_text("print('uncommitted')\n") + + patch = read_local_changes(repo) + + assert patch.base_commit_sha == base + assert paths(patch) == [("keep.txt", "keep.txt"), ("src/app.py", "src/app.py")] + + +def test_upstream_branch_wins_over_the_remote_default(repo: Path) -> None: + first = head_of(repo) + (repo / "keep.txt").write_text("upstream moved\n") + git(repo, "commit", "-q", "-am", "upstream") + upstream = head_of(repo) + git(repo, "update-ref", "refs/remotes/origin/main", first) + git(repo, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + git(repo, "update-ref", "refs/remotes/origin/feature", upstream) + git(repo, "config", "remote.origin.url", "https://example.invalid/owner/name.git") + git(repo, "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*") + git(repo, "config", "branch.main.remote", "origin") + git(repo, "config", "branch.main.merge", "refs/heads/feature") + + assert read_local_changes(repo).base_commit_sha == upstream + + +def test_a_checkout_without_any_base_is_refused(repo: Path) -> None: + with pytest.raises(LocalChangesError, match="no base to review against"): + read_local_changes(repo) + + +def test_a_committed_range_ignores_the_work_tree(repo: Path) -> None: + base = head_of(repo) + (repo / "keep.txt").write_text("committed\n") + git(repo, "commit", "-q", "-am", "change") + (repo / "src" / "app.py").write_text("print('not committed')\n") + + patch = read_local_changes(repo, base=base, head="HEAD") + + assert patch.base_commit_sha == base + assert paths(patch) == [("keep.txt", "keep.txt")] + + +@pytest.mark.parametrize( + "kwargs", + [ + {"head": "HEAD"}, + {"base": "HEAD", "head": "HEAD", "selection": "staged"}, + {"selection": "everything"}, + {"remote": "-x"}, + {"remote": "origin/main"}, + ], +) +def test_contradictory_arguments_are_refused(repo: Path, kwargs: dict[str, Any]) -> None: + with pytest.raises(ValueError): + read_local_changes(repo, **kwargs) + + +@pytest.mark.parametrize("revision", ["", "-p", "--output=x", "no-such-branch"]) +def test_unknown_or_option_like_revisions_are_refused(repo: Path, revision: str) -> None: + with pytest.raises(LocalChangesError, match="names no commit"): + read_local_changes(repo, base=revision) + + +def test_a_directory_outside_any_checkout_is_refused(tmp_path: Path) -> None: + with pytest.raises(LocalChangesError, match="not inside a Git checkout"): + read_local_changes(tmp_path, base="HEAD") + + +def test_binary_changes_are_refused(repo: Path) -> None: + (repo / "image.bin").write_bytes(b"\x00\x01\x02\x03binary") + git(repo, "add", "image.bin") + with pytest.raises(LocalChangesError, match="'image.bin' is a binary change"): + read_local_changes(repo, base="HEAD") + + +def test_symbolic_links_and_submodules_are_refused(repo: Path) -> None: + blob = subprocess.run( + ["git", "-C", str(repo), "hash-object", "-w", "--stdin"], + input="keep.txt", + capture_output=True, + text=True, + check=True, + ).stdout.strip() + git(repo, "update-index", "--add", "--cacheinfo", f"120000,{blob},link") + with pytest.raises(LocalChangesError, match="'link' is a symbolic link"): + read_local_changes(repo, base="HEAD", selection="staged") + git(repo, "rm", "-q", "--cached", "link") + git(repo, "update-index", "--add", "--cacheinfo", f"160000,{head_of(repo)},vendor/lib") + with pytest.raises(LocalChangesError, match="'vendor/lib' is a submodule"): + read_local_changes(repo, base="HEAD", selection="staged") + + +def test_unresolved_merge_conflicts_are_refused(repo: Path) -> None: + git(repo, "checkout", "-q", "-b", "other") + (repo / "keep.txt").write_text("theirs\n") + git(repo, "commit", "-q", "-am", "theirs") + git(repo, "checkout", "-q", "main") + (repo / "keep.txt").write_text("ours\n") + git(repo, "commit", "-q", "-am", "ours") + subprocess.run(["git", "-C", str(repo), "merge", "-q", "other"], capture_output=True) + with pytest.raises(LocalChangesError, match="'keep.txt' has an unresolved merge conflict"): + read_local_changes(repo, base="HEAD", selection="staged") + + +def test_text_that_is_not_utf8_is_refused(repo: Path) -> None: + (repo / "keep.txt").write_bytes("café\n".encode("latin-1")) + with pytest.raises(LocalChangesError, match="not UTF-8"): + read_local_changes(repo, base="HEAD") + + +def test_patch_size_and_file_count_limits(repo: Path, monkeypatch: pytest.MonkeyPatch) -> None: + (repo / "keep.txt").write_text("x\n" * 200) + (repo / "src" / "app.py").write_text("y\n") + monkeypatch.setattr(local_module, "MAX_PATCH_BYTES", 100) + with pytest.raises(LocalChangesError, match="up to 5 MiB"): + read_local_changes(repo, base="HEAD") + monkeypatch.setattr(local_module, "MAX_PATCH_BYTES", 5 << 20) + monkeypatch.setattr(local_module, "MAX_PATCH_FILES", 1) + with pytest.raises(LocalChangesError, match="2 files"): + read_local_changes(repo, base="HEAD") + + +def test_no_changes_reads_as_an_empty_patch(repo: Path) -> None: + patch = read_local_changes(repo, base="HEAD") + assert (patch.files, patch.patch) == (0, "") + + +def test_request_carries_findings_and_trigger_and_bounds_findings(repo: Path) -> None: + (repo / "keep.txt").write_text("changed\n") + patch = read_local_changes(repo, base="HEAD") + body = patch.request( + verify_finding_ids=[FINDING], trigger_source=PatchTriggerSource.HOOK_PRE_PUSH + ) + assert body.to_dict() == { + "base_commit_sha": head_of(repo), + "patch": patch.patch, + "trigger_source": "HOOK_PRE_PUSH", + "verify_finding_ids": [str(FINDING)], + } + with pytest.raises(ValueError, match="at most 20"): + patch.request(verify_finding_ids=[FINDING] * 21) + + +# -------------------------------------------------------------------- secret check + +SHAPES = [ + ("AKIA", "A1B2C3D4E5F6G7H8", "an AWS access-key ID"), + ("ghp_", "a" * 36, "a GitHub token"), + ("github_pat_", "a" * 82, "a GitHub token"), + ("xoxb-", "12345678", "a Slack token"), + ("AIza", "a" * 35, "a Google API key"), + ("sk_live_", "a" * 24, "a Stripe live key"), + ("sk-", "a" * 48, "a model-provider key"), + ("sk-ant-", "a" * 40, "a model-provider key"), + ("plp_", "A" * 52, "a Proofline token"), +] + + +def one_file( + lines: list[str], *, old: str | None = "app.py", new: str | None = "app.py" +) -> LocalPatch: + header = f"diff --git a/{old or new} b/{new or old}\n--- a/{old}\n+++ b/{new}\n" + return LocalPatch("a" * 40, header + "\n".join(lines) + "\n", (PatchPath(old, new),)) + + +@pytest.mark.parametrize(("prefix", "body", "kind"), SHAPES) +def test_each_listed_credential_shape_is_refused_at_its_minimum( + prefix: str, body: str, kind: str +) -> None: + patch = one_file(["@@ -1,0 +1,1 @@", "+key = " + credential(prefix, body)]) + with pytest.raises(SecretInPatch) as caught: + check_secrets(patch) + assert (caught.value.kind, caught.value.path, caught.value.line) == (kind, "app.py", 1) + assert credential(prefix, body) not in str(caught.value) + + +@pytest.mark.parametrize(("prefix", "body", "kind"), SHAPES) +def test_a_body_one_short_of_the_minimum_is_not_a_credential( + prefix: str, body: str, kind: str +) -> None: + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+key = " + credential(prefix, body[:-1])])) + + +def test_private_key_markers_are_refused_but_certificates_are_not() -> None: + marker = "-----" + "BEGIN RSA PRIVATE KEY" + "-----" + with pytest.raises(SecretInPatch, match="a private-key marker"): + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+" + marker])) + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+-----BEGIN CERTIFICATE-----"])) + + +def test_removed_context_and_heading_lines_are_uploaded_so_they_are_read() -> None: + token = credential("ghp_", "b" * 36) + cases = [ + (["@@ -3,1 +3,0 @@", "-" + token], "base line", 3), + (["@@ -7,2 +7,2 @@", " " + token, "+x"], "new line", 7), + ([f"@@ -1,1 +1,1 @@ def handler({token}):", "+x"], "patch line", 4), + ] + for lines, coordinate, line in cases: + with pytest.raises(SecretInPatch) as caught: + check_secrets(one_file(lines)) + assert (caught.value.coordinate, caught.value.line) == (coordinate, line) + + +def test_line_numbers_follow_each_hunk() -> None: + token = credential("AKIA", "Z" * 16) + patch = one_file(["@@ -1,2 +1,2 @@", " a", "-b", "+c", "@@ -10,1 +10,2 @@", " d", "+" + token]) + with pytest.raises(SecretInPatch) as caught: + check_secrets(patch) + assert caught.value.line == 11 + + +@pytest.mark.parametrize("path", [".env", "config/.env", ".env.local", "deploy/.env.production"]) +def test_env_paths_are_refused_unless_allowed(path: str) -> None: + patch = one_file(["@@ -0,0 +1,1 @@", "+X=1"], old=None, new=path) + with pytest.raises(SecretInPatch, match="sensitive .env path"): + check_secrets(patch) + check_secrets(patch, allow_paths=[path]) + + +def test_similar_names_are_not_env_paths() -> None: + for path in (".envrc", "env.example", "docs/environment.md"): + check_secrets(one_file(["@@ -0,0 +1,1 @@", "+X=1"], old=None, new=path)) + + +def test_allow_paths_skips_only_that_exact_path() -> None: + token = credential("ghp_", "c" * 36) + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+" + token]), allow_paths=["app.py"]) + with pytest.raises(SecretInPatch): + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+" + token]), allow_paths=["other.py"]) + + +@pytest.mark.parametrize("bad", ["/app.py", "../app.py", "a//b", "./app.py", ""]) +def test_allow_paths_must_be_exact_repository_relative_paths(bad: str) -> None: + with pytest.raises(ValueError, match="allow_paths"): + check_secrets(one_file(["@@ -1,0 +1,1 @@", "+x"]), allow_paths=[bad]) + + +def test_a_patch_that_does_not_match_its_paths_is_refused() -> None: + broken = LocalPatch("a" * 40, "diff --git a/x b/x\n@@ nonsense @@\n", (PatchPath("x", "x"),)) + with pytest.raises(LocalChangesError, match="Could not map"): + check_secrets(broken) + missing = LocalPatch("a" * 40, "diff --git a/x b/x\n", ()) + with pytest.raises(LocalChangesError, match="Could not map"): + check_secrets(missing) + + +def test_a_secret_written_to_a_real_checkout_is_refused_before_upload(repo: Path) -> None: + (repo / "src" / "app.py").write_text("token = '" + credential("xoxb-", "99887766") + "'\n") + with pytest.raises(SecretInPatch) as caught: + check_secrets(read_local_changes(repo, base="HEAD")) + assert (caught.value.path, caught.value.line, caught.value.kind) == ( + "src/app.py", + 1, + "a Slack token", + ) + + +# ------------------------------------------------------------------------- clients + + +@asynccontextmanager +async def session(mode: str, url: str) -> AsyncIterator[Client]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as async_client: + yield async_client + + +async def review_from_git(client: Client, **kwargs: Any) -> Any: + result = client.request_patch_review_from_git(ORG, REPOSITORY, **kwargs) + return await result if inspect.isawaitable(result) else result + + +@MODES +async def test_clients_post_the_checkout_patch(mode: str, repo: Path) -> None: + (repo / "keep.txt").write_text("one\ntwo\nthree\n") + expected = read_local_changes(repo, base="HEAD") + + def respond(request: Request, index: int) -> Reply: + assert request.method == "POST" + assert ( + request.path == f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/patch-reviews" + ) + assert json.loads(request.body) == { + "base_commit_sha": expected.base_commit_sha, + "patch": expected.patch, + "trigger_source": "HOOK_PRE_COMMIT", + "verify_finding_ids": [str(FINDING)], + } + return Reply( + body={ + "review_id": str(REVIEW), + "existing": False, + "patch_digest": "b" * 64, + "verify": [], + } + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await review_from_git( + client, + cwd=repo, + base="HEAD", + verify_finding_ids=[FINDING], + trigger_source=PatchTriggerSource.HOOK_PRE_COMMIT, + ) + assert (result.review_id, result.existing) == (REVIEW, False) + assert len(server.requests) == 1 + + +@MODES +async def test_clients_send_nothing_when_the_checkout_is_refused(mode: str, repo: Path) -> None: + with Server(lambda request, index: Reply(status=500)) as server: + async with session(mode, server.url) as client: + with pytest.raises(NoLocalChanges): + await review_from_git(client, cwd=repo, base="HEAD") + (repo / "src" / "app.py").write_text(credential("sk-proj-", "d" * 40) + "\n") + with pytest.raises(SecretInPatch): + await review_from_git(client, cwd=repo, base="HEAD") + # Allowed, so it is sent; this test server answers every request with 500. + with pytest.raises(ProoflineError): + await review_from_git(client, cwd=repo, base="HEAD", allow_paths=["src/app.py"]) + assert len(server.requests) == 1 + + +def test_sync_and_async_review_from_git_share_one_signature() -> None: + sync_parameters = inspect.signature(ProoflineClient.request_patch_review_from_git).parameters + async_method = AsyncProoflineClient.request_patch_review_from_git + assert inspect.iscoroutinefunction(async_method) + assert sync_parameters == inspect.signature(async_method).parameters