diff --git a/README.md b/README.md index d0cef0c..0888b93 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,27 @@ is installed by rustup. Run `cargo fmt --check`, `cargo clippy --locked --all-ta `openapi.public.json` is the public API contract pinned for this revision. Server compatibility is checked in the Proofline control plane. +## Coverage uploads + +Upload reports your CI produced for an exact commit: + +```sh +proofline --org "$PROOFLINE_ORGANIZATION_ID" coverage upload \ + --repository-id "$PROOFLINE_REPOSITORY_ID" \ + --commit "$TESTED_COMMIT_SHA" --report coverage/lcov.info --json +``` + +Set `PROOFLINE_TOKEN` to a repository-restricted token with `coverage:write`. +The token holder needs current GitHub write access to the repository. Uploads +accept LCOV, Cobertura XML, JaCoCo XML and Go cover profiles. Repeat `--report` +for up to 50 UTF-8 files with distinct report names. Relative paths retain their +directories, so `packages/a/lcov.info` and `packages/b/lcov.info` are distinct. +Leading `./` is removed; relative paths cannot contain `..`. Absolute paths use +only the file name. The JSON body cannot exceed 64 MiB. The command sends the exact +40-character lowercase SHA supplied by CI and does not resolve a branch or run tests. +An identical upload returns the recorded report. Upload success records evidence; +the server evaluates the coverage check separately. + Licensed under Apache-2.0. ## Publishing diff --git a/openapi.public.json b/openapi.public.json index 17205ad..7c11188 100644 --- a/openapi.public.json +++ b/openapi.public.json @@ -953,6 +953,100 @@ ], "type": "object" }, + "CoverageRefused": { + "description": "An upload refused for its content: a symbolic or unknown commit, or a\n report that cannot be read. Nothing is stored.", + "properties": { + "detail": { + "description": "One sentence naming what was refused and why.", + "type": "string" + }, + "status": { + "description": "Always 422.", + "format": "uint16", + "maximum": 65535, + "minimum": 0, + "type": "integer" + }, + "title": { + "description": "Always `unprocessable coverage upload`.", + "type": "string" + } + }, + "required": [ + "title", + "status", + "detail" + ], + "type": "object" + }, + "CoverageUploadRequest": { + "additionalProperties": false, + "description": "The coverage reports a CI run produced for one commit.", + "properties": { + "reports": { + "description": "One to 50 reports, each LCOV, Cobertura XML, `JaCoCo` XML or a Go\n cover profile, in a JSON body of at most 64 MiB.", + "items": { + "$ref": "#/components/schemas/UploadedReport" + }, + "type": "array" + }, + "tested_sha": { + "description": "The full 40-character commit the tests ran on. GitHub must have it in\n this repository. A merge commit counts for a pull request head that is\n one of its two parents.", + "type": "string" + } + }, + "required": [ + "tested_sha", + "reports" + ], + "type": "object" + }, + "CoverageUploadResponse": { + "description": "The report the upload recorded, or the one an identical upload recorded.", + "properties": { + "covered_lines": { + "description": "Covered lines among those instrumented lines.", + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "created": { + "description": "False when the same reports for this commit were already recorded.", + "type": "boolean" + }, + "formats": { + "description": "The format of each report, in upload order.", + "items": { + "type": "string" + }, + "type": "array" + }, + "instrumented_lines": { + "description": "Instrumented lines across the reports, a file two reports name under\n one path counted once.", + "format": "uint64", + "minimum": 0, + "type": "integer" + }, + "report_id": { + "description": "The recorded report.", + "format": "uuid", + "type": "string" + }, + "tested_sha": { + "description": "The commit the reports tested, as the upload named it.", + "type": "string" + } + }, + "required": [ + "report_id", + "tested_sha", + "created", + "formats", + "instrumented_lines", + "covered_lines" + ], + "type": "object" + }, "CustomerAssessment": { "properties": { "checks": { @@ -6217,6 +6311,24 @@ ], "type": "object" }, + "UploadedReport": { + "additionalProperties": false, + "properties": { + "content": { + "description": "The report text, exactly as the coverage tool wrote it.", + "type": "string" + }, + "name": { + "description": "A relative name for the report, such as `web/lcov.info`, unique in\n the upload.", + "type": "string" + } + }, + "required": [ + "name", + "content" + ], + "type": "object" + }, "WalkthroughFileView": { "properties": { "additions": { @@ -6882,6 +6994,94 @@ "x-proofline-token-scope": "reviews:request" } }, + "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports": { + "post": { + "description": "Records the LCOV, Cobertura, JaCoCo or Go coverage reports a CI run produced for one exact commit GitHub has in the repository, for COVERAGE checks that accept uploads. A branch, tag or abbreviated SHA, or a report that cannot be read, gets 422 and stores nothing. Requires a repository-restricted token and live GitHub write access; the same reports for the same commit return the report already recorded.", + "operationId": "upload_coverage_reports", + "parameters": [ + { + "in": "path", + "name": "org_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + }, + { + "in": "path", + "name": "repo_id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + }, + "style": "simple" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadRequest" + } + } + }, + "description": "The coverage reports a CI run produced for one commit.", + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadResponse" + } + } + }, + "description": "The report the upload recorded, or the one an identical upload recorded." + }, + "201": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageUploadResponse" + } + } + }, + "description": "The report the upload recorded, or the one an identical upload recorded." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CoverageRefused" + } + } + }, + "description": "An upload refused for its content: a symbolic or unknown commit, or a\n report that cannot be read. Nothing is stored." + }, + "default": { + "content": { + "application/problem+json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "An RFC 9457 problem; the HTTP status remains authoritative." + } + }, + "security": [ + { + "bearerAuth": [] + } + ], + "summary": "Upload coverage reports", + "x-proofline-token-scope": "coverage:write" + } + }, "/api/v1/organizations/{org_id}/repositories/{repo_id}/file-reviews": { "post": { "description": "Reviews up to twenty exact file paths at one pushed commit. Requires live GitHub read access and verifies every path at that commit. The retained selection is immutable; a repeat by the same person returns its review. Results remain in Proofline and are never posted to GitHub.", diff --git a/src/api.rs b/src/api.rs index 32ce193..d6ed9f7 100644 --- a/src/api.rs +++ b/src/api.rs @@ -11,9 +11,10 @@ use url::Url; use uuid::Uuid; use crate::model::{ - CommitReviewRequest, CommitReviewResponse, FileReviewRequest, FileReviewResponse, - PatchReviewRequest, PatchReviewResponse, RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, - RunNowRequest, RunNowResponse, StopResponse, + CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, + FileReviewRequest, FileReviewResponse, PatchReviewRequest, PatchReviewResponse, + RepositoryNames, ReviewDetail, ReviewPage, RunNowMode, RunNowRequest, RunNowResponse, + StopResponse, }; use crate::origin::Origin; use crate::text::terminal_safe; @@ -535,6 +536,25 @@ impl Api { Err(self.http.problem(&reply)) } + /// Uploads reports for one exact tested commit. Both a new report and an + /// identical upload return the recorded report. One HTTP attempt. + pub async fn upload_coverage_reports( + &self, + repository_id: Uuid, + request: &CoverageUploadRequest, + ) -> Result { + let repository = repository_id.to_string(); + let url = self.url(&["repositories", &repository, "coverage-reports"]); + let (reply, _) = self + .http + .send(self.request(Method::POST, url).json(request)) + .await?; + if matches!(reply.status, StatusCode::OK | StatusCode::CREATED) { + return self.decode(&reply.body); + } + Err(self.http.problem(&reply)) + } + /// Requests whole-file review of a selection at one pushed commit. pub async fn request_file_review( &self, diff --git a/src/coverage.rs b/src/coverage.rs new file mode 100644 index 0000000..d8294e2 --- /dev/null +++ b/src/coverage.rs @@ -0,0 +1,143 @@ +//! Uploads customer-produced coverage at an explicit tested commit. + +use std::collections::BTreeSet; +use std::io::Write as _; +use std::path::{Component, Path, PathBuf}; + +use anyhow::{Context as _, bail}; +use clap::{Args, Subcommand}; +use tokio::io::AsyncReadExt as _; +use uuid::Uuid; + +use crate::api::Api; +use crate::model::{CoverageUploadRequest, UploadedReport}; + +const MAX_BODY_BYTES: usize = 64 << 20; + +#[derive(Debug, Subcommand)] +pub(crate) enum Command { + /// Upload LCOV, Cobertura, `JaCoCo` or Go reports. Requires coverage:write + /// on a token restricted to this repository, with live GitHub write access. + Upload(UploadArgs), +} + +#[derive(Debug, Args)] +pub(crate) struct UploadArgs { + /// Full lowercase 40-character SHA that the reports tested; never a branch. + #[arg(long, value_name = "SHA")] + commit: String, + /// Proofline repository ID receiving the reports. + #[arg(long, value_name = "UUID")] + repository_id: Uuid, + /// Report file. Relative paths name reports; absolute paths use the file name. + /// Repeat for up to 50 reports with distinct names. + #[arg(long = "report", value_name = "FILE", required = true)] + reports: Vec, + /// Print the recorded upload as JSON. + #[arg(long)] + json: bool, +} + +pub(crate) async fn request(args: &UploadArgs) -> anyhow::Result { + if args.commit.len() != 40 + || !args + .commit + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + { + bail!("--commit must name the full lowercase 40-character SHA the reports tested"); + } + if args.reports.is_empty() || args.reports.len() > 50 { + bail!("name between 1 and 50 coverage report files"); + } + let mut names = BTreeSet::new(); + let mut reports = Vec::with_capacity(args.reports.len()); + let mut remaining = MAX_BODY_BYTES; + for path in &args.reports { + let name = report_name(path)?; + if !names.insert(name.clone()) { + bail!("coverage report names must be distinct: {name:?}"); + } + let file = tokio::fs::File::open(path) + .await + .with_context(|| format!("could not open coverage report {}", path.display()))?; + let mut bytes = Vec::new(); + file.take(u64::try_from(remaining)? + 1) + .read_to_end(&mut bytes) + .await + .with_context(|| format!("could not read coverage report {}", path.display()))?; + if bytes.len() > remaining { + bail!("the coverage upload body is larger than 64 MiB"); + } + remaining -= bytes.len(); + reports.push(UploadedReport { + name, + content: String::from_utf8(bytes) + .with_context(|| format!("coverage report {} is not UTF-8", path.display()))?, + }); + } + let request = CoverageUploadRequest { + tested_sha: args.commit.clone(), + reports, + }; + if serde_json::to_vec(&request)?.len() > MAX_BODY_BYTES { + bail!("the coverage upload body is larger than 64 MiB after JSON encoding"); + } + Ok(request) +} + +fn report_name(path: &Path) -> anyhow::Result { + let path = if path.is_absolute() { + Path::new( + path.file_name() + .context("a coverage report needs a file name")?, + ) + } else { + path + }; + let mut parts = Vec::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::Normal(part) => { + let part = part + .to_str() + .filter(|value| !value.contains(['\\', ':'])) + .context("coverage report names must be UTF-8 without a backslash or colon")?; + parts.push(part); + } + _ => bail!("relative coverage report paths cannot contain parent directories"), + } + } + if parts.is_empty() { + bail!("a coverage report needs a file name"); + } + Ok(parts.join("/")) +} + +pub(crate) async fn upload( + api: &Api, + args: &UploadArgs, + request: &CoverageUploadRequest, +) -> anyhow::Result<()> { + let result = api + .upload_coverage_reports(args.repository_id, request) + .await?; + let mut stdout = std::io::stdout().lock(); + if args.json { + writeln!(stdout, "{}", serde_json::to_string(&result)?)?; + } else { + writeln!( + stdout, + "Coverage report {}: {} of {} instrumented lines covered; tested commit {}.", + result.report_id, + result.covered_lines, + result.instrumented_lines, + crate::text::terminal_safe(&result.tested_sha), + )?; + if !result.created { + writeln!(stdout, "These reports were already recorded.")?; + } + } + Ok(()) +} diff --git a/src/lib.rs b/src/lib.rs index f4880be..65c17d1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ mod agent; pub mod api; +mod coverage; pub mod credentials; pub mod device; pub mod git; @@ -106,6 +107,9 @@ enum Command { /// Commands for a CI job. #[command(subcommand)] Ci(CiCommand), + /// Upload coverage reports produced by your CI. + #[command(subcommand)] + Coverage(coverage::Command), /// Install or remove Git hooks that review each commit and push. Hooks(hooks::HooksArgs), /// Run an installed Git hook. Git calls this from the hook script. @@ -420,6 +424,12 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result hooks::manage(args).await.map(|()| Verdict::Done), + Command::Coverage(coverage::Command::Upload(args)) => { + let request = coverage::request(&args).await?; + let api = connect(Http::new(origin)?, token, cli.org).await?; + coverage::upload(&api, &args, &request).await?; + Ok(Verdict::Done) + } Command::Hook(args) => hooks::run(args, origin, token, cli.org).await, } } diff --git a/src/model.rs b/src/model.rs index bfca8d7..2420134 100644 --- a/src/model.rs +++ b/src/model.rs @@ -6,6 +6,28 @@ use serde::{Deserialize, Serialize}; use uuid::Uuid; +#[derive(Debug, Deserialize, Serialize)] +pub struct CoverageUploadRequest { + pub tested_sha: String, + pub reports: Vec, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct UploadedReport { + pub name: String, + pub content: String, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct CoverageUploadResponse { + pub report_id: Uuid, + pub tested_sha: String, + pub created: bool, + pub formats: Vec, + pub instrumented_lines: u64, + pub covered_lines: u64, +} + #[derive(Debug, Deserialize, Serialize)] pub struct ReviewPage { pub items: Vec, diff --git a/tests/contract.rs b/tests/contract.rs index 9088aed..1cd1a83 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -5,10 +5,11 @@ use std::process::Command; use proofline_cli::model::{ Assessment, Check, Checks, CodeAssessment, CommitReviewRequest, CommitReviewResponse, - EvidenceRef, FileReviewRequest, FileReviewResponse, FileScope, FilterChoice, Finding, - OpenItems, PatchReviewRequest, PatchReviewResponse, RepositoryName, RepositoryNames, - ReviewDetail, ReviewFilters, ReviewPage, ReviewSubject, ReviewSummary, RunNowMode, - RunNowRequest, RunNowResponse, StopResponse, + CoverageUploadRequest, CoverageUploadResponse, EvidenceRef, FileReviewRequest, + FileReviewResponse, FileScope, FilterChoice, Finding, OpenItems, PatchReviewRequest, + PatchReviewResponse, RepositoryName, RepositoryNames, ReviewDetail, ReviewFilters, ReviewPage, + ReviewSubject, ReviewSummary, RunNowMode, RunNowRequest, RunNowResponse, StopResponse, + UploadedReport, }; use serde::Serialize; use serde::de::DeserializeOwned; @@ -147,6 +148,9 @@ fn holds(name: &str) { #[test] fn types_match_the_public_contract() { holds::("ReviewPage"); + holds::("CoverageUploadRequest"); + holds::("CoverageUploadResponse"); + holds::("UploadedReport"); holds::("ReviewFilters"); holds::("FilterChoice"); holds::("RepositoryNames"); @@ -230,6 +234,10 @@ fn operations_the_cli_calls_exist() { ("get", "/api/v1/organizations/{org_id}/reviews"), ("get", "/api/v1/organizations/{org_id}/reviews/{review_id}"), ("get", "/api/v1/organizations/{org_id}/repository-names"), + ( + "post", + "/api/v1/organizations/{org_id}/repositories/{repo_id}/coverage-reports", + ), ( "post", "/api/v1/organizations/{org_id}/reviews/{review_id}/stop", diff --git a/tests/http.rs b/tests/http.rs index e07b0a4..c51f002 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -23,8 +23,157 @@ const TOKEN: &str = "pld_secretsecretsecret"; const REPOSITORY: &str = "0190f3a0-0000-7000-8000-000000000022"; const SELECTED_REVIEW: &str = "0190f3a0-0000-7000-8000-000000000033"; +#[tokio::test] +async fn coverage_upload_preserves_the_tested_commit_and_reports_refusals() { + let directory = tempfile::tempdir().unwrap(); + let report = directory.path().join("packages/a/coverage/lcov.info"); + let content = "TN:\nSF:src/lib.rs\nDA:1,1\nDA:2,0\nend_of_record\n"; + for path in [ + "packages/a/coverage/lcov.info", + "packages/b/coverage/lcov.info", + ] { + let path = directory.path().join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); + } + let requests = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&requests); + let sha = "a".repeat(40); + let expected_sha = sha.clone(); + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/coverage-reports"), + post(move |headers: HeaderMap, Json(body): Json| { + let observed = Arc::clone(&observed); + let expected_sha = expected_sha.clone(); + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + assert_eq!( + body, + json!({ + "tested_sha": expected_sha, + "reports": [ + { "name": "packages/a/coverage/lcov.info", "content": content }, + { "name": "packages/b/coverage/lcov.info", "content": content }, + ], + }) + ); + let attempt = observed.fetch_add(1, Ordering::SeqCst); + if attempt >= 2 { + return ( + StatusCode::UNPROCESSABLE_ENTITY, + Json( + json!({"title": "unprocessable coverage upload", "status": 422, + "detail": "GitHub has no commit at the tested SHA"}), + ), + ); + } + ( + if attempt == 0 { + StatusCode::CREATED + } else { + StatusCode::OK + }, + Json( + json!({ "report_id": SELECTED_REVIEW, "tested_sha": expected_sha, + "created": attempt == 0, "formats": ["LCOV"], + "instrumented_lines": 2, "covered_lines": 1 }), + ), + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let args = [ + "coverage", + "upload", + "--repository-id", + REPOSITORY, + "--commit", + &sha, + "--report", + "./packages/a/coverage/lcov.info", + "--report", + "packages/b/coverage/lcov.info", + "--json", + ]; + for created in [true, false] { + let output = cli_in(&origin, &args, directory.path()).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["created"], created); + assert_eq!(result["tested_sha"], sha); + assert_eq!(result["covered_lines"], 1); + assert_eq!(result["instrumented_lines"], 2); + } + let output = cli_in(&origin, &args, directory.path()).await; + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("HTTP 422")); + assert!(!String::from_utf8_lossy(&output.stderr).contains(TOKEN)); + assert_eq!(requests.load(Ordering::SeqCst), 3); + let output = cli( + &origin, + &[ + "coverage", + "upload", + "--repository-id", + REPOSITORY, + "--commit", + "main", + "--report", + report.to_str().unwrap(), + ], + ) + .await; + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("full lowercase 40-character SHA")); + assert_eq!(requests.load(Ordering::SeqCst), 3); + server.abort(); +} + +#[tokio::test] +async fn coverage_upload_rejects_ambiguous_and_oversized_files_before_http() { + let directory = tempfile::tempdir().unwrap(); + let report = directory.path().join("lcov.info"); + std::fs::write(&report, "SF:lib.rs\nDA:1,1\nend_of_record\n").unwrap(); + let path = report.to_str().unwrap(); + let sha = "a".repeat(40); + // This origin has no server: validation must fail before HTTP or credentials. + let args = [ + "coverage", + "upload", + "--repository-id", + REPOSITORY, + "--commit", + &sha, + "--report", + path, + "--report", + path, + ]; + let output = cli("http://127.0.0.1:1", &args).await; + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("report names must be distinct")); + std::fs::File::create(&report) + .unwrap() + .set_len((64 << 20) + 1) + .unwrap(); + let output = cli("http://127.0.0.1:1", &args[..8]).await; + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("larger than 64 MiB")); +} + async fn cli(origin: &str, args: &[&str]) -> std::process::Output { let directory = tempfile::tempdir().unwrap(); + cli_in(origin, args, directory.path()).await +} + +async fn cli_in(origin: &str, args: &[&str], directory: &std::path::Path) -> std::process::Output { tokio::time::timeout( std::time::Duration::from_secs(15), tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) @@ -32,7 +181,7 @@ async fn cli(origin: &str, args: &[&str]) -> std::process::Output { .args(args) .env("PROOFLINE_TOKEN", TOKEN) .env("PATH", "") - .current_dir(directory.path()) + .current_dir(directory) .kill_on_drop(true) .output(), )