diff --git a/README.md b/README.md index fd56b0f..c56770c 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. +`proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`. + In GitHub Actions, `proofline ci review --annotations` prints unresolved findings as workflow annotations at verified cited lines. Findings without a verified head location appear on the job. The review link contains the full result. ## Scans diff --git a/src/lib.rs b/src/lib.rs index 133dd8a..6273dcc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -318,6 +318,10 @@ struct ReviewArgs { /// Return once the review is requested instead of waiting for its result. #[arg(long)] no_wait: bool, + /// Exit 3 when the completed review has an open finding at or above this + /// severity, as `ci review --fail-on` does. + #[arg(long, value_enum, value_name = "SEVERITY", conflicts_with = "no_wait")] + fail_on: Option, /// Include secret-shaped patch content from this exact repository-relative /// path. Repeat for more paths; each override applies only to local review. #[arg(long, value_name = "PATH", conflicts_with = "pr")] @@ -381,7 +385,7 @@ pub enum Verdict { /// Proofline did not answer: it was unreachable, failed on its side, or /// had no finished review before the deadline. Unavailable, - /// A complete review has an open finding at or above `ci review --fail-on`. + /// A complete review has an open finding at or above `--fail-on`. ThresholdReached, /// A Git hook's exit policy refuses the commit or push. Blocked, @@ -1002,6 +1006,7 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result true, &args.output, OutputFormat::from_json(args.output.json), + args.fail_on, ) .await } @@ -1034,7 +1039,7 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { } else { OutputFormat::from_json(args.output.json) }; - show(api, review_id, args.wait, &args.output, format).await + show(api, review_id, args.wait, &args.output, format, None).await } #[derive(Debug, thiserror::Error)] @@ -1094,6 +1099,7 @@ async fn show( wait: bool, output: &OutputArgs, format: OutputFormat, + fail_on: Option, ) -> anyhow::Result { let deadline = if wait { Some(poll_deadline(output.timeout)?) @@ -1104,7 +1110,19 @@ async fn show( let (raw, detail, state) = read_review(api, review_id, deadline, sarif).await?; print_review(api, review_id, raw, &detail, state, format)?; match state { - Some(Outcome::Completed) => return Ok(Verdict::Done), + Some(Outcome::Completed) => { + let verdict = review_verdict(&detail, fail_on); + match verdict { + Verdict::ThresholdReached => { + say("The review has an open finding at or above the --fail-on severity."); + } + Verdict::Unavailable => say( + "Proofline returned the completed review without `open_items`, so --fail-on could not be measured. It is not a pass.", + ), + Verdict::Done | Verdict::NotComplete | Verdict::Blocked => {} + } + return Ok(verdict); + } Some(ended) => say_not_complete(ended), None if wait => say(&format!( "The review was still {} after {} minutes; it continues at {}", @@ -1446,6 +1464,28 @@ fn ci_verdict( } } +/// How `review --fail-on` ends for a complete review. A pull request counts +/// its open items, as `ci review` does; other reviews have no finding +/// decisions, so their findings count, as in a Git hook. +fn review_verdict(detail: &ReviewDetail, fail_on: Option) -> Verdict { + let Some(threshold) = fail_on else { + return Verdict::Done; + }; + if detail.kind == "PULL_REQUEST" { + return ci_verdict( + Some(Outcome::Completed), + detail.open_items.as_ref(), + outcome::code_assessment(detail), + fail_on, + ); + } + if outcome::findings_reach(detail, threshold) { + Verdict::ThresholdReached + } else { + Verdict::Done + } +} + fn print_review( api: &Api, requested_review: Uuid, @@ -1816,6 +1856,75 @@ mod tests { assert_eq!(next_pause(20, at(10), at(3), None), Duration::ZERO); } + #[test] + fn review_fail_on_measures_pull_requests_by_open_items_and_others_by_findings() { + let detail = |kind: &str, open_items: serde_json::Value| -> ReviewDetail { + serde_json::from_value(json!({ + "id": "0190f3a0-0000-7000-8000-000000000033", + "kind": kind, + "status": "COMPLETED", + "assessment_count": 1, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-000000000033", + "environment_display_name": "production", + "status": "COMPLETED", + "findings": [{ + "id": "0190f3a0-0000-7000-8000-000000000044", + "finding_fingerprint": null, + "severity": "SERIOUS", + "risk_domain": "resource_capacity", + "claim": "The pool outgrows the connection limit.", + "impact": "Connections are refused during the rollout.", + "lifecycle_state": "NEW", + "remediation": null, + "evidence_refs": [], + }], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + "incompleteness_kind": null, + "reason_codes": null, + "release_evidence_gap": null, + }], + "code_assessment": null, + "base_commit_sha": "b".repeat(40), + "head_commit_sha": "c".repeat(40), + "open_items": open_items, + "pull_request_number": null, + "repository_full_name": "acme/app", + "run_number": null, + })) + .unwrap() + }; + let (warning, serious) = (Some(Severity::Warning), Some(Severity::Serious)); + for kind in ["PATCH", "COMMIT", "FILES"] { + let review = detail(kind, serde_json::Value::Null); + assert_eq!( + review_verdict(&review, serious), + Verdict::ThresholdReached, + "{kind}" + ); + assert_eq!( + review_verdict(&review, warning), + Verdict::ThresholdReached, + "{kind}" + ); + assert_eq!(review_verdict(&review, None), Verdict::Done, "{kind}"); + } + // The finding was dismissed. + let dismissed = detail( + "PULL_REQUEST", + json!({ "open_findings": 0, "serious_findings": 0 }), + ); + assert_eq!(review_verdict(&dismissed, serious), Verdict::Done); + let open = detail( + "PULL_REQUEST", + json!({ "open_findings": 1, "serious_findings": 1 }), + ); + assert_eq!(review_verdict(&open, serious), Verdict::ThresholdReached); + let unmeasured = detail("PULL_REQUEST", serde_json::Value::Null); + assert_eq!(review_verdict(&unmeasured, serious), Verdict::Unavailable); + assert_eq!(review_verdict(&unmeasured, None), Verdict::Done); + } + #[test] fn ci_measures_only_a_complete_review_against_the_open_finding_counts() { let open = |open_findings, serious_findings| OpenItems { diff --git a/src/main.rs b/src/main.rs index 9dfcd42..7731b05 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,8 +50,8 @@ fn main() -> ExitCode { Ok(Verdict::NotComplete) => ExitCode::from(2), // Proofline gave no answer in time; distinct from the caller's error. Ok(Verdict::Unavailable) => ExitCode::from(4), - // `ci review --fail-on`: the review is complete and a finding reaches - // the caller's threshold. + // `--fail-on`: the review is complete and a finding reaches the + // caller's threshold. Ok(Verdict::ThresholdReached) => ExitCode::from(3), Ok(Verdict::Blocked) => ExitCode::FAILURE, Err(error) => { diff --git a/src/outcome.rs b/src/outcome.rs index e8aa9bb..1b34fe1 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -170,6 +170,17 @@ pub(crate) fn resolved(finding: &Finding) -> bool { finding.lifecycle_state == "RESOLVED" } +/// Whether an unresolved finding of a review without finding decisions +/// reaches `threshold`. +pub(crate) fn findings_reach(review: &ReviewDetail, threshold: Severity) -> bool { + let environment = review.assessments.iter().any(|assessment| { + assessment.findings.iter().any(|finding| { + finding.lifecycle_state != "RESOLVED" && threshold.reached_by(&finding.severity) + }) + }); + environment || code_assessment(review).is_some_and(|code| code_reaches(code, threshold)) +} + /// CODE has no World receipts or environment checks. Its recorded status, /// public reason codes and incompleteness are the only completion evidence for /// the code lane. Reason codes come first, as for an environment assessment. @@ -331,6 +342,48 @@ mod tests { } } + fn finding(severity: &str, lifecycle_state: &str) -> Finding { + Finding { + id: Uuid::nil(), + finding_fingerprint: None, + severity: severity.to_owned(), + risk_domain: "resource_capacity".to_owned(), + claim: "the pool outgrows the database's connection limit".to_owned(), + impact: "new connections are refused during the rollout".to_owned(), + lifecycle_state: lifecycle_state.to_owned(), + remediation: None, + evidence_refs: Vec::new(), + } + } + + #[test] + fn findings_reach_counts_unresolved_findings_at_or_above_the_threshold() { + let with = |severity: &str, lifecycle_state: &str| { + let mut production = assessment("COMPLETED"); + production.findings = vec![finding(severity, lifecycle_state)]; + let mut detail = review("COMPLETED", vec![production], 1); + detail.kind = "COMMIT".to_owned(); + detail + }; + for (severity, lifecycle_state, threshold, reaches) in [ + ("SERIOUS", "NEW", Severity::Serious, true), + ("SERIOUS", "NEW", Severity::Warning, true), + ("WARNING", "NEW", Severity::Warning, true), + ("WARNING", "UNCHANGED", Severity::Serious, false), + ("SERIOUS", "REINTRODUCED", Severity::Serious, true), + ("SERIOUS", "RESOLVED", Severity::Warning, false), + ("CRITICAL", "NEW", Severity::Serious, true), + ] { + assert_eq!( + findings_reach(&with(severity, lifecycle_state), threshold), + reaches, + "{severity} {lifecycle_state} {threshold:?}" + ); + } + let clean = review("COMPLETED", vec![assessment("COMPLETED")], 1); + assert!(!findings_reach(&clean, Severity::Warning)); + } + #[test] fn running_reviews_are_not_terminal() { assert_eq!(terminal(&review("RUNNING", Vec::new(), 1)), None); diff --git a/src/scan.rs b/src/scan.rs index 667e9c3..dcd9401 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -135,6 +135,7 @@ pub(crate) async fn run( true, &args.output, OutputFormat::from_json(args.output.json), + None, ) .await } diff --git a/src/tools.rs b/src/tools.rs index 364206b..d7c7ad5 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -103,6 +103,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result>>, file_requests: Arc>>, authorized: bool, + findings: Vec, } async fn observe(State(fixture): State, request: Request, next: Next) -> Response { @@ -77,7 +78,7 @@ async fn upload( } /// A settled patch review that re-verified `FINDING` against the patch. -async fn settled_review(headers: HeaderMap) -> Json { +async fn settled_review(State(fixture): State, headers: HeaderMap) -> Json { assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); Json(json!({ "id": REVIEW, @@ -88,7 +89,7 @@ async fn settled_review(headers: HeaderMap) -> Json { "id": REVIEW, "environment_display_name": "production", "status": "COMPLETED", - "findings": [], + "findings": fixture.findings, "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, "incompleteness_kind": null, "reason_codes": null, @@ -140,12 +141,17 @@ struct Server { impl Server { async fn start(authorized: bool) -> Self { + Self::with_findings(authorized, Vec::new()).await + } + + async fn with_findings(authorized: bool, findings: Vec) -> Self { let fixture = Fixture { requests: Arc::default(), uploads: Arc::default(), commit_requests: Arc::default(), file_requests: Arc::default(), authorized, + findings, }; let app = Router::new() .route( @@ -714,6 +720,55 @@ async fn pushed_commits_send_two_exact_shas_and_no_patch() { server.close().await; } +/// `--fail-on` exits 3 at or above the threshold and refuses `--no-wait`. +#[tokio::test] +async fn fail_on_exits_three_for_a_pushed_commit_finding_at_the_threshold() { + let checkout = Checkout::new(&[("kept.txt", "base\n")]).await; + checkout.write("kept.txt", "pushed\n").await; + checkout.git(&["commit", "-qam", "pushed"]).await; + let finding = |severity: &str| { + json!({ + "id": FINDING, + "finding_fingerprint": null, + "severity": severity, + "risk_domain": "resource_capacity", + "claim": "The pool outgrows the database's connection limit.", + "impact": "New connections are refused during the rollout.", + "lifecycle_state": "NEW", + "remediation": null, + "evidence_refs": [], + }) + }; + for (findings, flags, code) in [ + (vec![finding("SERIOUS")], vec!["--fail-on", "serious"], 3), + (vec![finding("SERIOUS")], vec!["--fail-on", "warning"], 3), + (vec![finding("WARNING")], vec!["--fail-on", "serious"], 0), + (vec![finding("SERIOUS")], vec![], 0), + (vec![], vec!["--fail-on", "warning"], 0), + ] { + let server = Server::with_findings(true, findings).await; + let mut flags = flags.clone(); + flags.extend(["--commit", "HEAD"]); + let output = checkout.review_and_wait(&server, &[], &flags).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(code), "{flags:?}: {stderr}"); + assert_eq!( + stderr.contains("at or above the --fail-on severity"), + code == 3, + "{flags:?}: {stderr}" + ); + assert_eq!(server.fixture.commit_requests.lock().unwrap().len(), 1); + server.close().await; + } + let server = Server::start(true).await; + let output = checkout + .review(&server, &[], &["--fail-on", "serious", "--commit", "HEAD"]) + .await; + assert_eq!(output.status.code(), Some(1)); + server.assert_no_requests(); + server.close().await; +} + /// Even the root commit is a valid whole-file subject; the index and working /// tree cannot change its selected paths or contribute source bytes. #[tokio::test]