diff --git a/README.md b/README.md index cbdda95..9b2b3c6 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ Native knowledge, fix and configuration commands send the selected organization `proofline review --path src/main.rs` reviews only that file's local changes against the normal merge-base. The path is literal and repository-relative; the command refuses directories, globs, and `..`. Combine it with `--staged` to read the index, or `--include-untracked` to select a new, non-ignored file. The command preserves the real index and applies the usual secret preflight. You cannot combine `--path` with pushed-commit, range, or pull-request review. -`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. These commands can find the reviews your token can still read after a repository disconnects. With a clone URL or Git remote, they resolve the project on its registered host and read its runs by repository ID. 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 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. These commands can find the reviews your token can still read after a repository disconnects. With a clone URL or Git remote, they resolve the project on its registered host and read its runs by repository ID. 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. `proofline findings --review REVIEW_ID --head FULL_SHA` reads that review directly, with no checkout, and exits 1 without printing it unless the review's head is that commit. A search by `--head`, or by the checkout's HEAD, makes the same check on the review it finds. Letter case in a SHA does not matter. None of these commands reads the organization's review list. `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. diff --git a/src/hooks.rs b/src/hooks.rs index 7d5550a..fe2f464 100644 --- a/src/hooks.rs +++ b/src/hooks.rs @@ -505,7 +505,7 @@ 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) + let (_, detail, state) = read_review(api, requested.review_id, Some(deadline), false, None) .await? .context("Proofline did not answer a read of the review before the deadline")?; anyhow::Ok((requested.review_id, detail, state)) diff --git a/src/lib.rs b/src/lib.rs index 19da9e1..5df9d03 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -456,14 +456,17 @@ struct ReviewArgs { output: OutputArgs, } +/// Which review to read. A pull request, a head commit and a review ID are +/// three ways to name one; only a review ID may be combined with a head, which +/// then states the commit that review must be of. #[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. + /// Latest review whose head is exactly this pushed commit, in either + /// letter case. Defaults to the checkout's HEAD. With --review, the + /// commit that review must be of; nothing is printed for another head. #[arg(long, value_name = "SHA")] head: Option, /// This review. @@ -479,7 +482,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_all = ["json", "pr"])] sarif: bool, #[command(flatten)] repository: RepositoryArgs, @@ -1576,13 +1579,27 @@ async fn finish( &args.output, OutputFormat::from_json(args.output.json), args.fail_on, + None, ) .await } async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { + // The commit the review read must be of, when the caller named or implied + // one. A search by head is only a summary row; the detail read below must + // agree with it before anything is printed. A review ID or a pull request + // alone names no commit. + let mut head = None; let review_id = match (&args.selector.review, args.selector.pr) { - (Some(id), _) => *id, + (Some(id), _) => { + head = args + .selector + .head + .as_deref() + .map(git::commit_sha) + .transpose()?; + *id + } (None, Some(number)) => pull_request_review(api, &args.repository, number).await?, (None, None) => { let sha = match &args.selector.head { @@ -1593,11 +1610,17 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { resolve_repository(api, &args.repository, RepositoryRead::History).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 found = latest(api, repository_id, &sha, |item| { + item.audit_mode.is_none() + && item + .head_commit_sha + .as_deref() + .is_some_and(|head| head.eq_ignore_ascii_case(&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"))?; + head = Some(sha); + found } }; let format = if args.sarif { @@ -1605,7 +1628,16 @@ 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, + review_id, + args.wait, + &args.output, + format, + None, + head.as_deref(), + ) + .await } #[derive(Debug, thiserror::Error)] @@ -1633,20 +1665,26 @@ type ReviewRead = (serde_json::Value, ReviewDetail, Option); /// last answer before the deadline decides. `None` means no read answered /// before the deadline. Every read confirms the server's answer is of the /// review requested, not a cache or routing mix-up that would otherwise let -/// a result for a different review decide this one's outcome. +/// a result for a different review decide this one's outcome. With `head`, +/// it also confirms the review is of that commit. async fn read_review( api: &Api, review_id: Uuid, deadline: Option, sarif: bool, + head: Option<&str>, ) -> 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), + _ => { + return read_review_once(api, review_id, sarif, head) + .await + .map(Some); + } }; poll_until( deadline, - || read_review_once(api, review_id, sarif), + || read_review_once(api, review_id, sarif, head), |read: &ReviewRead| read.2.is_some(), |read: &ReviewRead, delay| { say(&format!( @@ -1694,9 +1732,19 @@ where } } -async fn read_review_once(api: &Api, review_id: Uuid, sarif: bool) -> anyhow::Result { +async fn read_review_once( + api: &Api, + review_id: Uuid, + sarif: bool, + head: Option<&str>, +) -> anyhow::Result { let (raw, detail) = api.review(review_id).await?; outcome::same_review(&detail, review_id)?; + // Before the SARIF check and before anything is printed: a review of + // another head never reaches the output. + if let Some(head) = head { + outcome::same_head(&detail, head)?; + } if sarif { sarif::validate_subject(&detail, review_id)?; } @@ -1713,6 +1761,8 @@ 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. +/// With `head`, a review of any other head, or of none, is refused before +/// anything is printed. async fn show( api: &Api, review_id: Uuid, @@ -1720,6 +1770,7 @@ async fn show( output: &OutputArgs, format: OutputFormat, fail_on: Option, + head: Option<&str>, ) -> anyhow::Result { let deadline = if wait { Some(poll_deadline(output.timeout)?) @@ -1727,7 +1778,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 { + let Some((raw, detail, state)) = read_review(api, review_id, deadline, sarif, head).await? + else { say_not_established(api, review_id, output.timeout); return Ok(Verdict::Unavailable); }; @@ -1863,19 +1915,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) - ); - } + outcome::same_head(detail, commit)?; if let Some(detail_repository) = detail.repository_id && detail_repository != repository_id { @@ -1916,7 +1956,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, Some(deadline), sarif_path.is_some(), None).await? else { say_not_established(api, review_id, args.timeout); return Ok(Verdict::Unavailable); @@ -2641,7 +2681,14 @@ mod tests { // Reads start at 0, 5 and 15 seconds; the client's own request // timeout is 30 seconds, so the deadline is what ends the third. let deadline = tokio::time::Instant::now() + Duration::from_secs(40); - let read = read_review(&api, REQUESTED.parse().unwrap(), Some(deadline), false).await; + let read = read_review( + &api, + REQUESTED.parse().unwrap(), + Some(deadline), + false, + None, + ) + .await; ticker.abort(); let (raw, detail, state) = read.unwrap().expect("an answered read stands"); assert_eq!(*reads.lock().unwrap(), 3); diff --git a/src/outcome.rs b/src/outcome.rs index 0a80059..4933a49 100644 --- a/src/outcome.rs +++ b/src/outcome.rs @@ -33,6 +33,31 @@ pub(crate) fn same_review(detail: &ReviewDetail, requested: Uuid) -> Result<(), } } +/// A review was asked for by head commit, or read with `--head`, but the +/// server's own account of it names a different head or none. `returned` is +/// already safe to print on one line. +#[derive(Debug, thiserror::Error)] +#[error( + "proofline asked for the review of {requested}, but the server returned head commit {returned}" +)] +pub(crate) struct WrongHead { + pub(crate) requested: String, + pub(crate) returned: String, +} + +/// Confirms `detail` is of the `requested` head commit. A hexadecimal SHA +/// names the same commit in either letter case, so case is not compared. A +/// review that records no head is not of any requested head. +pub(crate) fn same_head(detail: &ReviewDetail, requested: &str) -> Result<(), WrongHead> { + match detail.head_commit_sha.as_deref() { + Some(head) if head.eq_ignore_ascii_case(requested) => Ok(()), + returned => Err(WrongHead { + requested: requested.to_owned(), + returned: returned.map_or_else(|| "none".to_owned(), crate::text::one_line), + }), + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Outcome { Completed, @@ -343,6 +368,32 @@ mod tests { } } + #[test] + fn same_head_ignores_letter_case_and_refuses_another_or_no_head() { + let sha = "0123456789abcdef0123456789abcdef01234567"; + let mut detail = review("COMPLETED", Vec::new(), 0); + detail.head_commit_sha = Some(sha.to_ascii_uppercase()); + assert!(same_head(&detail, sha).is_ok()); + detail.head_commit_sha = Some(sha.to_owned()); + assert!(same_head(&detail, &sha.to_ascii_uppercase()).is_ok()); + + let other = "89abcdef0123456789abcdef0123456789abcdef"; + detail.head_commit_sha = Some(format!("{other}\u{1b}[2J")); + let refused = same_head(&detail, sha).unwrap_err(); + assert_eq!(refused.requested, sha); + assert_eq!(refused.returned, format!("{other}\u{FFFD}[2J")); + + detail.head_commit_sha = None; + let refused = same_head(&detail, sha).unwrap_err(); + assert_eq!(refused.returned, "none"); + assert_eq!( + refused.to_string(), + format!( + "proofline asked for the review of {sha}, but the server returned head commit none" + ) + ); + } + fn finding(severity: &str, lifecycle_state: &str) -> Finding { Finding { id: Uuid::nil(), diff --git a/src/scan.rs b/src/scan.rs index 3a8e37a..445823d 100644 --- a/src/scan.rs +++ b/src/scan.rs @@ -157,6 +157,7 @@ pub(crate) async fn run( &args.output, OutputFormat::from_json(args.output.json), None, + None, ) .await { diff --git a/src/tools.rs b/src/tools.rs index c9cfdc7..2f1b13a 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -115,6 +115,7 @@ pub(crate) async fn rerun(api: &Api, args: &RerunArgs) -> anyhow::Result>>, +} + +impl Console { + fn reads(&self) -> Vec { + self.reads.lock().unwrap().clone() + } + + fn detail_path() -> String { + format!("/api/v1/organizations/{ORG}/reviews/{REVIEW}") + } +} + +/// A completed pull-request review with one open finding. `head` is what the +/// server reports for it; `None` leaves the field out, as a patch review does. +fn detail(head: Option<&str>) -> Value { + let mut document = json!({ + "id": REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "repository_full_name": "acme/app", + "pull_request_number": 42, + "run_number": 7, + "assessment_count": 1, + "assessments": [{ + "id": ASSESSMENT, + "environment_display_name": "production", + "status": "COMPLETED", + "findings": [{ + "id": FINDING, + "severity": "WARNING", + "risk_domain": "data_integrity", + "claim": CLAIM, + "impact": "The customer can be charged twice.", + "lifecycle_state": "ACTIVE", + "remediation": "Make the receipt idempotent.", + "evidence_refs": [], + }], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + }); + if let Some(head) = head { + document["head_commit_sha"] = json!(head); + } + document +} + +async fn list(State(console): State, headers: HeaderMap, uri: Uri) -> Json { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + console.reads.lock().unwrap().push(uri.to_string()); + Json(json!({ + "items": [{ + "id": REVIEW, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "created_at": "2026-10-01T00:00:00Z", + "head_commit_sha": console.summary_head, + "pull_request_number": 42, + "repository_id": REPOSITORY, + "run_number": 7, + }], + "next_cursor": null, + "truncated": false, + "filters": { + "repositories": [{ "id": REPOSITORY, "name": "acme/app" }], + "environments": [], + "authors": [], + }, + })) +} + +async fn read(State(console): State, headers: HeaderMap, uri: Uri) -> Json { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + console.reads.lock().unwrap().push(uri.to_string()); + Json(console.detail) +} + +async fn serve(summary_head: &str, detail: Value) -> (String, Console) { + let console = Console { + summary_head: summary_head.to_owned(), + detail, + reads: Arc::default(), + }; + let app = Router::new() + .route(&format!("/api/v1/organizations/{ORG}/reviews"), get(list)) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}"), + get(read), + ) + .with_state(console.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + (origin, console) +} + +/// Runs the real binary. With `path`, the command finds Git there; without +/// it, `PATH` is empty, so a command that needs Git or a checkout fails. +async fn findings(origin: &str, directory: &Path, path: Option<&str>, args: &[&str]) -> Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .args(["--base-url", origin, "--org", ORG, "findings"]) + .args(args) + .env("PROOFLINE_TOKEN", TOKEN) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env( + "DBUS_SESSION_BUS_ADDRESS", + "unix:path=/proofline-test-unavailable-bus", + ) + .env("PATH", path.unwrap_or("")) + .current_dir(directory) + .kill_on_drop(true); + tokio::time::timeout(Duration::from_secs(15), command.output()) + .await + .unwrap() + .unwrap() +} + +/// A read with no Git and no checkout: the review ID and head are all it has. +async fn outside_a_checkout(origin: &str, args: &[&str]) -> Output { + findings(origin, &std::env::temp_dir(), None, args).await +} + +fn stdout(output: &Output) -> String { + String::from_utf8_lossy(&output.stdout).into_owned() +} + +fn stderr(output: &Output) -> String { + String::from_utf8_lossy(&output.stderr).into_owned() +} + +/// The command printed a review, with the finding in it. +fn assert_printed(output: &Output) { + assert_eq!(output.status.code(), Some(0), "{}", stderr(output)); + assert!(stdout(output).contains(CLAIM), "{}", stdout(output)); +} + +/// The command refused the review: exit 1, nothing on stdout, and an error +/// that names the head asked for and the head Proofline returned. +fn assert_refused(output: &Output, requested: &str, returned: &str) { + let (out, err) = (stdout(output), stderr(output)); + assert_eq!(output.status.code(), Some(1), "{err}"); + assert!(out.is_empty(), "{out}"); + assert!(!err.contains(CLAIM), "{err}"); + let expected = format!( + "proofline: proofline asked for the review of {requested}, but the server returned head commit {returned}" + ); + assert!(err.contains(&expected), "{err}"); +} + +#[tokio::test] +async fn head_with_a_review_id_reads_the_review_outside_a_checkout() { + let (origin, console) = serve(COMMIT_A, detail(Some(COMMIT_A))).await; + for format in [None, Some("--json"), Some("--sarif")] { + let mut args = vec!["--review", REVIEW, "--head", COMMIT_A]; + args.extend(format); + let output = outside_a_checkout(&origin, &args).await; + assert_printed(&output); + match format { + Some("--json") => { + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["review"]["id"], REVIEW); + assert_eq!(document["outcome"], "COMPLETED"); + } + Some(_) => { + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["version"], "2.1.0"); + } + None => assert!(stdout(&output).contains("COMPLETED"), "{}", stdout(&output)), + } + } + // The review is read directly: no review list, no repository lookup. + assert_eq!(console.reads(), vec![Console::detail_path(); 3]); +} + +#[tokio::test] +async fn review_id_alone_still_reads_any_review_including_one_without_a_head() { + for head in [Some(COMMIT_B), None] { + let (origin, console) = serve(COMMIT_A, detail(head)).await; + for format in [None, Some("--json")] { + let mut args = vec!["--review", REVIEW]; + args.extend(format); + assert_printed(&outside_a_checkout(&origin, &args).await); + } + assert_eq!(console.reads(), vec![Console::detail_path(); 2]); + } +} + +#[tokio::test] +async fn a_review_id_with_another_or_no_head_is_refused_in_every_format() { + let other = COMMIT_B.to_ascii_uppercase(); + for (head, returned) in [ + (Some(COMMIT_B), COMMIT_B), + // The server's spelling is quoted back, not the normalized one. + (Some(other.as_str()), other.as_str()), + (None, "none"), + (Some("main"), "main"), + (Some(""), ""), + ] { + let (origin, console) = serve(COMMIT_A, detail(head)).await; + for format in [None, Some("--json"), Some("--sarif")] { + let mut args = vec!["--review", REVIEW, "--head", COMMIT_A]; + args.extend(format); + let output = outside_a_checkout(&origin, &args).await; + assert_refused(&output, COMMIT_A, returned); + } + assert_eq!(console.reads(), vec![Console::detail_path(); 3]); + } +} + +#[tokio::test] +async fn a_head_search_refuses_a_detail_at_another_commit_in_every_format() { + // The summary row names commit A and the detail for the same review ID + // names commit B: the reproduction from #123. + let (origin, console) = serve(COMMIT_A, detail(Some(COMMIT_B))).await; + let dir = std::env::temp_dir(); + for format in [None, Some("--json")] { + let mut args = vec!["--repo", "acme/app", "--head", COMMIT_A]; + args.extend(format); + let output = findings(&origin, &dir, None, &args).await; + assert_refused(&output, COMMIT_A, COMMIT_B); + } + // The search found the review, so the detail was read: refusing is the + // check's doing, not a failed search. + let reads = console.reads(); + assert!(reads.iter().any(|read| read.contains("/reviews/0190"))); + assert!(reads.iter().any(|read| read.contains("search=0123"))); + + // A detail with no head at all is refused the same way. + let (origin, _) = serve(COMMIT_A, detail(None)).await; + let output = findings( + &origin, + &dir, + None, + &["--repo", "acme/app", "--head", COMMIT_A], + ) + .await; + assert_refused(&output, COMMIT_A, "none"); +} + +#[tokio::test] +async fn equivalent_hexadecimal_heads_match_in_either_letter_case() { + let upper = COMMIT_A.to_ascii_uppercase(); + let dir = std::env::temp_dir(); + for (summary, read, requested) in [ + (COMMIT_A, COMMIT_A, upper.as_str()), + (COMMIT_A, upper.as_str(), COMMIT_A), + (upper.as_str(), COMMIT_A, COMMIT_A), + (upper.as_str(), upper.as_str(), upper.as_str()), + ] { + let (origin, _) = serve(summary, detail(Some(read))).await; + let by_search = findings( + &origin, + &dir, + None, + &["--repo", "acme/app", "--head", requested], + ) + .await; + assert_printed(&by_search); + let by_id = outside_a_checkout(&origin, &["--review", REVIEW, "--head", requested]).await; + assert_printed(&by_id); + } +} + +/// A repository whose HEAD is a real commit, for the default selection. +struct Checkout { + directory: tempfile::TempDir, + head: String, +} + +impl Checkout { + fn new() -> Self { + let directory = tempfile::tempdir().unwrap(); + std::fs::write(directory.path().join("gitconfig"), "").unwrap(); + let checkout = Self { + directory, + head: String::new(), + }; + std::fs::create_dir_all(checkout.root()).unwrap(); + checkout.git(&["init", "-q", "-b", "main"]); + checkout.git(&[ + "-c", + "user.name=Findings Head Test", + "-c", + "user.email=findings-head@example.test", + "commit", + "--allow-empty", + "-qm", + "base", + ]); + let head = checkout.git(&["rev-parse", "HEAD"]).trim().to_owned(); + Self { head, ..checkout } + } + + fn root(&self) -> std::path::PathBuf { + self.directory.path().join("repo") + } + + fn git(&self, args: &[&str]) -> String { + let output = std::process::Command::new("git") + .args(args) + .current_dir(self.root()) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", self.directory.path().join("gitconfig")) + .output() + .unwrap(); + assert!(output.status.success(), "git {args:?}: {}", stderr(&output)); + String::from_utf8(output.stdout).unwrap() + } +} + +#[tokio::test] +async fn the_checkouts_head_is_the_default_and_is_checked_the_same_way() { + let checkout = Checkout::new(); + let path = std::env::var("PATH").unwrap(); + let run = |origin: String| { + let (root, path) = (checkout.root(), path.clone()); + async move { findings(&origin, &root, Some(&path), &["--repo", "acme/app"]).await } + }; + + let (origin, console) = serve(&checkout.head, detail(Some(&checkout.head))).await; + assert_printed(&run(origin).await); + assert!( + console + .reads() + .iter() + .any(|read| read.contains(&format!("search={}", checkout.head))) + ); + + // The summary names the checkout's commit; the detail names another. + let (origin, _) = serve(&checkout.head, detail(Some(COMMIT_B))).await; + assert_refused(&run(origin).await, &checkout.head, COMMIT_B); + let (origin, _) = serve(&checkout.head, detail(None)).await; + assert_refused(&run(origin).await, &checkout.head, "none"); + + // The review ID with no --head names no commit, so the checkout's HEAD is + // not consulted. + let (origin, _) = serve(&checkout.head, detail(Some(COMMIT_B))).await; + let output = findings( + &origin, + &checkout.root(), + Some(&path), + &["--review", REVIEW], + ) + .await; + assert_printed(&output); +} + +#[tokio::test] +async fn a_pull_request_and_a_head_stay_separate_choices() { + let (origin, console) = serve(COMMIT_A, detail(Some(COMMIT_A))).await; + for args in [ + vec!["--pr", "42", "--head", COMMIT_A], + vec!["--pr", "42", "--review", REVIEW], + vec!["--pr", "42", "--review", REVIEW, "--head", COMMIT_A], + ] { + let output = outside_a_checkout(&origin, &args).await; + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(stdout(&output).is_empty()); + assert!( + stderr(&output).contains("cannot be used with"), + "{}", + stderr(&output) + ); + } + // A head that is not a full SHA is refused before any read. + for head in ["main", SHORT_COMMIT] { + let output = outside_a_checkout(&origin, &["--review", REVIEW, "--head", head]).await; + assert_eq!(output.status.code(), Some(1), "{head}"); + assert!(stdout(&output).is_empty()); + } + assert!(console.reads().is_empty()); +} + +#[tokio::test] +async fn wait_applies_the_same_head_check() { + let wait = ["--review", REVIEW, "--head", COMMIT_A, "--wait"]; + let (origin, _) = serve(COMMIT_A, detail(Some(COMMIT_A))).await; + assert_printed(&outside_a_checkout(&origin, &wait).await); + for head in [Some(COMMIT_B), None] { + let (origin, _) = serve(COMMIT_A, detail(head)).await; + let output = outside_a_checkout(&origin, &wait).await; + assert_refused(&output, COMMIT_A, head.unwrap_or("none")); + } +} + +#[tokio::test] +async fn an_audit_review_and_an_upper_case_request_are_checked_too() { + let mut audit = detail(Some(COMMIT_B)); + audit["audit_mode"] = json!("CODE_ONLY"); + let (origin, _) = serve(COMMIT_A, audit).await; + // The requested head is quoted in the normalized lower case. + let upper = COMMIT_A.to_ascii_uppercase(); + let output = outside_a_checkout(&origin, &["--review", REVIEW, "--head", &upper]).await; + assert_refused(&output, COMMIT_A, COMMIT_B); +} diff --git a/tests/http.rs b/tests/http.rs index 8508a79..ae29218 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1393,7 +1393,10 @@ async fn the_first_review_of_an_unreviewed_repository_is_requested_by_name() { } const DEPARTED_REPOSITORY: &str = "0190f3a0-0000-7000-8000-0000000000ee"; -const DEPARTED_HEAD: &str = "0123456789abcdef0123456789abcdef01234567"; +/// The head of both the summary rows and the detail the `review` handler +/// serves, so the fixture does not hand `findings --head` a summary at one +/// commit and a detail at another (#123). +const DEPARTED_HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; /// A console where `acme/old` has left the installation but keeps an /// authorized review: `/repository-names` omits it, the review collection