diff --git a/README.md b/README.md index eea0165..b985366 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,14 @@ Native knowledge, plan, fix and configuration commands send the selected organiz 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. +In a manually triggered or downstream job, pass the original PR number and its full head commit SHA to read that PR's review: + +```sh +proofline ci review --repo owner/name --pr 42 --commit "$PR_HEAD_SHA" --fail-on serious +``` + +Outside a GitHub pull-request event, `--pr` requires an explicit `--commit`. On a pull-request event, the PR number comes from the event, and any explicit `--pr` must match it. + For a CodePipeline execution or Amplify job, run `proofline ci deploy --commit SHA --aws-run ID` in a later pipeline. Add `--environment-id UUID` to select its Proofline environment. The output names the AWS provider and run ID. Proofline records a CodePipeline deploy only after the execution succeeds, so a reader inside that execution waits until its timeout and exits 2. On a GitHub `workflow_run` event, an explicit `--aws-run` disables the default Actions run and attempt filters. `proofline ci deploy --until 1h` waits until Proofline has recorded the deploy checks of the job's commit through the hour check, then exits 0 when each recorded `HEALTHY` with no gap, 3 when a deploy failed or regressed, and 2 when the result is not established, including when a deploy reads a state this CLI version does not know. After a read that answered, the wait keeps reading through a read that fails in transport, times out or gets a 5xx answer, and exits 4 after five such failures in a row, naming the last error; the first read and a refusal end it at once. Without `--timeout`, a wait for `--until landing`, `--until 20m` or `--until 1h` lasts until that check is due for the selected deploys, and at least 30 minutes, so a landing check that reads the runtime again, up to 75 minutes after landing, is still read; `--until 1d` needs `--timeout`. `--environment-id` (the Proofline environment's UUID, the `environment_id` that `--json` prints for each deploy), `--environment` (the GitHub Environment name), `--task`, `--deployment` (the ID of the GitHub deployment a pipeline created), `--run` and `--attempt` select the deploy, and on a `workflow_run` event the commit, `--run` and `--attempt` default to the completed run's. When `--run` defaults to a completed run that did not succeed, the command waits at most 5 minutes for a deploy from that run, then exits 2 with a last line that names the run's conclusion and says it recorded no deploy; a deploy the run did record gets the usual wait for its check. `--json` prints the response. Each deploy prints one line per check. A deploy that rolled the environment back to an earlier commit first prints a `rollback` line with the page of the deploy it restores, when Proofline recorded one, and the pages of the deploys it rolled back. A deploy whose newest check found its service serving an earlier deploy again first prints a `rolled back` line, and stops printing it once a later check finds none; with `--json` the response carries it as `rolled_back`. Both lines can appear for one deploy. A rollback's exit code comes from its checks like any other deploy's; neither line changes it or means the rollback fixed anything. A deploy whose deploy checks ended without recording the `--until` check ends the wait at once with exit 2, and the last line names the check and the deploy's page; a check that is overdue while the checks still run keeps the wait going until the timeout. diff --git a/src/api.rs b/src/api.rs index 4f84754..3c9d94c 100644 --- a/src/api.rs +++ b/src/api.rs @@ -609,7 +609,31 @@ impl Api { search: Option<&str>, cursor: Option<&str>, ) -> Result { - let mut url = self.url_list_reviews(); + self.review_page(self.url_list_reviews(), repository_id, search, cursor) + .await + } + + /// Applies the repository UUID filter to the name-based PR history route. + /// The caller matches the head locally while walking that history. + pub(crate) async fn pull_request_review_page( + &self, + repository: &str, + repository_id: Uuid, + number: i64, + cursor: Option<&str>, + ) -> Result { + let url = self.url_list_pull_request_reviews(repository, &number.to_string()); + self.review_page(url, Some(repository_id), None, cursor) + .await + } + + async fn review_page( + &self, + mut url: Url, + repository_id: Option, + search: Option<&str>, + cursor: Option<&str>, + ) -> Result { { let mut query = url.query_pairs_mut(); query.append_pair("limit", "50"); diff --git a/src/github_actions.rs b/src/github_actions.rs index 8022934..4d60230 100644 --- a/src/github_actions.rs +++ b/src/github_actions.rs @@ -93,6 +93,63 @@ struct Head { sha: String, } +pub(crate) struct PullRequestIdentity { + pub number: i64, + pub repository: Option, + pub head: Option, +} + +pub(crate) fn pull_request_identity(event: &str) -> anyhow::Result> { + #[derive(Deserialize)] + struct Repository { + full_name: String, + } + #[derive(Deserialize)] + struct Payload { + repository: Option, + pull_request: Request, + number: Option, + } + #[derive(Deserialize)] + struct Request { + number: Option, + #[serde(default)] + head: serde_json::Value, + } + if !event.starts_with("pull_request") { + return Ok(None); + } + let unreadable = + || format!("the {event} event payload must name the pull request; check GITHUB_EVENT_PATH"); + let path = std::env::var_os(EVENT_PATH).with_context(unreadable)?; + let bytes = std::fs::read(path).with_context(unreadable)?; + let payload: Payload = serde_json::from_slice(&bytes).with_context(unreadable)?; + let number = payload + .pull_request + .number + .or(payload.number) + .with_context(unreadable)?; + if number <= 0 + || payload.number.is_some_and(|outer| outer != number) + || payload + .repository + .as_ref() + .is_some_and(|repo| repo.full_name.trim().is_empty()) + { + bail!("{}", unreadable()); + } + Ok(Some(PullRequestIdentity { + number, + repository: payload.repository.map(|repo| repo.full_name), + head: payload + .pull_request + .head + .get("sha") + .and_then(serde_json::Value::as_str) + .map(str::to_owned), + })) +} + /// The commit a GitHub Actions job tests, or `None` outside one. On a /// `pull_request*` event `GITHUB_SHA` is GitHub's merge commit or the base /// branch's head, never a commit Proofline reviewed, so the pull request's head diff --git a/src/lib.rs b/src/lib.rs index 8c6f1d6..4ac6ea5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -220,6 +220,10 @@ enum CiCommand { #[derive(Debug, Args)] struct CiReviewArgs { + /// Pull request number. Outside a GitHub pull-request event, also pass + /// --commit with the pull request's full head SHA. + #[arg(long, value_name = "NUMBER", value_parser = clap::value_parser!(i64).range(1..))] + pr: Option, /// Full commit SHA under test. Defaults to `COMMIT_SHA`, then the pull /// request's head on a GitHub Actions pull-request event, then `GITHUB_SHA`. #[arg(long, value_name = "SHA")] @@ -614,11 +618,50 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - let commit = ci_commit(args.commit.as_deref())?; - let http = Http::new(origin)?; let event = std::env::var(github_actions::EVENT_NAME).unwrap_or_default(); + let pr = github_actions::pull_request_identity(&event)?; + match (&pr, args.pr) { + (Some(event_pr), Some(number)) if event_pr.number != number => { + bail!( + "--pr {number} disagrees with GitHub event pull request #{}; omit --pr or pass --pr {}", + event_pr.number, + event_pr.number, + ); + } + (None, Some(_)) if args.commit.is_none() => { + bail!( + "--pr requires --commit SHA outside a GitHub pull-request event; pass the pull request's full head commit SHA" + ); + } + _ => {} + } + let name = repository_name(&args.repository).await?; + if let Some(event_repository) = pr.as_ref().and_then(|pr| pr.repository.as_deref()) + && !event_repository.eq_ignore_ascii_case(&name) + { + let event_repository = text::one_line(event_repository); + let name = text::one_line(&name); + bail!( + "the GitHub event names repository {event_repository}, but the selected repository is {name}; pass --repo {event_repository} or select its git remote with --remote", + ); + } + let number = pr.as_ref().map(|pr| pr.number).or(args.pr); + let commit = ci_commit_with(args.commit.as_deref(), || { + let Some(pr) = pr else { + return github_actions::commit_under_test(); + }; + pr.head.map(Some).with_context(|| { + format!("the {event} event payload names no pull-request head; name it with --commit") + }) + })?; + let subject = CiReviewSubject { + name: &name, + commit: &commit, + pr: number, + }; + let http = Http::new(origin)?; let issuer = github_actions::Issuer::from_environment(); - let result = ci_job(http, token, issuer, &event, cli.org, &args, &commit).await; + let result = ci_job(http, token, issuer, &event, cli.org, &args, subject).await; ci_ending(result) } Command::Ci(CiCommand::Deploy(mut args)) => { @@ -895,7 +938,8 @@ fn unique( async fn connected_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Result<(String, Uuid)> { let name = repository_name(args).await?; let names = api.repository_names().await?; - connected(api, name, names) + let (_, id) = connected(api, &name, names)?; + Ok((name, id)) } /// A connected repository, for requesting a scan, resolved through the route @@ -903,21 +947,22 @@ async fn connected_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Resul async fn scannable_repository(api: &Api, args: &RepositoryArgs) -> anyhow::Result<(String, Uuid)> { let name = repository_name(args).await?; let names = api.scan_repository_names().await?; - connected(api, name, names) + let (_, id) = connected(api, &name, names)?; + Ok((name, id)) } -fn connected(api: &Api, name: String, names: RepositoryNames) -> anyhow::Result<(String, Uuid)> { +fn connected(api: &Api, name: &str, names: RepositoryNames) -> anyhow::Result<(String, Uuid)> { let candidates = names .repositories .into_iter() .map(|repository| (repository.id, repository.full_name)); - let (id, _) = unique(api, &name, candidates, || { + let (id, canonical_name) = unique(api, name, candidates, || { anyhow::anyhow!( "{name} is not a repository in organization {} that this token can read; check the repository name and the token's repositories", api.organization_id() ) })?; - Ok((name, id)) + Ok((canonical_name, id)) } /// A repository with reviews the token can read, for finding one of them, as @@ -1002,18 +1047,32 @@ fn route_name(full_name: &str) -> &str { .map_or(full_name, |(_, name)| name) } -/// The newest review in `repository` that `matches`, searching with `search`. +/// Search a known PR's history because an organization-wide full-SHA +/// search returns only the latest run at that commit, possibly another PR's. async fn latest( api: &Api, repository: Uuid, search: &str, + pr: Option<(&str, i64)>, matches: impl Fn(&ReviewSummary) -> bool, ) -> anyhow::Result> { let mut cursor: Option = None; for _ in 0..SEARCH_PAGES { - let page = api - .reviews(Some(repository), Some(search), cursor.as_deref()) - .await?; + let page = match pr { + Some((name, number)) => { + api.pull_request_review_page( + route_name(name), + repository, + number, + cursor.as_deref(), + ) + .await? + } + None => { + api.reviews(Some(repository), Some(search), cursor.as_deref()) + .await? + } + }; if let Some(found) = page.items.iter().find(|item| matches(item)) { return Ok(Some(found.id)); } @@ -1218,7 +1277,7 @@ async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { 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| { + latest(api, repository_id, &sha, None, |item| { item.audit_mode.is_none() && item.head_commit_sha.as_deref() == Some(sha.as_str()) }) .await? @@ -1251,34 +1310,49 @@ fn poll_deadline(minutes: u64) -> Result); -/// 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 -/// pending then is dropped, whatever the HTTP client's own timeout, so the -/// 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. +/// Keep the single read used by existing review and hook callers when +/// they have no time left to wait. async fn read_review( api: &Api, review_id: Uuid, 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); + read_review_checked(api, review_id, deadline, sarif, |_| Ok(())).await +} + +/// Reads once without a deadline. With a deadline, no read starts at or +/// after it, and a read still pending then is dropped. Each reply must match +/// the requested review ID and pass the caller's subject check. +async fn read_review_checked( + api: &Api, + review_id: Uuid, + deadline: Option, + sarif: bool, + check_subject: impl Fn(&ReviewDetail) -> anyhow::Result<()>, +) -> anyhow::Result> { + let Some(deadline) = deadline else { + return read_review_once(api, review_id, sarif, &check_subject) + .await + .map(Some); }; let mut delay = FIRST_POLL_SECONDS; - loop { - let Ok(read) = - tokio::time::timeout_at(deadline, read_review_once(api, review_id, sarif)).await + while tokio::time::Instant::now() < deadline { + let Ok(read) = tokio::time::timeout_at( + deadline, + read_review_once(api, review_id, sarif, &check_subject), + ) + .await else { return Ok(None); }; - let read = read?; let now = tokio::time::Instant::now(); - if read.2.is_some() || now >= deadline { + if now >= deadline { + return Ok(None); + } + let read = read?; + if read.2.is_some() { return Ok(Some(read)); } say(&format!( @@ -1291,11 +1365,18 @@ async fn read_review( } delay = (delay * 2).min(LONGEST_POLL_SECONDS); } + Ok(None) } -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, + check_subject: &impl Fn(&ReviewDetail) -> anyhow::Result<()>, +) -> anyhow::Result { let (raw, detail) = api.review(review_id).await?; outcome::same_review(&detail, review_id)?; + check_subject(&detail)?; if sarif { sarif::validate_subject(&detail, review_id)?; } @@ -1375,13 +1456,20 @@ fn say_not_complete(ended: Outcome) { /// on a pull-request event, `GITHUB_SHA` otherwise. Only a full SHA is /// accepted, never a ref. fn ci_commit(flag: Option<&str>) -> anyhow::Result { + ci_commit_with(flag, github_actions::commit_under_test) +} + +fn ci_commit_with( + flag: Option<&str>, + runner_commit: impl FnOnce() -> anyhow::Result>, +) -> anyhow::Result { let cloud_build = std::env::var("COMMIT_SHA") .ok() .filter(|value| !value.trim().is_empty()); let raw = match (flag, cloud_build) { (Some(raw), _) => raw.to_owned(), (None, Some(raw)) => raw, - (None, None) => github_actions::commit_under_test()? + (None, None) => runner_commit()? .context("name the commit under test with --commit, COMMIT_SHA or GITHUB_SHA")?, }; Ok(git::commit_sha(&raw)?) @@ -1407,9 +1495,15 @@ fn unavailable(error: &anyhow::Error) -> bool { .is_some_and(ApiError::transient) } -/// `ci review` once its inputs are read. In GitHub Actions without -/// `PROOFLINE_TOKEN`, the job's signed identity is the credential, and only -/// then, on a `pull_request` event, may the job ask for a review itself. +#[derive(Clone, Copy)] +struct CiReviewSubject<'a> { + name: &'a str, + commit: &'a str, + pr: Option, +} + +/// In GitHub Actions without `PROOFLINE_TOKEN`, the job's signed identity +/// is the credential. A `pull_request` job on that identity may request a review. async fn ci_job( http: Http, token: Option, @@ -1417,8 +1511,9 @@ async fn ci_job( event: &str, org: Option, args: &CiReviewArgs, - commit: &str, + subject: CiReviewSubject<'_>, ) -> anyhow::Result { + let commit = subject.commit; let (api, request) = match (token, issuer) { (None, Some(issuer)) => { let head = github_actions::pull_request_head(event, commit); @@ -1428,29 +1523,24 @@ async fn ci_job( } (token, _) => (connect(http, token, org).await?, None), }; - ci_review(&api, args, commit, request.as_ref()).await + ci_review(&api, args, subject, request.as_ref()).await } /// How long a pull-request job waits for the App's review of its head before /// it asks for one. const REQUEST_AFTER: Duration = Duration::from_secs(120); -/// 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 -/// requested by id; a search match on `commit` against a summary row does -/// not guarantee the detail fetched moments later, by that id, kept the same -/// story, so the fields the search relied on are checked again here against -/// the server's own account of the subject. The repository is compared by -/// id, not `repository_full_name`: a GitHub rename changes the name but not -/// the id, and comparing names would then refuse a review that is actually -/// of the right repository. The id is checked only when the server names -/// one, since it is absent on an old server or a review that names no -/// repository. +/// Search summaries and review-request responses only nominate an ID. +/// Check every subject field the server has recorded. Polling can continue +/// while fields are missing, but reporting requires the requested subject. +/// The repository ID stays stable across GitHub renames. +/// Commit-only jobs also accept legacy details without a repository ID. fn confirm_ci_subject( detail: &ReviewDetail, commit: &str, repository_id: Uuid, + pr: Option, + require_identity: bool, ) -> anyhow::Result<()> { if detail.kind != "PULL_REQUEST" { bail!( @@ -1458,10 +1548,10 @@ fn confirm_ci_subject( text::one_line(&detail.kind) ); } - if !detail + if detail .head_commit_sha .as_deref() - .is_some_and(|head| head.eq_ignore_ascii_case(commit)) + .map_or(require_identity, |head| !head.eq_ignore_ascii_case(commit)) { bail!( "proofline asked for the review of {commit}, but the server returned head commit {}", @@ -1471,35 +1561,55 @@ fn confirm_ci_subject( .map_or_else(|| "none".to_owned(), text::one_line) ); } - if let Some(detail_repository) = detail.repository_id - && detail_repository != repository_id + let require_repository = require_identity && pr.is_some(); + if detail + .repository_id + .map_or(require_repository, |id| id != repository_id) + { + let actual = detail + .repository_id + .map_or_else(|| "none".to_owned(), |id| id.to_string()); + bail!( + "proofline asked for a review in repository {repository_id}, but the server returned repository {actual}" + ); + } + if let Some(pr) = pr + && detail + .pull_request_number + .map_or(require_identity, |number| number != pr) { + let actual = detail + .pull_request_number + .map_or_else(|| "none".to_owned(), |number| number.to_string()); bail!( - "proofline asked for a review in repository {repository_id}, but the server returned a review in repository {detail_repository}" + "proofline asked for the review of pull request #{pr}, but the server returned pull request {actual}" ); } Ok(()) } -/// Waits for the review the App runs for the pull request whose head is -/// `commit`, then reports it. With `request`, a job that has found no review +/// Waits for a review of the job's subject, then reports it. +/// With `request`, a job that has found no review /// after [`REQUEST_AFTER`] asks once for one and reports the review it gets; /// a refusal is reported and the wait goes on. Without it nothing is /// requested, so the job never starts a second review of the head. async fn ci_review( api: &Api, args: &CiReviewArgs, - commit: &str, + subject: CiReviewSubject<'_>, request: Option<&github_actions::ReviewRequest>, ) -> anyhow::Result { let started = tokio::time::Instant::now(); let deadline = poll_deadline(args.timeout)?; - let (name, repository_id) = connected_repository(api, &args.repository).await?; + let (name, repository_id) = connected(api, subject.name, api.repository_names().await?)?; + let subject = CiReviewSubject { + name: &name, + ..subject + }; let Some(review_id) = wait_for_head_review( api, - &name, + subject, repository_id, - commit, args.timeout, started, deadline, @@ -1510,13 +1620,31 @@ async fn ci_review( return Ok(Verdict::Unavailable); }; let sarif_path = args.sarif.as_deref(); + // Only an explicit zero timeout gets a single read without a deadline. + // SARIF checks the full subject when written. During the wait, pending + // details may omit fields, but any recorded conflict stops the job. + let read_deadline = (args.timeout != 0).then_some(deadline); let Some((raw, detail, state)) = - read_review(api, review_id, Some(deadline), sarif_path.is_some()).await? + read_review_checked(api, review_id, read_deadline, false, |detail| { + confirm_ci_subject(detail, subject.commit, repository_id, subject.pr, false) + }) + .await? else { say_not_established(api, review_id, args.timeout); return Ok(Verdict::Unavailable); }; - confirm_ci_subject(&detail, commit, repository_id)?; + if let Err(error) = confirm_ci_subject(&detail, subject.commit, repository_id, subject.pr, true) + { + if state.is_some() { + return Err(error); + } + say(&format!( + "The review did not report its full subject after {} minutes. It continues at {}", + args.timeout, + api.review_url(review_id), + )); + return Ok(Verdict::Unavailable); + } if let Some(path) = sarif_path { write_sarif(api, review_id, &detail, path).await?; } @@ -1536,25 +1664,40 @@ async fn ci_review( Ok(verdict) } -/// Polls for the newest `PULL_REQUEST` review whose head is `commit` until +/// Polls for the newest `PULL_REQUEST` review matching the job's subject until /// `deadline`, asking once through `request` from [`REQUEST_AFTER`] past /// `started`. `None` means no review appeared, which it has already said. async fn wait_for_head_review( api: &Api, - name: &str, + subject: CiReviewSubject<'_>, repository_id: Uuid, - commit: &str, timeout_minutes: u64, started: tokio::time::Instant, deadline: tokio::time::Instant, mut request: Option<&github_actions::ReviewRequest>, ) -> anyhow::Result> { + let CiReviewSubject { name, commit, pr } = subject; + let target = pr.map_or_else(|| name.to_owned(), |number| format!("{name} #{number}")); let request_at = started + REQUEST_AFTER; let mut delay = FIRST_POLL_SECONDS; loop { - let found = latest(api, repository_id, commit, |item| { - item.kind == "PULL_REQUEST" && item.head_commit_sha.as_deref() == Some(commit) - }) + let found = latest( + api, + repository_id, + commit, + pr.map(|number| (name, number)), + |item| { + item.kind == "PULL_REQUEST" + && item + .head_commit_sha + .as_deref() + .is_some_and(|head| head.eq_ignore_ascii_case(commit)) + && pr.is_none_or(|number| { + item.pull_request_number == Some(number) + && item.repository_id.is_none_or(|id| id == repository_id) + }) + }, + ) .await?; if found.is_some() { return Ok(found); @@ -1562,18 +1705,18 @@ async fn wait_for_head_review( let now = tokio::time::Instant::now(); if now >= deadline { say(&format!( - "No pull-request review of {name} has head commit {commit} after {timeout_minutes} minutes. Proofline reviews a commit once it is the head of an open pull request." + "No pull-request review of {target} has head commit {commit} after {timeout_minutes} minutes. Proofline reviews a commit once it is the head of an open pull request." )); return Ok(None); } if now >= request_at && let Some(asking) = request.take() - && let Some(id) = ask_for_review(asking, name, commit).await + && let Some(id) = ask_for_review(asking, &target, commit).await { return Ok(Some(id)); } say(&format!( - "No review of {name} at {commit} yet; checking again in {delay} seconds." + "No review of {target} at {commit} yet; checking again in {delay} seconds." )); let pending = request.is_some().then_some(request_at); tokio::time::sleep(next_pause(delay, now, deadline, pending)).await; @@ -1815,6 +1958,8 @@ mod tests { Completes, /// It starts the review, which is still running whenever it is read. StaysRunning, + /// Its ID resolves to a different PR, with no repository ID yet. + WrongPendingReview, /// It refuses the request. Refused, /// It starts the review. Each read answers after 20 seconds, still @@ -1942,14 +2087,10 @@ mod tests { Json(json!({ "repositories": [{ "id": REPOSITORY, "full_name": "acme/app" }] })) }), ) + .route(&format!("/api/v1/organizations/{ORG}/reviews"), get(empty_review_page)) .route( - &format!("/api/v1/organizations/{ORG}/reviews"), - get(|| async { - Json(json!({ - "items": [], "next_cursor": null, "truncated": false, - "filters": { "repositories": [], "environments": [], "authors": [] }, - })) - }), + &format!("/api/v1/organizations/{ORG}/reviews/pr/app/12"), + get(empty_review_page), ) .route( &format!("/api/v1/organizations/{ORG}/reviews/{REQUESTED}"), @@ -1962,7 +2103,7 @@ mod tests { *reads }; let status = match grant { - Grant::StaysRunning => "RUNNING", + Grant::StaysRunning | Grant::WrongPendingReview => "RUNNING", Grant::AnswersSlowly => { tokio::time::sleep(Duration::from_secs(20)).await; if read <= 2 { "RUNNING" } else { "COMPLETED" } @@ -1974,7 +2115,8 @@ mod tests { "kind": "PULL_REQUEST", "status": status, "head_commit_sha": HEAD, - "pull_request_number": 12, + "pull_request_number": if matches!(grant, Grant::WrongPendingReview) { 13 } else { 12 }, + "repository_id": (!matches!(grant, Grant::WrongPendingReview)).then_some(REPOSITORY), "run_number": 1, "assessment_count": 1, "open_items": { @@ -2019,6 +2161,13 @@ mod tests { (origin, received) } + async fn empty_review_page() -> Json { + Json(json!({ + "items": [], "next_cursor": null, "truncated": false, + "filters": { "repositories": [], "environments": [], "authors": [] }, + })) + } + /// The job asks for a review once, two minutes in, with an OIDC token /// issued for that request, and only when its own signed identity on a /// `pull_request` event is the credential. The clock is paused, so the @@ -2035,11 +2184,12 @@ mod tests { }); let review = "POST /api/v1/ci/github-actions/review".to_owned(); let token_requests = "GET /github/token".to_owned(); - // Whether the job holds `PROOFLINE_TOKEN`, its event, and the verdict. - for (stored_token, event, verdict) in [ - (false, "pull_request", Verdict::Done), - (true, "pull_request", Verdict::Unavailable), - (false, "push", Verdict::Unavailable), + for (stored_token, event, pr, verdict) in [ + (false, "pull_request", Some(12), Verdict::Done), + (true, "pull_request", Some(12), Verdict::Unavailable), + (false, "pull_request_target", Some(12), Verdict::Unavailable), + (false, "workflow_run", Some(12), Verdict::Unavailable), + (false, "push", None, Verdict::Unavailable), ] { let case = format!("token {stored_token}, {event}"); let start = tokio::time::Instant::now(); @@ -2050,6 +2200,7 @@ mod tests { SecretString::from("runner-secret"), ); let args = CiReviewArgs { + pr: None, commit: None, sarif: None, annotations: false, @@ -2063,7 +2214,12 @@ mod tests { }; let token = stored_token.then(|| SecretString::from("plp_stored")); let org = stored_token.then(|| ORG.parse().unwrap()); - let ended = ci_job(http, token, Some(issuer), event, org, &args, HEAD) + let subject = CiReviewSubject { + name: "acme/app", + commit: HEAD, + pr, + }; + let ended = ci_job(http, token, Some(issuer), event, org, &args, subject) .await .unwrap(); assert_eq!(ended, verdict, "{case}"); @@ -2121,6 +2277,7 @@ mod tests { SecretString::from("runner-secret"), ); let args = CiReviewArgs { + pr: None, commit: None, sarif: None, annotations: false, @@ -2132,7 +2289,21 @@ mod tests { remote: "origin".to_owned(), }, }; - let verdict = ci_job(http, None, Some(issuer), "pull_request", None, &args, HEAD).await; + let subject = CiReviewSubject { + name: "acme/app", + commit: HEAD, + pr: Some(12), + }; + let verdict = ci_job( + http, + None, + Some(issuer), + "pull_request", + None, + &args, + subject, + ) + .await; ticker.abort(); let received = received.lock().unwrap().clone(); (verdict, received) @@ -2189,6 +2360,38 @@ mod tests { } } + #[tokio::test(start_paused = true)] + async fn a_deadline_used_up_before_polling_does_not_start_a_detail_read() { + let deadline = tokio::time::Instant::now(); + let (origin, received) = console(deadline, Grant::Completes, HOURLY).await; + let http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); + let api = Api::new(http, SecretString::from("plp_stored"), ORG.parse().unwrap()); + let read = read_review_checked( + &api, + REQUESTED.parse().unwrap(), + Some(deadline), + false, + |_| Ok(()), + ) + .await + .unwrap(); + assert!(read.is_none()); + assert!(received.lock().unwrap().is_empty()); + } + + #[tokio::test(start_paused = true)] + async fn a_requested_review_of_another_pr_is_rejected_before_waiting() { + let (verdict, received) = pull_request_job(Grant::WrongPendingReview, HOURLY).await; + let error = verdict.unwrap_err().to_string(); + assert!(error.contains("returned pull request 13"), "{error}"); + assert_eq!(review_requests(&received), 1); + let detail = format!("GET /api/v1/organizations/{ORG}/reviews/{REQUESTED}"); + assert_eq!( + received.iter().filter(|(path, ..)| *path == detail).count(), + 1 + ); + } + /// A credential granted for 100 seconds is renewed at the first read past /// half its lifetime, with a newly issued identity, so the wait reads under the first and /// completes under the second, and the job still asks for one review. A @@ -2196,7 +2399,7 @@ mod tests { /// failure (exit 1); one it cannot serve ends it as unavailable (exit 4). #[tokio::test(start_paused = true)] async fn a_wait_renews_its_credential_and_a_refused_renewal_ends_it() { - let reviews = format!("GET /api/v1/organizations/{ORG}/reviews"); + let reviews = format!("GET /api/v1/organizations/{ORG}/reviews/pr/app/12"); let requested = format!("GET /api/v1/organizations/{ORG}/reviews/{REQUESTED}"); let exchanges = "POST /api/v1/ci/github-actions/credentials"; let (verdict, received) = pull_request_job(Grant::Completes, Exchange::Grants(100)).await; diff --git a/tests/http.rs b/tests/http.rs index 940dc12..9cd878c 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -195,6 +195,7 @@ async fn cli_for_organization( "unix:path=/proofline-test-unavailable-bus", ) .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env_remove("GITHUB_EVENT_NAME") .env("PATH", "") .current_dir(directory); if use_flag { @@ -206,13 +207,14 @@ async fn cli_for_organization( } else { command.env("PROOFLINE_ORGANIZATION_ID", organization); } - tokio::time::timeout( - std::time::Duration::from_secs(15), - command.args(args).kill_on_drop(true).output(), - ) - .await - .unwrap() - .unwrap() + cli_output(command.args(args).kill_on_drop(true)).await +} + +async fn cli_output(command: &mut tokio::process::Command) -> std::process::Output { + tokio::time::timeout(std::time::Duration::from_secs(15), command.output()) + .await + .unwrap() + .unwrap() } #[tokio::test] @@ -1345,6 +1347,19 @@ async fn findings_of_a_departed_repository_still_resolve_through_its_reviews() { const CI_REPOSITORY: &str = "0190f3a0-0000-7000-8000-0000000000f0"; const CI_REVIEW: &str = "0190f3a0-0000-7000-8000-0000000000f1"; const CI_HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; +const OTHER_HEAD: &str = "0123456789abcdef0123456789abcdef01234567"; +const CLEAN_PR_REVIEW: &str = "0190f3a0-0000-7000-8000-0000000000fa"; + +#[derive(Clone, Copy)] +enum PrReviewFixture { + Single, + SamePage, + LaterPage, + WrongDetail, + MissingDetailRepository, + Pending { sparse: bool }, + Missing, +} #[derive(Debug, Clone, Copy)] struct CiCodeFinding { @@ -1373,6 +1388,25 @@ async fn ci_console( assessment: &'static str, open: Option<[u64; 2]>, code: Option, +) -> (String, Arc>>) { + ci_console_with_prs( + kind, + status, + assessment, + open, + code, + PrReviewFixture::Single, + ) + .await +} + +async fn ci_console_with_prs( + kind: &'static str, + status: StatusCode, + assessment: &'static str, + open: Option<[u64; 2]>, + code: Option, + fixture: PrReviewFixture, ) -> (String, Arc>>) { let requests = Arc::new(Mutex::new(Vec::new())); let findings = match open { @@ -1395,6 +1429,62 @@ async fn ci_console( "not_assessed": [], }) }); + let review_pages = get(move |uri: axum::http::Uri| async move { + let scoped = uri.path().ends_with("/reviews/pr/app/12"); + let query: std::collections::HashMap<_, _> = + url::form_urlencoded::parse(uri.query().unwrap_or_default().as_bytes()).collect(); + if scoped { + assert_eq!( + query.get("repository").map(AsRef::as_ref), + Some(CI_REPOSITORY) + ); + assert!(!query.contains_key("search")); + } else { + assert!(uri.path().ends_with("/reviews"), "{uri}"); + } + let mut exact = json!({ + "id": CI_REVIEW, + "kind": kind, + "status": "COMPLETED", + "created_at": "2026-10-01T00:00:00Z", + "head_commit_sha": CI_HEAD, + "pull_request_number": 12, + "repository_id": CI_REPOSITORY, + "run_number": 1, + }); + let mut clean = exact.clone(); + clean["id"] = json!(CLEAN_PR_REVIEW); + clean["pull_request_number"] = json!(13); + let mut wrong_repository = exact.clone(); + wrong_repository["id"] = json!("0190f3a0-0000-7000-8000-0000000000fb"); + wrong_repository["repository_id"] = json!(REPOSITORY); + let mut old_head = exact.clone(); + old_head["head_commit_sha"] = json!(OTHER_HEAD); + old_head["id"] = json!("0190f3a0-0000-7000-8000-0000000000fc"); + if scoped { + exact.as_object_mut().unwrap().remove("repository_id"); + } + let (items, cursor) = match fixture { + PrReviewFixture::Single => (vec![exact], None), + _ if !scoped => (vec![clean], None), + PrReviewFixture::LaterPage + if query.get("cursor").is_some_and(|value| value == "next") => + { + (vec![exact], None) + } + // A scoped list can still contain rows for the wrong subject. + PrReviewFixture::LaterPage => (vec![clean, wrong_repository, old_head], Some("next")), + PrReviewFixture::Missing => (vec![old_head], None), + _ => (vec![exact], None), + }; + Json(json!({ + "items": items, + "next_cursor": cursor, + "truncated": cursor.is_some(), + "filters": { "repositories": [], "environments": [], "authors": [] }, + })) + }); + let detail_reads = Arc::new(AtomicUsize::new(0)); let app = Router::new() // The GitHub Actions runner's OIDC token endpoint and the exchange. .route( @@ -1436,23 +1526,11 @@ async fn ci_console( ) .route( &format!("/api/v1/organizations/{ORG}/reviews"), - get(move || async move { - Json(json!({ - "items": [{ - "id": CI_REVIEW, - "kind": kind, - "status": "COMPLETED", - "created_at": "2026-10-01T00:00:00Z", - "head_commit_sha": CI_HEAD, - "pull_request_number": 12, - "repository_id": CI_REPOSITORY, - "run_number": 1, - }], - "next_cursor": null, - "truncated": false, - "filters": { "repositories": [], "environments": [], "authors": [] }, - })) - }), + review_pages.clone(), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/pr/app/12"), + review_pages, ) .route( &format!( @@ -1468,10 +1546,14 @@ async fn ci_console( }), ) .route( - &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), - get(move || { + &format!("/api/v1/organizations/{ORG}/reviews/{{id}}"), + get(move |Path(id): Path| { let (findings, open_items) = (findings.clone(), open_items.clone()); + let reads = Arc::clone(&detail_reads); async move { + if id != CI_REVIEW && id != CLEAN_PR_REVIEW { + return StatusCode::NOT_FOUND.into_response(); + } if !status.is_success() { return ( status, @@ -1479,12 +1561,32 @@ async fn ci_console( ) .into_response(); } + if let PrReviewFixture::Pending { sparse } = fixture + && reads.fetch_add(1, Ordering::Relaxed) == 0 + { + let mut pending = json!({ + "id": id, + "kind": "PULL_REQUEST", + "status": "PENDING", + "assessment_count": 0, + "assessments": [], + }); + if !sparse { + pending["repository_id"] = json!(CI_REPOSITORY); + pending["pull_request_number"] = json!(12); + pending["head_commit_sha"] = json!(CI_HEAD); + } + return Json(pending).into_response(); + } + let clean = id == CLEAN_PR_REVIEW; + let pr = if clean || matches!(fixture, PrReviewFixture::WrongDetail) { 13 } else { 12 }; let mut document = json!({ - "id": CI_REVIEW, + "id": id, "kind": "PULL_REQUEST", "status": "COMPLETED", "head_commit_sha": CI_HEAD, - "pull_request_number": 12, + "repository_id": CI_REPOSITORY, + "pull_request_number": pr, "run_number": 1, "assessment_count": 1, "open_items": open_items, @@ -1496,6 +1598,15 @@ async fn ci_console( "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, }], }); + if clean { + document["open_items"]["open_findings"] = json!(0); + document["open_items"]["serious_findings"] = json!(0); + document["assessments"][0]["findings"] = json!([]); + return Json(document).into_response(); + } + if matches!(fixture, PrReviewFixture::MissingDetailRepository) { + document.as_object_mut().unwrap().remove("repository_id"); + } if let Some(code) = code { let findings = code.severity.map_or_else( || json!([]), @@ -1652,6 +1763,7 @@ async fn ci_review_attaches_to_the_head_review_and_keeps_unknown_apart_in_its_ex .env("PROOFLINE_TOKEN", TOKEN) .env("COMMIT_SHA", CI_HEAD) .env_remove("GITHUB_SHA") + .env_remove("GITHUB_EVENT_NAME") .env("PATH", "") .current_dir(directory.path()) .kill_on_drop(true); @@ -1676,6 +1788,16 @@ async fn ci_review_attaches_to_the_head_review_and_keeps_unknown_apart_in_its_ex ); if code == 1 { assert!(requests.is_empty(), "{requests:?}"); + } else { + assert!( + requests.contains(&format!("GET /api/v1/organizations/{ORG}/reviews")), + "{requests:?}" + ); + assert!( + !requests + .iter() + .any(|request| request.contains("/reviews/pr/")) + ); } match sarif { Some(success) => { @@ -1716,38 +1838,34 @@ async fn ci_review_attaches_to_the_head_review_and_keeps_unknown_apart_in_its_ex #[tokio::test] async fn ci_review_on_a_pull_request_event_reviews_the_head_not_the_merge_commit() { - let (origin, _) = ci_console("PULL_REQUEST", StatusCode::OK, "COMPLETED", None, None).await; - // GitHub's merge commit, which no review has as its head. - let merge = "0123456789abcdef0123456789abcdef01234567"; - let cases = [ - (json!({ "pull_request": { "head": { "sha": CI_HEAD } } }), 0), - // Without the head the job names it; the merge commit is never used. - (json!({ "pull_request": { "number": 7 } }), 1), - ]; - for (payload, code) in cases { + // The fixture sets GITHUB_SHA to a different commit, as with a merge build. + for (payload, exit) in [ + ( + json!({ "number": 12, "pull_request": { "head": { "sha": CI_HEAD } } }), + 3, + ), + (json!({ "pull_request": { "number": 12 } }), 1), + // Either number field can identify the PR, but both must agree when supplied. + ( + json!({ "number": 13, "pull_request": { "number": 12, "head": { "sha": CI_HEAD } } }), + 1, + ), + ] { let directory = tempfile::tempdir().unwrap(); - let event = directory.path().join("event.json"); - std::fs::write(&event, payload.to_string()).unwrap(); - let output = tokio::time::timeout( - std::time::Duration::from_secs(15), - tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) - .args(["--base-url", &origin, "--org", ORG, "ci", "review"]) - .args(["--repo", "acme/app", "--timeout", "0"]) - .env("PROOFLINE_TOKEN", TOKEN) - .env_remove("COMMIT_SHA") - .env("GITHUB_SHA", merge) - .env("GITHUB_EVENT_NAME", "pull_request") - .env("GITHUB_EVENT_PATH", &event) - .env("PATH", "") - .current_dir(directory.path()) - .kill_on_drop(true) - .output(), + let (mut command, requests) = pr_review_cli( + PrReviewFixture::Single, + directory.path(), + "pull_request", + payload, + false, ) - .await - .unwrap() - .unwrap(); + .await; + let output = cli_output(command.args(["--timeout", "0"])).await; let stderr = String::from_utf8_lossy(&output.stderr); - assert_eq!(output.status.code(), Some(code), "{payload}: {stderr}"); + assert_eq!(output.status.code(), Some(exit), "{stderr}"); + if exit == 1 { + assert!(requests.lock().unwrap().is_empty(), "{stderr}"); + } } } @@ -1787,6 +1905,16 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede ]; for (origin, code) in cases { let directory = tempfile::tempdir().unwrap(); + let event = directory.path().join("event.json"); + std::fs::write( + &event, + json!({ + "repository": { "full_name": "acme/app" }, + "pull_request": { "number": 12, "head": { "sha": CI_HEAD } }, + }) + .to_string(), + ) + .unwrap(); let output = tokio::time::timeout( std::time::Duration::from_secs(15), tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) @@ -1800,6 +1928,7 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede ) .env("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-secret") .env("GITHUB_EVENT_NAME", "pull_request") + .env("GITHUB_EVENT_PATH", &event) .env("PATH", "") .current_dir(directory.path()) .kill_on_drop(true) @@ -1826,6 +1955,325 @@ async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_crede ); } +async fn pr_review_cli( + fixture: PrReviewFixture, + directory: &std::path::Path, + event: &str, + payload: Value, + runner: bool, +) -> (tokio::process::Command, Arc>>) { + let (origin, requests) = ci_console_with_prs( + "PULL_REQUEST", + StatusCode::OK, + "COMPLETED", + Some([1, 1]), + None, + fixture, + ) + .await; + let event_path = directory.join("event.json"); + std::fs::write(&event_path, payload.to_string()).unwrap(); + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")); + command + .args(["--base-url", &origin, "--org", ORG, "ci", "review"]) + .args(["--repo", "Acme/APP", "--fail-on", "serious", "--json"]) + .env("GITHUB_EVENT_NAME", event) + .env("GITHUB_EVENT_PATH", event_path) + .env("GITHUB_SHA", OTHER_HEAD) + .env_remove("COMMIT_SHA") + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .current_dir(directory) + .kill_on_drop(true); + if runner { + command + .env_remove("PROOFLINE_TOKEN") + .env( + "ACTIONS_ID_TOKEN_REQUEST_URL", + format!("{origin}/github/token?api-version=2.0"), + ) + .env("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-secret"); + } else { + command.env("PROOFLINE_TOKEN", TOKEN); + } + (command, requests) +} + +#[tokio::test] +async fn ci_review_binds_findings_to_the_jobs_pull_request() { + use PrReviewFixture::*; + #[derive(Clone, Copy)] + struct Case { + fixture: PrReviewFixture, + runner: bool, + repository: Option<&'static str>, + commit: Option<&'static str>, + cloud_commit: Option<&'static str>, + event_head: &'static str, + exit: i32, + } + let later_page = Case { + fixture: LaterPage, + runner: false, + repository: None, + commit: None, + cloud_commit: None, + event_head: CI_HEAD, + exit: 3, + }; + let repository_conflict = Case { + fixture: SamePage, + repository: Some("acme/other"), + commit: Some(CI_HEAD), + exit: 1, + ..later_page + }; + for Case { + fixture, + runner, + repository, + commit, + cloud_commit, + event_head, + exit, + } in [ + later_page, + Case { + runner: true, + ..later_page + }, + Case { + repository: Some("aCmE/aPp"), + cloud_commit: Some(CI_HEAD), + event_head: OTHER_HEAD, + ..later_page + }, + Case { + fixture: WrongDetail, + repository: Some("acme/app"), + commit: Some(CI_HEAD), + cloud_commit: Some(OTHER_HEAD), + event_head: OTHER_HEAD, + exit: 1, + ..later_page + }, + Case { + fixture: MissingDetailRepository, + repository: Some("acme/app"), + exit: 1, + ..later_page + }, + Case { + fixture: Missing, + repository: Some("acme/app"), + exit: 4, + ..later_page + }, + repository_conflict, + Case { + runner: true, + repository: Some("acme/other\nrepo"), + ..repository_conflict + }, + ] { + let directory = tempfile::tempdir().unwrap(); + let mut payload = json!({ + "pull_request": { "number": 12, "head": { "sha": event_head } }, + }); + if let Some(repository) = repository { + payload["repository"] = json!({ "full_name": repository }); + } + let (mut command, requests) = + pr_review_cli(fixture, directory.path(), "pull_request", payload, runner).await; + let sarif = directory.path().join("result.sarif"); + command.args(["--timeout", "0", "--sarif"]).arg(&sarif); + if let Some(commit) = commit { + command.args(["--commit", commit]); + } + if let Some(cloud_commit) = cloud_commit { + command.env("COMMIT_SHA", cloud_commit); + } + let output = cli_output(&mut command).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(exit), "{stderr}"); + let requests = requests.lock().unwrap(); + let conflict = repository.is_some_and(|name| name.starts_with("acme/other")); + assert!(!requests.contains(&format!("GET /api/v1/organizations/{ORG}/reviews"))); + let detail = format!("GET /api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"); + assert_eq!( + requests.contains(&detail), + !conflict && !matches!(fixture, Missing) + ); + assert!( + !requests + .iter() + .any(|request| request.ends_with(CLEAN_PR_REVIEW)) + ); + assert_eq!(sarif.exists(), exit == 3); + if conflict { + assert!(requests.is_empty(), "{requests:?}"); + assert!(stderr.contains("pass --repo acme/other"), "{stderr}"); + assert!( + stderr.contains("selected repository is Acme/APP"), + "{stderr}" + ); + if runner { + assert!(stderr.contains("acme/other repo"), "{stderr}"); + assert!(!stderr.contains("acme/other\nrepo"), "{stderr}"); + } + } else if exit == 3 { + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["review"]["id"], CI_REVIEW); + assert_eq!(result["review"]["pull_request_number"], 12); + assert_eq!( + requests + .iter() + .any(|request| request == "GET /github/token"), + runner + ); + if matches!(fixture, LaterPage) { + let list = format!("GET /api/v1/organizations/{ORG}/reviews/pr/app/12"); + assert_eq!( + requests.iter().filter(|request| **request == list).count(), + 2 + ); + } + } else if matches!(fixture, WrongDetail) { + assert!(stderr.contains("pull request #12"), "{stderr}"); + assert!(stderr.contains("returned pull request 13"), "{stderr}"); + assert!(output.stdout.is_empty()); + } else if matches!(fixture, MissingDetailRepository) { + assert!(stderr.contains("returned repository none"), "{stderr}"); + assert!(output.stdout.is_empty()); + } else { + assert!(stderr.contains("acme/app #12"), "{stderr}"); + assert!(stderr.contains("after 0 minutes"), "{stderr}"); + } + } +} + +#[tokio::test] +async fn ci_review_explicit_pr_uses_the_named_head_in_downstream_jobs() { + let explicit = ["--pr", "12", "--commit", CI_HEAD]; + let cases: &[(&str, &[&str], i32, &str)] = &[ + ("workflow_run", &explicit, 3, ""), + ("workflow_dispatch", &explicit, 3, ""), + ( + "workflow_run", + &["--pr", "12"], + 1, + "--pr requires --commit SHA", + ), + ( + "workflow_run", + &["--pr", "12", "--commit", "89abcdef"], + 1, + "full commit SHA", + ), + ( + "workflow_run", + &["--pr", "0", "--commit", CI_HEAD], + 1, + "invalid value", + ), + ( + "pull_request", + &["--pr", "13", "--commit", CI_HEAD], + 1, + "omit --pr or pass --pr 12", + ), + ("pull_request", &["--pr", "12"], 3, ""), + ]; + for &(event, flags, exit, error) in cases { + let directory = tempfile::tempdir().unwrap(); + let (mut command, requests) = pr_review_cli( + PrReviewFixture::SamePage, + directory.path(), + event, + json!({ + "repository": { "full_name": "acme/app" }, + "pull_request": { "number": 12, "head": { "sha": CI_HEAD } }, + }), + false, + ) + .await; + command.args(["--timeout", "0"]).args(flags); + if event != "pull_request" { + command.env("COMMIT_SHA", OTHER_HEAD); + } + let output = cli_output(&mut command).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.code(), + Some(exit), + "{event} {flags:?}: {stderr}" + ); + let requests = requests.lock().unwrap(); + if exit == 3 { + let review: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(review["review"]["id"], CI_REVIEW); + assert!(requests.iter().all(|request| request.starts_with("GET "))); + } else { + assert!(stderr.contains(error), "{event} {flags:?}: {stderr}"); + assert!(requests.is_empty(), "{requests:?}"); + } + } +} + +#[tokio::test] +async fn ci_review_reports_a_pending_result_only_when_its_subject_is_known() { + for (runner, sparse, timeout, exit, reads) in [ + (false, true, "1", 3, 2), + (true, true, "1", 3, 2), + (true, true, "0", 4, 1), + (true, false, "0", 4, 1), + ] { + let directory = tempfile::tempdir().unwrap(); + let event = json!({ "pull_request": { "number": 12, "head": { "sha": CI_HEAD } } }); + let (mut command, requests) = pr_review_cli( + PrReviewFixture::Pending { sparse }, + directory.path(), + "pull_request", + event, + runner, + ) + .await; + let sarif = directory.path().join("result.sarif"); + let output = cli_output(command.args(["--timeout", timeout, "--sarif"]).arg(&sarif)).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(exit), "{stderr}"); + let detail = format!("GET /api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"); + assert_eq!( + requests + .lock() + .unwrap() + .iter() + .filter(|path| **path == detail) + .count(), + reads + ); + let reports = exit == 3 || !sparse; + assert_eq!(sarif.exists(), reports); + if reports { + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["review"]["head_commit_sha"], CI_HEAD); + if exit == 4 { + assert_eq!(result.get("outcome"), Some(&Value::Null)); + let sarif: Value = serde_json::from_slice(&std::fs::read(sarif).unwrap()).unwrap(); + assert_eq!( + sarif["runs"][0]["invocations"][0]["executionSuccessful"], + false + ); + } + } else { + assert!(output.stdout.is_empty()); + assert!( + stderr.contains("did not report its full subject"), + "{stderr}" + ); + } + } +} + #[tokio::test] async fn ci_review_fail_on_exits_three_for_an_open_finding_of_a_complete_review() { let code = |only, severity, lifecycle_state| {