Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
115 changes: 112 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Severity>,
/// 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")]
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -1034,7 +1039,7 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result<Verdict> {
} 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)]
Expand Down Expand Up @@ -1094,6 +1099,7 @@ async fn show(
wait: bool,
output: &OutputArgs,
format: OutputFormat,
fail_on: Option<Severity>,
) -> anyhow::Result<Verdict> {
let deadline = if wait {
Some(poll_deadline(output.timeout)?)
Expand All @@ -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 {}",
Expand Down Expand Up @@ -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<Severity>) -> 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,
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
53 changes: 53 additions & 0 deletions src/outcome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions src/scan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ pub(crate) async fn run(
true,
&args.output,
OutputFormat::from_json(args.output.json),
None,
)
.await
}
Expand Down
1 change: 1 addition & 0 deletions src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result<Verdict
true,
&args.output,
OutputFormat::from_json(args.output.json),
None,
)
.await
}
Expand Down
59 changes: 57 additions & 2 deletions tests/local_patch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ struct Fixture {
commit_requests: Arc<Mutex<Vec<Value>>>,
file_requests: Arc<Mutex<Vec<Value>>>,
authorized: bool,
findings: Vec<Value>,
}

async fn observe(State(fixture): State<Fixture>, request: Request, next: Next) -> Response {
Expand Down Expand Up @@ -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<Value> {
async fn settled_review(State(fixture): State<Fixture>, headers: HeaderMap) -> Json<Value> {
assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}"));
Json(json!({
"id": REVIEW,
Expand All @@ -88,7 +89,7 @@ async fn settled_review(headers: HeaderMap) -> Json<Value> {
"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,
Expand Down Expand Up @@ -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<Value>) -> 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(
Expand Down Expand Up @@ -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]
Expand Down