From 26c181646d13df5919eaac98c9fc8d96114dc595 Mon Sep 17 00:00:00 2001 From: Celestial-0 Date: Mon, 30 Nov 2026 09:20:45 +0000 Subject: [PATCH] Verify the requested head before printing findings Allow findings --review ID --head SHA to read a known review outside a checkout. Apply the same head check to lookups by explicit SHA and the checkout HEAD, and reject a missing or different head before emitting text, JSON or SARIF. SHA comparison is case-insensitive. Add regression tests for a detail from another commit, implicit HEAD and SARIF output. --- README.md | 2 + src/hooks.rs | 7 +- src/lib.rs | 174 ++++++++++++++++++++++++++++++------------------- src/scan.rs | 2 +- src/tools.rs | 2 +- tests/http.rs | 109 +++++++++++++++++++++++++++---- tests/sarif.rs | 94 ++++++++++++++++++++++++++ 7 files changed, 307 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index eea0165..37cf57a 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline reviews --repository-id UUID --cursor CURSOR` returns one page with its continuation metadata, and all flags are optional. `proofline routing REVIEW_ID` reads recorded routing. `proofline run --repo owner/name --pr 7 --run 2` reads one retained run, and `proofline history --repo owner/name --pr 7` reads all recorded runs. Both commands send the API the name without its owner, and use the response only when its repository choices list `owner/name`, or the Git remote's owner and name, among the organization's reviewed repositories. A repository with no reviews in the organization exits nonzero. `proofline findings --pr 7` finds the pull request's newest review through the same route and counts only runs of the repository whose full name matches. None of these commands reads the organization's review list. +`proofline findings --review ID --head SHA` reads the named review directly and verifies its head before printing findings. This works outside a checkout, including with `--wait`, `--json` or `--sarif`. A different or missing head in the result exits 1 with empty stdout. A search with `findings --head SHA`, or plain `findings` at the checkout's HEAD, also verifies the detail returned for the selected review. + `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`. diff --git a/src/hooks.rs b/src/hooks.rs index 1de7d43..34b5edc 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -495,9 +495,10 @@ async fn request( verify_finding_ids: Vec::new(), }; let requested = api.request_patch_review(repository_id, &request).await?; - let (_, detail, state) = read_review(api, requested.review_id, Some(deadline), false) - .await? - .context("Proofline did not answer a read of the review before the deadline")?; + let (_, detail, state) = + read_review(api, requested.review_id.into(), Some(deadline), false) + .await? + .context("Proofline did not answer a read of the review before the deadline")?; anyhow::Ok((requested.review_id, detail, state)) }; match requested.await { diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..237fc30 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -369,14 +369,13 @@ struct ReviewArgs { } #[derive(Debug, Args)] -#[group(multiple = false)] struct Selector { /// Latest review of this pull request. - #[arg(long, value_name = "NUMBER")] + #[arg(long, value_name = "NUMBER", conflicts_with_all = ["head", "review"])] pr: Option, - /// Latest review whose head is exactly this pushed commit. Defaults to - /// the checkout's HEAD. - #[arg(long, value_name = "SHA")] + /// Find the latest review at this commit, or verify the head of --review ID. + /// With no selector, use the checkout's HEAD. + #[arg(long, value_name = "SHA", value_parser = git::commit_sha)] head: Option, /// This review. #[arg(long, value_name = "ID")] @@ -391,7 +390,7 @@ struct FindingsArgs { #[arg(long)] wait: bool, /// Export this retained pull-request review as SARIF 2.1.0. - #[arg(long, requires = "review", conflicts_with_all = ["json", "pr", "head"])] + #[arg(long, requires = "review", conflicts_with = "json")] sarif: bool, #[command(flatten)] repository: RepositoryArgs, @@ -601,9 +600,6 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - if let Some(head) = &args.selector.head { - git::commit_sha(head)?; - } let api = connect(Http::new(origin)?, token, cli.org).await?; findings(&api, &args).await } @@ -1197,7 +1193,7 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result } show( api, - review_id, + review_id.into(), true, &args.output, OutputFormat::from_json(args.output.json), @@ -1207,22 +1203,27 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result } async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { - let review_id = match (&args.selector.review, args.selector.pr) { - (Some(id), _) => *id, - (None, Some(number)) => pull_request_review(api, &args.repository, number).await?, + let (review_id, expected_head) = match (args.selector.review, args.selector.pr) { + (Some(id), _) => (id, args.selector.head.clone()), + (None, Some(number)) => ( + pull_request_review(api, &args.repository, number).await?, + None, + ), (None, None) => { let sha = match &args.selector.head { - Some(raw) => git::commit_sha(raw)?, + Some(head) => head.clone(), None => git::head().await?, }; let (name, repository_id) = reviewed_repository(api, &args.repository).await?; // An audit is a revision scan of this commit too, but its // findings are in its report, so it never answers for the head. - latest(api, repository_id, &sha, |item| { - item.audit_mode.is_none() && item.head_commit_sha.as_deref() == Some(sha.as_str()) + let id = latest(api, repository_id, &sha, |item| { + item.audit_mode.is_none() + && head_matches(item.head_commit_sha.as_deref(), &sha) }) .await? - .with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr"))? + .with_context(|| format!("no review of {name} has head commit {sha}; push it and open a pull request, or name one with --pr"))?; + (id, Some(sha)) } }; let format = if args.sarif { @@ -1230,7 +1231,18 @@ 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, None).await + show( + api, + ReviewTarget { + id: review_id, + head: expected_head.as_deref(), + }, + args.wait, + &args.output, + format, + None, + ) + .await } #[derive(Debug, thiserror::Error)] @@ -1251,6 +1263,36 @@ fn poll_deadline(minutes: u64) -> Result); +/// The review a caller expects to read. A held commit must be confirmed +/// before its findings can be returned. +#[derive(Clone, Copy)] +struct ReviewTarget<'a> { + id: Uuid, + head: Option<&'a str>, +} + +impl From for ReviewTarget<'_> { + fn from(id: Uuid) -> Self { + Self { id, head: None } + } +} + +impl ReviewTarget<'_> { + fn validate(self, detail: &ReviewDetail, sarif: bool, polling: bool) -> anyhow::Result<()> { + outcome::same_review(detail, self.id)?; + // Only an intermediate text or JSON read may wait for a missing head. + if let Some(head) = self.head + && (!polling || sarif || detail.head_commit_sha.is_some()) + { + confirm_head(detail, head)?; + } + if sarif { + sarif::validate_subject(detail, self.id)?; + } + Ok(()) + } +} + /// Reads the review, polling until it finishes or `deadline` passes. Without /// a deadline, or with one already passed (`--timeout 0`), it reads once. /// Otherwise no read starts at or after the deadline, and a read still @@ -1261,46 +1303,40 @@ type ReviewRead = (serde_json::Value, ReviewDetail, Option); /// a result for a different review decide this one's outcome. async fn read_review( api: &Api, - review_id: Uuid, + target: ReviewTarget<'_>, deadline: Option, sarif: bool, ) -> anyhow::Result> { - let deadline = match deadline { - Some(deadline) if tokio::time::Instant::now() < deadline => deadline, - _ => return read_review_once(api, review_id, sarif).await.map(Some), - }; + let deadline = deadline.filter(|end| tokio::time::Instant::now() < *end); let mut delay = FIRST_POLL_SECONDS; - loop { - let Ok(read) = - tokio::time::timeout_at(deadline, read_review_once(api, review_id, sarif)).await - else { - return Ok(None); + let last = loop { + let request = api.review(target.id); + let (raw, detail) = if let Some(end) = deadline { + let Ok(response) = tokio::time::timeout_at(end, request).await else { + return Ok(None); + }; + response? + } else { + request.await? }; - let read = read?; + let state = outcome::terminal(&detail); let now = tokio::time::Instant::now(); - if read.2.is_some() || now >= deadline { - return Ok(Some(read)); - } + let Some(end) = deadline.filter(|end| state.is_none() && now < *end) else { + break (raw, detail, state); + }; + target.validate(&detail, sarif, true)?; say(&format!( "Review is {}; checking again in {delay} seconds.", - text::one_line(&read.1.status) + text::one_line(&detail.status) )); - tokio::time::sleep_until(deadline.min(now + Duration::from_secs(delay))).await; - if tokio::time::Instant::now() >= deadline { - return Ok(Some(read)); + tokio::time::sleep_until(end.min(now + Duration::from_secs(delay))).await; + if tokio::time::Instant::now() >= end { + break (raw, detail, state); } delay = (delay * 2).min(LONGEST_POLL_SECONDS); - } -} - -async fn read_review_once(api: &Api, review_id: Uuid, sarif: bool) -> anyhow::Result { - let (raw, detail) = api.review(review_id).await?; - outcome::same_review(&detail, review_id)?; - if sarif { - sarif::validate_subject(&detail, review_id)?; - } - let state = outcome::terminal(&detail); - Ok((raw, detail, state)) + }; + target.validate(&last.1, sarif, false)?; + Ok(Some(last)) } /// Said when no read of the review answered before the deadline. @@ -1314,7 +1350,7 @@ fn say_not_established(api: &Api, review_id: Uuid, timeout_minutes: u64) { /// Prints the review, after waiting for it to finish when `wait` is set. async fn show( api: &Api, - review_id: Uuid, + target: ReviewTarget<'_>, wait: bool, output: &OutputArgs, format: OutputFormat, @@ -1326,8 +1362,8 @@ async fn show( None }; let sarif = matches!(format, OutputFormat::Sarif); - let Some((raw, detail, state)) = read_review(api, review_id, deadline, sarif).await? else { - say_not_established(api, review_id, output.timeout); + let Some((raw, detail, state)) = read_review(api, target, deadline, sarif).await? else { + say_not_established(api, target.id, output.timeout); return Ok(Verdict::Unavailable); }; // `audit_mode` marks an audit, as on a listed review (`ReviewSummary`). @@ -1335,7 +1371,7 @@ async fn show( print_audit(api, raw, &detail, format)?; return Ok(Verdict::NotComplete); } - print_review(api, review_id, raw, &detail, state, format)?; + print_review(api, target.id, raw, &detail, state, format)?; match state { Some(Outcome::Completed) => { let verdict = review_verdict(&detail, fail_on); @@ -1355,7 +1391,7 @@ async fn show( "The review was still {} after {} minutes; it continues at {}", text::one_line(&detail.status), output.timeout, - api.review_url(review_id) + api.review_url(target.id) )), None => say("The review has not finished; pass --wait to wait for its result."), } @@ -1435,6 +1471,24 @@ async fn ci_job( /// it asks for one. const REQUEST_AFTER: Duration = Duration::from_secs(120); +fn head_matches(reported: Option<&str>, expected: &str) -> bool { + reported.is_some_and(|head| head.eq_ignore_ascii_case(expected)) +} + +/// A matching review ID alone cannot establish which commit its findings describe. +fn confirm_head(detail: &ReviewDetail, commit: &str) -> anyhow::Result<()> { + if !head_matches(detail.head_commit_sha.as_deref(), commit) { + bail!( + "proofline asked for the review of {commit}, but the server returned head commit {}", + detail + .head_commit_sha + .as_deref() + .map_or_else(|| "none".to_owned(), text::one_line) + ); + } + Ok(()) +} + /// Confirms `detail` is actually the pull-request review of `commit` in /// `repository_id` before it is allowed to decide a CI verdict or produce a /// SARIF artifact. [`read_review`] already confirms `detail` is the review @@ -1458,19 +1512,7 @@ fn confirm_ci_subject( text::one_line(&detail.kind) ); } - if !detail - .head_commit_sha - .as_deref() - .is_some_and(|head| head.eq_ignore_ascii_case(commit)) - { - bail!( - "proofline asked for the review of {commit}, but the server returned head commit {}", - detail - .head_commit_sha - .as_deref() - .map_or_else(|| "none".to_owned(), text::one_line) - ); - } + confirm_head(detail, commit)?; if let Some(detail_repository) = detail.repository_id && detail_repository != repository_id { @@ -1511,7 +1553,7 @@ async fn ci_review( }; let sarif_path = args.sarif.as_deref(); let Some((raw, detail, state)) = - read_review(api, review_id, Some(deadline), sarif_path.is_some()).await? + read_review(api, review_id.into(), Some(deadline), sarif_path.is_some()).await? else { say_not_established(api, review_id, args.timeout); return Ok(Verdict::Unavailable); diff --git a/src/scan.rs b/src/scan.rs index cfff60a..759444b 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -139,7 +139,7 @@ pub(crate) async fn run( } match show( api, - review_id, + review_id.into(), true, &args.output, OutputFormat::from_json(args.output.json), diff --git a/src/tools.rs b/src/tools.rs index a3602f7..455f22d 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -108,7 +108,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result (Origin, Arc>>) { - let page = || async { - Json(json!({ +async fn departed(summary_head: &str) -> (Origin, Arc>>) { + let page = Json(json!({ // A newer audit at the same head, which no head // selection takes: its findings are in its report. "items": [{ @@ -1217,7 +1217,7 @@ async fn departed() -> (Origin, Arc>>) { "audit_mode": "CODE_ONLY", "status": "COMPLETED", "created_at": "2026-10-02T00:00:00Z", - "head_commit_sha": DEPARTED_HEAD, + "head_commit_sha": summary_head.to_ascii_uppercase(), "pull_request_number": null, "repository_id": DEPARTED_REPOSITORY, "run_number": 1, @@ -1226,7 +1226,7 @@ async fn departed() -> (Origin, Arc>>) { "kind": "PULL_REQUEST", "status": "COMPLETED", "created_at": "2026-10-01T00:00:00Z", - "head_commit_sha": DEPARTED_HEAD, + "head_commit_sha": summary_head.to_ascii_uppercase(), "pull_request_number": 9, "repository_id": DEPARTED_REPOSITORY, "run_number": 1, @@ -1238,13 +1238,16 @@ async fn departed() -> (Origin, Arc>>) { "environments": [], "authors": [], }, - })) - }; + })); + let serve_page = move || std::future::ready(page.clone()); let app = Router::new() - .route(&format!("/api/v1/organizations/{ORG}/reviews"), get(page)) + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(serve_page.clone()), + ) .route( &format!("/api/v1/organizations/{ORG}/reviews/pr/{{repository}}/{{number}}"), - get(page), + get(serve_page), ) .route( &format!("/api/v1/organizations/{ORG}/repository-names"), @@ -1277,7 +1280,7 @@ async fn departed() -> (Origin, Arc>>) { #[tokio::test] async fn findings_of_a_departed_repository_still_resolve_through_its_reviews() { - let (origin, reads) = departed().await; + let (origin, reads) = departed(DEPARTED_HEAD).await; let origin = origin.to_string(); let run = |selector: [&'static str; 2], command: &'static str| { let origin = origin.clone(); @@ -2159,7 +2162,7 @@ async fn identity_console( }], "next_cursor": null, "truncated": false, - "filters": { "repositories": [], "environments": [], "authors": [] }, + "filters": { "repositories": [{ "id": CI_REPOSITORY, "name": "acme/app" }], "environments": [], "authors": [] }, })) }), ) @@ -2194,10 +2197,92 @@ async fn identity_console( origin } +#[tokio::test] +async fn findings_at_the_checkouts_head_refuses_a_detail_for_another_commit() { + let checkout = tempfile::tempdir().unwrap(); + for args in [ + &["init", "--quiet"][..], + &[ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.org", + "commit", + "--allow-empty", + "-qm", + "fixture", + ], + &["remote", "add", "origin", "https://github.com/acme/old.git"], + ] { + let status = tokio::process::Command::new("git") + .current_dir(checkout.path()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", checkout.path().join("empty.gitconfig")) + .args(args) + .status() + .await + .unwrap(); + assert!(status.success(), "git {args:?}"); + } + let head = tokio::process::Command::new("git") + .current_dir(checkout.path()) + .args(["rev-parse", "HEAD"]) + .output() + .await + .unwrap(); + assert!(head.status.success()); + let head = String::from_utf8(head.stdout).unwrap(); + let (origin, _) = departed(head.trim()).await; + let output = cli_with_git( + &origin.to_string(), + &["findings", "--json"], + checkout.path(), + ) + .await; + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let diagnostic = String::from_utf8_lossy(&output.stderr); + assert!( + diagnostic.contains(head.trim()) && diagnostic.contains(DEPARTED_HEAD), + "{diagnostic}" + ); +} + const OTHER_REVIEW_ID: &str = "0190f3a0-0000-7000-8000-0000000000e1"; const OTHER_HEAD_COMMIT: &str = "fedcba9876543210fedcba9876543210fedcba98"; const OTHER_REPOSITORY_ID: &str = "0190f3a0-0000-7000-8000-0000000000f9"; +#[tokio::test] +async fn findings_by_head_refuses_a_detail_for_another_commit() { + let origin = identity_console( + CI_REVIEW, + OTHER_HEAD_COMMIT, + "PULL_REQUEST", + CI_REPOSITORY, + "COMPLETED", + ) + .await; + let output = cli( + &origin, + &[ + "findings", "--repo", "acme/app", "--head", CI_HEAD, "--json", + ], + ) + .await; + assert_eq!( + output.status.code(), + Some(1), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + assert!(output.stdout.is_empty()); + let diagnostic = String::from_utf8_lossy(&output.stderr); + assert!( + diagnostic.contains(CI_HEAD) && diagnostic.contains(OTHER_HEAD_COMMIT), + "{diagnostic}" + ); +} + #[tokio::test] async fn ci_review_refuses_a_detail_that_mismatches_one_identity_field_at_a_time() { // Each case matches every identity field except the one named, so the diff --git a/tests/sarif.rs b/tests/sarif.rs index fd65418..092389e 100644 --- a/tests/sarif.rs +++ b/tests/sarif.rs @@ -973,12 +973,106 @@ async fn sarif_refuses_unpinned_or_unrecognized_records_before_writing_output() console.assert_reads(1, ORG); } +#[tokio::test] +async fn a_retained_review_can_be_exported_at_the_callers_head_without_a_checkout() { + let console = Console::new(review(Vec::new())); + let origin = serve(console.clone()).await; + let output = cli( + &origin, + ORG, + TOKEN, + &[ + "findings", + "--review", + REVIEW, + "--head", + &HEAD.to_ascii_uppercase(), + "--sarif", + ], + ) + .await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + report(&output, &schema()); + console.assert_reads(1, ORG); +} + +#[tokio::test] +async fn a_pinned_read_refuses_the_wrong_head_before_polling_again() { + let mut running = review(Vec::new()); + running["status"] = json!("RUNNING"); + let console = Console::new(running); + let origin = serve(console.clone()).await; + let output = cli( + &origin, + ORG, + TOKEN, + &[ + "findings", + "--review", + REVIEW, + "--head", + OTHER_COMMIT, + "--wait", + "--json", + ], + ) + .await; + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let diagnostic = String::from_utf8_lossy(&output.stderr); + assert!( + diagnostic.contains(HEAD) && diagnostic.contains(OTHER_COMMIT), + "{diagnostic}" + ); + console.assert_reads(1, ORG); +} + +#[tokio::test] +async fn a_missing_head_is_reported_before_any_pinned_findings_are_written() { + let mut detail = review(Vec::new()); + detail.as_object_mut().unwrap().remove("head_commit_sha"); + let console = Console::new(detail); + let origin = serve(console.clone()).await; + for format in [None, Some("--json"), Some("--sarif")] { + let mut args = vec!["findings", "--review", REVIEW, "--head", HEAD]; + args.extend(format); + let output = cli(&origin, ORG, TOKEN, &args).await; + assert_eq!(output.status.code(), Some(1)); + assert!(output.stdout.is_empty()); + let diagnostic = String::from_utf8_lossy(&output.stderr); + assert!( + diagnostic.contains(HEAD) && diagnostic.contains("head commit none"), + "{diagnostic}" + ); + } + let unpinned = cli( + &origin, + ORG, + TOKEN, + &["findings", "--review", REVIEW, "--json"], + ) + .await; + assert!( + unpinned.status.success(), + "{}", + String::from_utf8_lossy(&unpinned.stderr) + ); + console.assert_reads(4, ORG); +} + #[tokio::test] async fn sarif_usage_errors_are_rejected_before_reading_a_review() { let console = Console::new(review(Vec::new())); let origin = serve(console.clone()).await; for args in [ vec!["findings", "--sarif"], + vec!["findings", "--pr", "42", "--review", REVIEW], + vec!["findings", "--pr", "42", "--head", HEAD], + vec!["findings", "--review", REVIEW, "--head", "main"], vec!["findings", "--pr", "42", "--sarif"], vec!["findings", "--head", HEAD, "--sarif"], vec!["findings", "--review", REVIEW, "--json", "--sarif"],