From bb236c046aa6a4afbf5d5aa599b57f31d2618bd8 Mon Sep 17 00:00:00 2001 From: shibanalex <твой_email@example.com> Date: Fri, 27 Nov 2026 13:57:09 +0300 Subject: [PATCH 1/4] Add read_coverage_files and CoverageFile with path and size checks --- proofline/coverage.py | 225 +++++++++++++++++++++++++++++++++++++++++ tests/test_coverage.py | 204 +++++++++++++++++++++++++++++++++++++ 2 files changed, 429 insertions(+) create mode 100644 proofline/coverage.py create mode 100644 tests/test_coverage.py diff --git a/proofline/coverage.py b/proofline/coverage.py new file mode 100644 index 00000000..b974bdf9 --- /dev/null +++ b/proofline/coverage.py @@ -0,0 +1,225 @@ +"""Read coverage report files from disk into a validated upload request.""" + +from __future__ import annotations + +import errno +import json +import os +import stat +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path, PureWindowsPath +from string import hexdigits +from typing import TypeAlias + +from ._generated.models.coverage_upload_request import CoverageUploadRequest +from ._generated.models.uploaded_report import UploadedReport + +MAX_REPORTS = 50 +MAX_BODY_BYTES = 30 * 1024 * 1024 + +CoveragePath: TypeAlias = str | os.PathLike[str] + + +@dataclass(frozen=True, slots=True) +class CoverageFile: + """A coverage report path on disk with an optional server-recorded name.""" + + path: CoveragePath + name: str | None = None + + +CoverageFileInput: TypeAlias = CoveragePath | CoverageFile + + +@dataclass(frozen=True, slots=True) +class _PreparedFile: + raw_path: str + logical_path: Path + name: str + + +@dataclass(frozen=True, slots=True) +class _PreparedCoverageUpload: + tested_sha: str + logical_root: Path + files: tuple[_PreparedFile, ...] + + +def _path_text(value: object, label: str) -> str: + if not isinstance(value, (str, os.PathLike)): + raise TypeError(f"{label} must be a str or os.PathLike[str].") + raw = os.fspath(value) + if not isinstance(raw, str): + raise TypeError(f"{label} must be a str path, not bytes.") + if "\x00" in raw: + raise ValueError(f"{label} cannot contain NUL bytes.") + return raw + + +def _within_root(target: Path, root: Path) -> bool: + return target != root and target.is_relative_to(root) + + +def _report_name(name: str) -> str: + segments = name.split("/") + windows = PureWindowsPath(name) + if ( + not name + or "\x00" in name + or "\\" in name + or os.path.isabs(name) + or windows.is_absolute() + or windows.drive != "" + or any(segment in ("", ".", "..") for segment in segments) + ): + raise ValueError( + f"Coverage report name {name!r} must be a relative POSIX path inside root." + ) + return name + + +def _prepare_coverage_files( + tested_sha: str, + files: Sequence[CoverageFileInput], + *, + root: CoveragePath | None = None, +) -> _PreparedCoverageUpload: + if ( + not isinstance(tested_sha, str) + or len(tested_sha) != 40 + or any(character not in hexdigits for character in tested_sha) + ): + raise ValueError("tested_sha must be a full 40-character hexadecimal commit SHA.") + if isinstance(files, (str, bytes, bytearray, memoryview, os.PathLike)) or not isinstance( + files, Sequence + ): + raise TypeError("files must be a sequence of report paths or CoverageFile entries.") + entries = tuple(files) + if not 1 <= len(entries) <= MAX_REPORTS: + raise ValueError(f"Upload 1 to {MAX_REPORTS} coverage reports.") + + root_text = os.getcwd() if root is None else _path_text(root, "root") + logical_root = Path(os.path.abspath(root_text)) + + prepared: list[_PreparedFile] = [] + seen_names: set[str] = set() + for entry in entries: + if isinstance(entry, CoverageFile): + raw_path = _path_text(entry.path, "CoverageFile.path") + if entry.name is not None and not isinstance(entry.name, str): + raise TypeError("CoverageFile.name must be a str or None.") + explicit_name = entry.name + else: + raw_path = _path_text(entry, "files entry") + explicit_name = None + + if not raw_path: + raise ValueError("Coverage report path must be inside root.") + logical_path = Path(os.path.abspath(os.path.join(logical_root, raw_path))) + if not _within_root(logical_path, logical_root): + raise ValueError(f"Coverage report path {raw_path!r} must be inside root.") + + default_name = logical_path.relative_to(logical_root).as_posix() + name = _report_name(explicit_name if explicit_name is not None else default_name) + if name in seen_names: + raise ValueError(f"Coverage report names must be unique; {name!r} is duplicated.") + seen_names.add(name) + prepared.append(_PreparedFile(raw_path=raw_path, logical_path=logical_path, name=name)) + + return _PreparedCoverageUpload( + tested_sha=tested_sha, + logical_root=logical_root, + files=tuple(prepared), + ) + + +def _read_regular_file(path: Path, name: str, remaining_budget: int) -> bytes: + flags = ( + os.O_RDONLY + | getattr(os, "O_BINARY", 0) + | getattr(os, "O_NONBLOCK", 0) + | getattr(os, "O_NOFOLLOW", 0) + ) + fd = os.open(path, flags) + try: + info = os.fstat(fd) + if stat.S_ISDIR(info.st_mode): + raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), str(path)) + if not stat.S_ISREG(info.st_mode): + raise ValueError(f"Coverage report {name!r} must be a regular file.") + if info.st_size > remaining_budget: + raise ValueError("Coverage reports exceed the 30 MiB upload limit.") + chunks: list[bytes] = [] + total = 0 + while True: + chunk = os.read(fd, min(65_536, remaining_budget - total + 1)) + if not chunk: + break + total += len(chunk) + if total > remaining_budget: + raise ValueError("Coverage reports exceed the 30 MiB upload limit.") + chunks.append(chunk) + return b"".join(chunks) + finally: + os.close(fd) + + +def _read_prepared_coverage_files(prepared: _PreparedCoverageUpload) -> CoverageUploadRequest: + real_root = Path(os.path.realpath(prepared.logical_root, strict=True)) + if not real_root.is_dir(): + raise NotADirectoryError( + errno.ENOTDIR, os.strerror(errno.ENOTDIR), str(prepared.logical_root) + ) + + resolved_files: list[tuple[_PreparedFile, Path]] = [] + for item in prepared.files: + real_path = Path(os.path.realpath(item.logical_path, strict=True)) + if not _within_root(real_path, real_root): + raise ValueError(f"Coverage report path {item.raw_path!r} must be inside root.") + resolved_files.append((item, real_path)) + + # Report bytes alone can exceed the 30 MiB body limit; bound reads on open descriptors + # so oversized or non-regular files fail before allocating full buffers. + remaining_budget = MAX_BODY_BYTES + reports: list[UploadedReport] = [] + for item, real_path in resolved_files: + raw = _read_regular_file(real_path, item.name, remaining_budget) + remaining_budget -= len(raw) + try: + # Strict UTF-8 keeps a leading BOM intact so content matches the written file. + content = raw.decode("utf-8") + except UnicodeDecodeError: + raise ValueError(f"Coverage report {item.name!r} is not UTF-8 text.") from None + reports.append(UploadedReport(name=item.name, content=content)) + + request = CoverageUploadRequest(tested_sha=prepared.tested_sha, reports=reports) + # Match httpx2's compact UTF-8 JSON encoding used by upload_coverage_reports. + wire = json.dumps( + request.to_dict(), + ensure_ascii=False, + separators=(",", ":"), + allow_nan=False, + ).encode("utf-8") + if len(wire) > MAX_BODY_BYTES: + raise ValueError("Coverage reports exceed the 30 MiB upload limit.") + return request + + +def read_coverage_files( + tested_sha: str, + files: Sequence[CoverageFileInput], + *, + root: CoveragePath | None = None, +) -> CoverageUploadRequest: + """Read coverage reports from disk into a validated upload request. + + Each report defaults its recorded name to its POSIX path relative to ``root`` + (the current working directory when omitted), unless wrapped in ``CoverageFile`` + with an explicit ``name``. Refuses abbreviated SHAs, counts outside 1..50, + duplicate or escaping paths and names, non-regular or non-UTF-8 files, and + serialized JSON bodies exceeding 30 MiB with ``ValueError`` before any network + call. Filesystem errors such as missing files propagate unchanged as ``OSError``. + """ + prepared = _prepare_coverage_files(tested_sha, files, root=root) + return _read_prepared_coverage_files(prepared) diff --git a/tests/test_coverage.py b/tests/test_coverage.py new file mode 100644 index 00000000..3f5324b5 --- /dev/null +++ b/tests/test_coverage.py @@ -0,0 +1,204 @@ +"""Coverage file reading, path containment and 30 MiB wire-bound tests.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +import pytest + +from proofline.coverage import MAX_BODY_BYTES, CoverageFile, read_coverage_files + +SHA = "c" * 40 + + +def test_read_coverage_files_preserves_names_and_bom( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + nested = tmp_path / "nested" + nested.mkdir() + lcov = "\ufeffSF:pkg/mod.py\nDA:1,1\nend_of_record\n" + go_cover = "mode: set\nexample.com/pkg/mod.go:1.1,2.2 1 1\n" + (nested / "lcov.info").write_bytes(lcov.encode("utf-8")) + (tmp_path / "cover.out").write_text(go_cover, encoding="utf-8") + + mixed_sha = "AbCdEf01" * 5 + request = read_coverage_files( + mixed_sha, + [ + Path("nested") / "lcov.info", + CoverageFile(tmp_path / "cover.out", name="go/coverage.out"), + ], + root=tmp_path, + ) + assert request.to_dict() == { + "tested_sha": mixed_sha, + "reports": [ + {"name": "nested/lcov.info", "content": lcov}, + {"name": "go/coverage.out", "content": go_cover}, + ], + } + + monkeypatch.chdir(tmp_path) + from_cwd = read_coverage_files(mixed_sha, ["nested/lcov.info"]) + assert from_cwd.reports[0].name == "nested/lcov.info" + assert from_cwd.reports[0].content == lcov + + +def test_tested_sha_does_not_fall_back_to_github_sha( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + (tmp_path / "lcov.info").write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + monkeypatch.setenv("GITHUB_SHA", "a" * 40) + with pytest.raises(ValueError, match="40-character"): + read_coverage_files("", ["lcov.info"], root=tmp_path) + + +@pytest.mark.parametrize( + "bad_sha", + [ + "main", + "c" * 12, + "c" * 39, + "c" * 41, + "c" * 64, + "g" * 40, + f" {'c' * 39}", + ], +) +def test_invalid_tested_sha_refused_locally(tmp_path: Path, bad_sha: str) -> None: + (tmp_path / "lcov.info").write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + with pytest.raises(ValueError, match="40-character"): + read_coverage_files(bad_sha, ["lcov.info"], root=tmp_path) + + +def test_non_sequence_files_rejected_with_type_error(tmp_path: Path) -> None: + report = tmp_path / "lcov.info" + report.write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + for invalid in ("lcov.info", b"lcov.info", report): + with pytest.raises(TypeError, match="sequence"): + read_coverage_files(SHA, invalid, root=tmp_path) # type: ignore[arg-type] + + +def test_local_validation_refuses_bad_counts_duplicates_escapes_and_binary(tmp_path: Path) -> None: + root = tmp_path / "workspace" + root.mkdir() + (root / "a.info").write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + (root / "b.info").write_text("SF:b.py\nend_of_record\n", encoding="utf-8") + (root / "report.gz").write_bytes(b"\x1f\x8b\xff") + + outside = tmp_path / "outside.info" + outside.write_text("secret", encoding="utf-8") + + cases: list[tuple[list[Any], str]] = [ + ([], "1 to 50"), + (["a.info"] * 51, "1 to 50"), + (["a.info", CoverageFile("a.info")], "unique"), + ( + [ + CoverageFile("a.info", name="dup.info"), + CoverageFile("b.info", name="dup.info"), + ], + "unique", + ), + (["../nonexistent.info"], "inside root"), + ([outside], "inside root"), + ([CoverageFile(outside, name="lcov.info")], "inside root"), + ([""], "inside root"), + (["."], "inside root"), + ([CoverageFile("a.info", name="")], "relative POSIX path"), + ([CoverageFile("a.info", name=".")], "relative POSIX path"), + ([CoverageFile("a.info", name="..")], "relative POSIX path"), + ([CoverageFile("a.info", name="./a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/./a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/../a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub//a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="/abs.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub\\a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="C:a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="a\x00b.info")], "relative POSIX path"), + (["report.gz"], "report.gz.*not UTF-8"), + ] + for file_specs, pattern in cases: + with pytest.raises(ValueError, match=pattern): + read_coverage_files(SHA, file_specs, root=root) + + with pytest.raises(FileNotFoundError): + read_coverage_files(SHA, ["missing.info"], root=root) + + sub_dir = root / "subdir" + sub_dir.mkdir() + with pytest.raises(IsADirectoryError): + read_coverage_files(SHA, ["subdir"], root=root) + + +@pytest.mark.skipif(not hasattr(os, "symlink"), reason="OS does not support symlinks") +def test_symlinks_inside_root_work_while_escaping_symlinks_are_refused(tmp_path: Path) -> None: + root = tmp_path / "root" + sub = root / "sub" + sub.mkdir(parents=True) + target_in_root = sub / "real.info" + target_in_root.write_text("SF:ok.py\nend_of_record\n", encoding="utf-8") + + outside = tmp_path / "outside.info" + outside.write_text("outside", encoding="utf-8") + + in_link = root / "linked.info" + out_link = root / "escape.info" + try: + in_link.symlink_to(target_in_root) + out_link.symlink_to(outside) + except OSError as exc: + pytest.skip(f"Symlinks unavailable in test environment: {exc}") + + req = read_coverage_files(SHA, ["linked.info"], root=root) + assert len(req.reports) == 1 + assert req.reports[0].name == "linked.info" + assert req.reports[0].content == "SF:ok.py\nend_of_record\n" + + escape_specs: tuple[str | CoverageFile, ...] = ( + "escape.info", + CoverageFile("escape.info", name="lcov.info"), + ) + for spec in escape_specs: + with pytest.raises(ValueError, match="inside root"): + read_coverage_files(SHA, [spec], root=root) + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFO unavailable") +def test_fifo_special_file_is_refused_without_blocking(tmp_path: Path) -> None: + fifo = tmp_path / "pipe.info" + os.mkfifo(fifo) + with pytest.raises(ValueError, match="regular file"): + read_coverage_files(SHA, ["pipe.info"], root=tmp_path) + + +def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path: Path) -> None: + sparse = tmp_path / "huge.info" + sparse.write_bytes(b"") + os.truncate(sparse, MAX_BODY_BYTES + 1) + with pytest.raises(ValueError, match="30 MiB"): + read_coverage_files(SHA, ["huge.info"], root=tmp_path) + + empty_envelope = json.dumps( + {"tested_sha": SHA, "reports": [{"name": "a.info", "content": ""}]}, + ensure_ascii=False, + separators=(",", ":"), + ).encode("utf-8") + exact_content_len = MAX_BODY_BYTES - len(empty_envelope) + + exact = tmp_path / "a.info" + exact.write_bytes(b"x" * exact_content_len) + built = read_coverage_files(SHA, ["a.info"], root=tmp_path) + assert len(built.reports[0].content) == exact_content_len + + exact.write_bytes(b"x" * (exact_content_len + 1)) + with pytest.raises(ValueError, match="30 MiB"): + read_coverage_files(SHA, ["a.info"], root=tmp_path) + + exact.write_bytes(b'"' + b"x" * (exact_content_len - 1)) + with pytest.raises(ValueError, match="30 MiB"): + read_coverage_files(SHA, ["a.info"], root=tmp_path) From a361c2bc201bdc52c772096633806d6b6d5cf792 Mon Sep 17 00:00:00 2001 From: shibanalex <твой_email@example.com> Date: Fri, 27 Nov 2026 19:57:53 +0300 Subject: [PATCH 2/4] Wire upload_coverage_files into sync and async clients --- proofline/__init__.py | 3 + proofline/client.py | 37 ++++++- scripts/contracts.py | 9 +- tests/test_coverage.py | 236 ++++++++++++++++++++++++++++++----------- 4 files changed, 220 insertions(+), 65 deletions(-) diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..b45b9a17 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,6 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .coverage import CoverageFile, read_coverage_files from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -46,6 +47,7 @@ "CheckGap", "CommitReviewRequest", "CommitReviewResponse", + "CoverageFile", "CoverageUploadRequest", "CoverageUploadResponse", "CustomerAssessmentDetail", @@ -80,4 +82,5 @@ "UploadedReport", "__version__", "models", + "read_coverage_files", ] diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..8aff9701 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,7 +4,7 @@ import math 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 string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -12,6 +12,7 @@ from urllib.parse import quote from uuid import UUID +import anyio import httpx2 from pydantic import SecretStr @@ -72,6 +73,13 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .coverage import ( + CoverageFileInput, + CoveragePath, + _prepare_coverage_files, + _read_prepared_coverage_files, + read_coverage_files, +) from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -479,6 +487,19 @@ def upload_coverage_reports( body=body, ) + def upload_coverage_files( + self, + organization_id: UUID, + repository_id: UUID, + tested_sha: str, + files: Sequence[CoverageFileInput], + *, + root: CoveragePath | None = None, + ) -> CoverageUploadResponse: + """Read coverage report files from disk and upload them for one commit.""" + body = read_coverage_files(tested_sha, files, root=root) + return self.upload_coverage_reports(organization_id, repository_id, body=body) + def request_file_review( self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest ) -> FileReviewResponse: @@ -870,6 +891,20 @@ async def upload_coverage_reports( body=body, ) + async def upload_coverage_files( + self, + organization_id: UUID, + repository_id: UUID, + tested_sha: str, + files: Sequence[CoverageFileInput], + *, + root: CoveragePath | None = None, + ) -> CoverageUploadResponse: + """Read coverage report files from disk and upload them for one commit.""" + prepared = _prepare_coverage_files(tested_sha, files, root=root) + body = await anyio.to_thread.run_sync(_read_prepared_coverage_files, prepared) + return await self.upload_coverage_reports(organization_id, repository_id, body=body) + async def request_file_review( self, organization_id: UUID, repository_id: UUID, *, body: FileReviewRequest ) -> FileReviewResponse: diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..9c5af44d 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", + "upload_coverage_files", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_coverage.py b/tests/test_coverage.py index 3f5324b5..a37a67f5 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -2,19 +2,43 @@ from __future__ import annotations +import asyncio import json import os from pathlib import Path from typing import Any +from uuid import UUID import pytest -from proofline.coverage import MAX_BODY_BYTES, CoverageFile, read_coverage_files +from proofline import ( + AsyncProoflineClient, + CoverageFile, + ProoflineClient, + SecretStr, + read_coverage_files, +) +from proofline.coverage import MAX_BODY_BYTES + +from . import fixtures +from .http_server import Reply, Server +REPORT_ID = UUID("00000000-0000-4000-8000-000000000099") SHA = "c" * 40 -def test_read_coverage_files_preserves_names_and_bom( +def _upload_reply(tested_sha: str = SHA, *, created: bool = True) -> dict[str, Any]: + return { + "report_id": str(REPORT_ID), + "tested_sha": tested_sha, + "created": created, + "formats": ["LCOV", "GO_COVER"], + "instrumented_lines": 12, + "covered_lines": 10, + } + + +def test_sync_and_async_upload_coverage_files_preserve_names_and_bom( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: nested = tmp_path / "nested" @@ -25,26 +49,58 @@ def test_read_coverage_files_preserves_names_and_bom( (tmp_path / "cover.out").write_text(go_cover, encoding="utf-8") mixed_sha = "AbCdEf01" * 5 - request = read_coverage_files( - mixed_sha, - [ - Path("nested") / "lcov.info", - CoverageFile(tmp_path / "cover.out", name="go/coverage.out"), - ], - root=tmp_path, + with Server( + lambda _, idx: Reply( + status=201 if idx == 0 else 200, + body=_upload_reply(mixed_sha, created=idx == 0), + ) + ) as peer: + with ProoflineClient(SecretStr(fixtures.TOKEN), base_url=peer.url) as client: + first = client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + mixed_sha, + [ + Path("nested") / "lcov.info", + CoverageFile(tmp_path / "cover.out", name="go/coverage.out"), + ], + root=tmp_path, + ) + assert first.report_id == REPORT_ID + assert first.created is True + + monkeypatch.chdir(tmp_path) + + async def run_async() -> None: + async with AsyncProoflineClient(SecretStr(fixtures.TOKEN), base_url=peer.url) as client: + second = await client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + mixed_sha, + [ + "nested/lcov.info", + CoverageFile("cover.out", name="go/coverage.out"), + ], + ) + assert second.created is False + + asyncio.run(run_async()) + + assert len(peer.requests) == 2 + expected_path = ( + f"/api/v1/organizations/{fixtures.ORG}/repositories/{fixtures.REPOSITORY}/coverage-reports" ) - assert request.to_dict() == { - "tested_sha": mixed_sha, - "reports": [ - {"name": "nested/lcov.info", "content": lcov}, - {"name": "go/coverage.out", "content": go_cover}, - ], - } - - monkeypatch.chdir(tmp_path) - from_cwd = read_coverage_files(mixed_sha, ["nested/lcov.info"]) - assert from_cwd.reports[0].name == "nested/lcov.info" - assert from_cwd.reports[0].content == lcov + for req in peer.requests: + assert req.method == "POST" + assert req.path == expected_path + assert req.headers["Authorization"] == f"Bearer {fixtures.TOKEN}" + assert json.loads(req.body) == { + "tested_sha": mixed_sha, + "reports": [ + {"name": "nested/lcov.info", "content": lcov}, + {"name": "go/coverage.out", "content": go_cover}, + ], + } def test_tested_sha_does_not_fall_back_to_github_sha( @@ -82,7 +138,9 @@ def test_non_sequence_files_rejected_with_type_error(tmp_path: Path) -> None: read_coverage_files(SHA, invalid, root=tmp_path) # type: ignore[arg-type] -def test_local_validation_refuses_bad_counts_duplicates_escapes_and_binary(tmp_path: Path) -> None: +def test_local_validation_refuses_bad_counts_duplicates_escapes_and_binary_before_http( + tmp_path: Path, +) -> None: root = tmp_path / "workspace" root.mkdir() (root / "a.info").write_text("SF:a.py\nend_of_record\n", encoding="utf-8") @@ -92,47 +150,70 @@ def test_local_validation_refuses_bad_counts_duplicates_escapes_and_binary(tmp_p outside = tmp_path / "outside.info" outside.write_text("secret", encoding="utf-8") - cases: list[tuple[list[Any], str]] = [ - ([], "1 to 50"), - (["a.info"] * 51, "1 to 50"), - (["a.info", CoverageFile("a.info")], "unique"), - ( - [ - CoverageFile("a.info", name="dup.info"), - CoverageFile("b.info", name="dup.info"), - ], - "unique", - ), - (["../nonexistent.info"], "inside root"), - ([outside], "inside root"), - ([CoverageFile(outside, name="lcov.info")], "inside root"), - ([""], "inside root"), - (["."], "inside root"), - ([CoverageFile("a.info", name="")], "relative POSIX path"), - ([CoverageFile("a.info", name=".")], "relative POSIX path"), - ([CoverageFile("a.info", name="..")], "relative POSIX path"), - ([CoverageFile("a.info", name="./a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="sub/./a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="sub/../a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="sub//a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="/abs.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="sub/")], "relative POSIX path"), - ([CoverageFile("a.info", name="sub\\a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="C:a.info")], "relative POSIX path"), - ([CoverageFile("a.info", name="a\x00b.info")], "relative POSIX path"), - (["report.gz"], "report.gz.*not UTF-8"), - ] - for file_specs, pattern in cases: - with pytest.raises(ValueError, match=pattern): - read_coverage_files(SHA, file_specs, root=root) - - with pytest.raises(FileNotFoundError): - read_coverage_files(SHA, ["missing.info"], root=root) - - sub_dir = root / "subdir" - sub_dir.mkdir() - with pytest.raises(IsADirectoryError): - read_coverage_files(SHA, ["subdir"], root=root) + with Server(lambda _, __: Reply(status=500, body={})) as peer: + with ProoflineClient(SecretStr(fixtures.TOKEN), base_url=peer.url) as client: + cases: list[tuple[list[Any], str]] = [ + ([], "1 to 50"), + (["a.info"] * 51, "1 to 50"), + (["a.info", CoverageFile("a.info")], "unique"), + ( + [ + CoverageFile("a.info", name="dup.info"), + CoverageFile("b.info", name="dup.info"), + ], + "unique", + ), + (["../nonexistent.info"], "inside root"), + ([outside], "inside root"), + # Explicit custom name must not allow reading a path outside root. + ([CoverageFile(outside, name="lcov.info")], "inside root"), + ([""], "inside root"), + (["."], "inside root"), + ([CoverageFile("a.info", name="")], "relative POSIX path"), + ([CoverageFile("a.info", name=".")], "relative POSIX path"), + ([CoverageFile("a.info", name="..")], "relative POSIX path"), + ([CoverageFile("a.info", name="./a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/./a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/../a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub//a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="/abs.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub/")], "relative POSIX path"), + ([CoverageFile("a.info", name="sub\\a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="C:a.info")], "relative POSIX path"), + ([CoverageFile("a.info", name="a\x00b.info")], "relative POSIX path"), + (["report.gz"], "report.gz.*not UTF-8"), + ] + for file_specs, pattern in cases: + with pytest.raises(ValueError, match=pattern): + client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + SHA, + file_specs, + root=root, + ) + + with pytest.raises(FileNotFoundError): + client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + SHA, + ["missing.info"], + root=root, + ) + + sub_dir = root / "subdir" + sub_dir.mkdir() + with pytest.raises(IsADirectoryError): + client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + SHA, + ["subdir"], + root=root, + ) + + assert peer.requests == [] @pytest.mark.skipif(not hasattr(os, "symlink"), reason="OS does not support symlinks") @@ -183,6 +264,7 @@ def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path with pytest.raises(ValueError, match="30 MiB"): read_coverage_files(SHA, ["huge.info"], root=tmp_path) + # Compute exact compact JSON overhead for a single report named "a.info". empty_envelope = json.dumps( {"tested_sha": SHA, "reports": [{"name": "a.info", "content": ""}]}, ensure_ascii=False, @@ -195,6 +277,7 @@ def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path built = read_coverage_files(SHA, ["a.info"], root=tmp_path) assert len(built.reports[0].content) == exact_content_len + # One extra byte — or a quote character that JSON-escapes to two bytes — crosses 30 MiB. exact.write_bytes(b"x" * (exact_content_len + 1)) with pytest.raises(ValueError, match="30 MiB"): read_coverage_files(SHA, ["a.info"], root=tmp_path) @@ -202,3 +285,30 @@ def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path exact.write_bytes(b'"' + b"x" * (exact_content_len - 1)) with pytest.raises(ValueError, match="30 MiB"): read_coverage_files(SHA, ["a.info"], root=tmp_path) + + +@pytest.mark.asyncio +async def test_async_upload_snapshots_input_list_before_file_reads(tmp_path: Path) -> None: + (tmp_path / "a.info").write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + (tmp_path / "b.info").write_text("SF:b.py\nend_of_record\n", encoding="utf-8") + + files: list[str] = ["a.info"] + with Server(lambda _, __: Reply(status=201, body=_upload_reply())) as peer: + async with AsyncProoflineClient(SecretStr(fixtures.TOKEN), base_url=peer.url) as client: + task = asyncio.create_task( + client.upload_coverage_files( + fixtures.ORG, + fixtures.REPOSITORY, + SHA, + files, + root=tmp_path, + ) + ) + await asyncio.sleep(0) + files.append("b.info") + await task + + assert len(peer.requests) == 1 + assert json.loads(peer.requests[0].body)["reports"] == [ + {"name": "a.info", "content": "SF:a.py\nend_of_record\n"} + ] From 1096ae89ca39bbf129b2bd7fea951ac6c8ee0184 Mon Sep 17 00:00:00 2001 From: shibanalex <твой_email@example.com> Date: Sat, 28 Nov 2026 20:07:23 +0300 Subject: [PATCH 3/4] Document upload_coverage_files and cover it in install smoke --- README.md | 19 +++++++ scripts/install_smoke.py | 108 ++++++++++++++++++++++++++++----------- 2 files changed, 98 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 721949da..8275e266 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,25 @@ with ProoflineClient() as client: ) ``` +To upload reports directly from disk, `upload_coverage_files` reads each file as UTF-8 text and names it by its POSIX path relative to `root`, which defaults to the working directory. Wrap an entry in `CoverageFile` to choose a different report name, or call `read_coverage_files` to build the `CoverageUploadRequest` without sending it. + +```python +from proofline import CoverageFile, ProoflineClient + +with ProoflineClient() as client: + report = client.upload_coverage_files( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + UUID(os.environ["PROOFLINE_REPOSITORY_ID"]), + os.environ["TESTED_SHA"], + [ + "coverage/lcov.info", + CoverageFile("go/cover.out", name="go/coverage.out"), + ], + ) +``` + +`upload_coverage_files` and `read_coverage_files` raise `ValueError` before sending anything when `tested_sha` is not a full 40-character hexadecimal SHA, the report count is outside 1 to 50, two reports share a name, a report path or name escapes `root`, a report is not a regular UTF-8 file, or the serialized JSON body would exceed 30 MiB. Filesystem errors such as a missing report propagate unchanged as `OSError`. + The response names the recorded report and its covered and instrumented line counts. An identical upload returns that report with `created=False`. Refused reports raise `ProoflineError`. Uploading a report does not establish a check verdict. ## MCP organization selection diff --git a/scripts/install_smoke.py b/scripts/install_smoke.py index 3509074c..43bb406b 100644 --- a/scripts/install_smoke.py +++ b/scripts/install_smoke.py @@ -6,6 +6,7 @@ import importlib.metadata import json import sys +import tempfile import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path @@ -13,12 +14,21 @@ from uuid import UUID import proofline -from proofline import AsyncProoflineClient, ProoflineClient, ReviewFilters, SecretStr +from proofline import ( + AsyncProoflineClient, + CoverageFile, + ProoflineClient, + ReviewFilters, + SecretStr, +) ORG = UUID("00000000-0000-4000-8000-000000000001") +REPO = UUID("00000000-0000-4000-8000-000000000005") REVIEW = UUID("00000000-0000-4000-8000-000000000002") ASSESSMENT = UUID("00000000-0000-4000-8000-000000000003") FINDING = UUID("00000000-0000-4000-8000-000000000004") +REPORT = UUID("00000000-0000-4000-8000-000000000006") +SHA = "c" * 40 TOKEN = "pln_synthetic_installed_package_token" QUERY = '(status:COMPLETED OR status:FAILED) AND -author:"release bot"' @@ -104,40 +114,80 @@ def do_GET(self) -> None: self.end_headers() self.wfile.write(payload) + def do_POST(self) -> None: + assert self.headers["Authorization"] == f"Bearer {TOKEN}" + assert self.headers["User-Agent"] == f"proofline-python/{package_version}" + assert self.path == f"/api/v1/organizations/{ORG}/repositories/{REPO}/coverage-reports" + calls.append(self.path) + length = int(self.headers["Content-Length"]) + uploaded = json.loads(self.rfile.read(length)) + assert uploaded == { + "tested_sha": SHA, + "reports": [{"name": "pkg/lcov.info", "content": "SF:a.py\nend_of_record\n"}], + } + payload = json.dumps( + { + "report_id": str(REPORT), + "tested_sha": SHA, + "created": True, + "formats": ["LCOV"], + "instrumented_lines": 1, + "covered_lines": 1, + } + ).encode() + self.send_response(201) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01}) thread.start() url = f"http://127.0.0.1:{server.server_port}" - async def asynchronous() -> None: - async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as client: - assert (await client.list_reviews(ORG, query=QUERY)).items == [] - history = await client.list_pull_request_reviews(ORG, "repo/name", 42, filters=filters) - assert history.items == [] - assert [item async for item in client.iter_reviews(ORG, filters=filters)] == [] - assert (await client.get_finding(ORG, FINDING)).id == FINDING - result = await client.wait_for_review(ORG, REVIEW, timeout=2) - assert result.status == "INCOMPLETE" - assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" - assert TOKEN not in repr(client) + with tempfile.TemporaryDirectory(prefix="proofline-smoke-cov-") as cov_dir: + report_file = Path(cov_dir) / "lcov.info" + report_file.write_text("SF:a.py\nend_of_record\n", encoding="utf-8") + cov_entry = CoverageFile("lcov.info", name="pkg/lcov.info") + + async def asynchronous() -> None: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as client: + assert (await client.list_reviews(ORG, query=QUERY)).items == [] + history = await client.list_pull_request_reviews( + ORG, "repo/name", 42, filters=filters + ) + assert history.items == [] + assert [item async for item in client.iter_reviews(ORG, filters=filters)] == [] + assert (await client.get_finding(ORG, FINDING)).id == FINDING + uploaded = await client.upload_coverage_files( + ORG, REPO, SHA, [cov_entry], root=cov_dir + ) + assert uploaded.report_id == REPORT + result = await client.wait_for_review(ORG, REVIEW, timeout=2) + assert result.status == "INCOMPLETE" + assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" + assert TOKEN not in repr(client) - try: - with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: - assert client.list_reviews(ORG, query=QUERY).items == [] - history = client.list_pull_request_reviews(ORG, "repo/name", 42, filters=filters) - assert history.items == [] - assert list(client.iter_reviews(ORG, filters=filters)) == [] - assert client.get_finding(ORG, FINDING).id == FINDING - result = client.wait_for_review(ORG, REVIEW, timeout=2) - assert result.status == "INCOMPLETE" - assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" - assert TOKEN not in repr(client) - asyncio.run(asynchronous()) - assert len(calls) == 10 - finally: - server.shutdown() - server.server_close() - thread.join(timeout=2) + try: + with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: + assert client.list_reviews(ORG, query=QUERY).items == [] + history = client.list_pull_request_reviews(ORG, "repo/name", 42, filters=filters) + assert history.items == [] + assert list(client.iter_reviews(ORG, filters=filters)) == [] + assert client.get_finding(ORG, FINDING).id == FINDING + uploaded = client.upload_coverage_files(ORG, REPO, SHA, [cov_entry], root=cov_dir) + assert uploaded.report_id == REPORT + result = client.wait_for_review(ORG, REVIEW, timeout=2) + assert result.status == "INCOMPLETE" + assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" + assert TOKEN not in repr(client) + asyncio.run(asynchronous()) + assert len(calls) == 12 + finally: + server.shutdown() + server.server_close() + thread.join(timeout=2) print("Installed Python SDK sync/async HTTP smoke passed.") From fb4c11b4a860ac7fa3b73dd5c9030329aea3592f Mon Sep 17 00:00:00 2001 From: shibanalex <твой_email@example.com> Date: Sat, 28 Nov 2026 20:11:58 +0300 Subject: [PATCH 4/4] Trim verbose comments in coverage helper and tests --- proofline/coverage.py | 7 +++---- tests/test_coverage.py | 5 ++--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/proofline/coverage.py b/proofline/coverage.py index b974bdf9..bcc4210e 100644 --- a/proofline/coverage.py +++ b/proofline/coverage.py @@ -179,22 +179,21 @@ def _read_prepared_coverage_files(prepared: _PreparedCoverageUpload) -> Coverage raise ValueError(f"Coverage report path {item.raw_path!r} must be inside root.") resolved_files.append((item, real_path)) - # Report bytes alone can exceed the 30 MiB body limit; bound reads on open descriptors - # so oversized or non-regular files fail before allocating full buffers. + # Check size on the open fd first so huge files don't blow up memory. remaining_budget = MAX_BODY_BYTES reports: list[UploadedReport] = [] for item, real_path in resolved_files: raw = _read_regular_file(real_path, item.name, remaining_budget) remaining_budget -= len(raw) try: - # Strict UTF-8 keeps a leading BOM intact so content matches the written file. + # Keep leading BOM intact (don't use utf-8-sig). content = raw.decode("utf-8") except UnicodeDecodeError: raise ValueError(f"Coverage report {item.name!r} is not UTF-8 text.") from None reports.append(UploadedReport(name=item.name, content=content)) request = CoverageUploadRequest(tested_sha=prepared.tested_sha, reports=reports) - # Match httpx2's compact UTF-8 JSON encoding used by upload_coverage_reports. + # Same compact json encoding httpx2 uses on the wire. wire = json.dumps( request.to_dict(), ensure_ascii=False, diff --git a/tests/test_coverage.py b/tests/test_coverage.py index a37a67f5..9d89801b 100644 --- a/tests/test_coverage.py +++ b/tests/test_coverage.py @@ -165,7 +165,7 @@ def test_local_validation_refuses_bad_counts_duplicates_escapes_and_binary_befor ), (["../nonexistent.info"], "inside root"), ([outside], "inside root"), - # Explicit custom name must not allow reading a path outside root. + # Custom name shouldn't bypass root check. ([CoverageFile(outside, name="lcov.info")], "inside root"), ([""], "inside root"), (["."], "inside root"), @@ -264,7 +264,6 @@ def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path with pytest.raises(ValueError, match="30 MiB"): read_coverage_files(SHA, ["huge.info"], root=tmp_path) - # Compute exact compact JSON overhead for a single report named "a.info". empty_envelope = json.dumps( {"tested_sha": SHA, "reports": [{"name": "a.info", "content": ""}]}, ensure_ascii=False, @@ -277,7 +276,7 @@ def test_thirty_mib_limit_enforced_for_sparse_files_and_exact_wire_json(tmp_path built = read_coverage_files(SHA, ["a.info"], root=tmp_path) assert len(built.reports[0].content) == exact_content_len - # One extra byte — or a quote character that JSON-escapes to two bytes — crosses 30 MiB. + # +1 byte or a quote (escapes to \") pushes us over 30 MiB exact.write_bytes(b"x" * (exact_content_len + 1)) with pytest.raises(ValueError, match="30 MiB"): read_coverage_files(SHA, ["a.info"], root=tmp_path)