From be4fc3552ae3a3f440f7d430679697ab27379db7 Mon Sep 17 00:00:00 2001 From: Abdulqoyyum Aileru Date: Thu, 12 Nov 2026 01:00:24 +0000 Subject: [PATCH] Read deployment reviews and hold a deploy job to them findings --deployment reads a deployment review by its public key through the review API's deployment operation, and refuses a reply that is another review or not a deployment review. ci deployment waits for the deployment review of the commit being deployed and reports it with the exit codes of ci review, including --fail-on. It only reads: the review API has no operation that requests one. --- README.md | 28 ++++ src/api.rs | 16 ++ src/deployment.rs | 160 +++++++++++++++++++ src/lib.rs | 223 ++++++++++++++++++++++++--- tests/contract.rs | 11 ++ tests/deployment.rs | 368 ++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 782 insertions(+), 24 deletions(-) create mode 100644 src/deployment.rs create mode 100644 tests/deployment.rs diff --git a/README.md b/README.md index 25b8097..75cdd35 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,34 @@ Knowledge reads need `reviews:read` and `knowledge:read`. Implementation also ne opens that GitHub organization's installation page; `--print` only prints its address. Cloud trust and connection changes still require a signed-in administrator browser. +## Deployment reviews + +Read a deployment review by its public key, `rev_` followed by 32 hexadecimal +digits, as its console address shows: + +```sh +proofline findings --deployment rev_0190f3a00000700080000000000000d1 --wait +``` + +The command reads the deployment operation of the review API and refuses a +reply that is another review or not a deployment review. `--json`, `--wait` and +`--timeout` behave as they do for `--review`; `--sarif` is for a retained +pull-request review. Reads need `reviews:read`. + +A deploy job holds itself to the review of the commit it deploys: + +```sh +proofline ci deployment --commit "$DEPLOYED_SHA" --fail-on serious +``` + +`ci deployment` waits for the deployment review whose head is that full commit +SHA, defaulting to `COMMIT_SHA` and then the GitHub Actions job's commit. It +authenticates as `ci review` does, with `PROOFLINE_TOKEN` or a GitHub Actions +job granted `id-token: write`. It only reads: the review API has no operation +that requests a deployment review, and a pull-request review of the same commit +is not its answer. Exit codes match `ci review`: 0 complete, 2 not complete, 3 an +open finding at or above `--fail-on`, 4 no answer before `--timeout`. + ## Windows Official releases include `proofline-x86_64-pc-windows-msvc.tar.gz` with `proofline.exe`. diff --git a/src/api.rs b/src/api.rs index f908670..9b29a94 100644 --- a/src/api.rs +++ b/src/api.rs @@ -10,6 +10,7 @@ use serde::de::DeserializeOwned; use url::Url; use uuid::Uuid; +use crate::deployment::PublicKey; use crate::model::{ CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, CoverageUploadResponse, FileReviewRequest, FileReviewResponse, PatchReviewRequest, PatchReviewResponse, @@ -476,6 +477,21 @@ impl Api { Ok((raw, typed)) } + /// Fetches a deployment review by its public key, as the raw document and + /// its typed reading. The caller holds the result to the key. + pub async fn deployment_review( + &self, + key: PublicKey, + ) -> Result<(serde_json::Value, ReviewDetail), ApiError> { + let key = key.to_string(); + let raw = self + .get(self.url(&["reviews", "deployments", &key])) + .await?; + let typed = serde_json::from_value(raw.clone()) + .map_err(|error| self.http.protocol(error.to_string()))?; + Ok((raw, typed)) + } + /// One page of the review collection, newest first. pub async fn reviews( &self, diff --git a/src/deployment.rs b/src/deployment.rs new file mode 100644 index 0000000..ff910d3 --- /dev/null +++ b/src/deployment.rs @@ -0,0 +1,160 @@ +//! A deployment review's public address. The review API reads a deployment +//! review by its `public_key`: `rev_` followed by the review's identifier +//! without hyphens. The key is parsed before any request, and the review the +//! server returns is held to it, so a command never reports another review +//! as the deployment the caller named. + +use std::fmt; +use std::str::FromStr; + +use uuid::Uuid; + +use crate::model::ReviewDetail; + +const PREFIX: &str = "rev_"; +/// A review identifier without its hyphens. +const DIGITS: usize = 32; +/// The `kind` of a deployment review. +pub const KIND: &str = "DEPLOYMENT"; + +/// The stable public address of one review. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PublicKey(Uuid); + +impl PublicKey { + /// The review this key addresses. + pub const fn review_id(self) -> Uuid { + self.0 + } +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +#[error("a deployment review key is `rev_` followed by 32 lowercase hexadecimal digits")] +pub struct InvalidPublicKey; + +impl FromStr for PublicKey { + type Err = InvalidPublicKey; + + /// Only the canonical form: the key becomes a path segment, and a second + /// spelling of one review would not be the address the server published. + fn from_str(raw: &str) -> Result { + let digits = raw.strip_prefix(PREFIX).ok_or(InvalidPublicKey)?; + if digits.len() != DIGITS + || !digits + .bytes() + .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) + { + return Err(InvalidPublicKey); + } + Uuid::try_parse(digits) + .map(Self) + .map_err(|_| InvalidPublicKey) + } +} + +impl fmt::Display for PublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{PREFIX}{}", self.0.simple()) + } +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum DeploymentError { + #[error("requested deployment review {requested}, but the server returned review {returned}")] + WrongReview { + requested: PublicKey, + returned: Uuid, + }, + #[error("review {review} has kind {kind}, not DEPLOYMENT; read it with `findings --review`")] + NotADeployment { review: Uuid, kind: String }, +} + +/// Holds the returned review to the key that asked for it. +pub fn validate(detail: &ReviewDetail, requested: PublicKey) -> Result<(), DeploymentError> { + if detail.id != requested.review_id() { + return Err(DeploymentError::WrongReview { + requested, + returned: detail.id, + }); + } + if detail.kind != KIND { + return Err(DeploymentError::NotADeployment { + review: detail.id, + kind: crate::text::one_line(&detail.kind), + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const REVIEW: &str = "0190f3a0-0000-7000-8000-0000000000d1"; + const KEY: &str = "rev_0190f3a00000700080000000000000d1"; + + fn key() -> String { + KEY.to_owned() + } + + fn detail(id: &str, kind: &str) -> ReviewDetail { + serde_json::from_value(serde_json::json!({ + "id": id, + "kind": kind, + "status": "COMPLETED", + "assessment_count": 0, + "assessments": [], + })) + .unwrap() + } + + #[test] + fn a_key_names_its_review_and_prints_as_it_was_written() { + let parsed: PublicKey = key().parse().unwrap(); + assert_eq!(parsed.review_id(), Uuid::parse_str(REVIEW).unwrap()); + assert_eq!(parsed.to_string(), key()); + } + + #[test] + fn only_the_canonical_spelling_is_a_key() { + for refused in [ + "", + REVIEW, + // No prefix, another prefix, or the hyphenated identifier. + "0190f3a00000700080000000000000d1", + "REV_0190f3a00000700080000000000000d1", + "rev_0190f3a0-0000-7000-8000-0000000000d1", + // Uppercase digits, one digit short and one digit long. + "rev_0190F3A00000700080000000000000D1", + "rev_0190f3a00000700080000000000000d", + "rev_0190f3a00000700080000000000000d10", + // Thirty-two characters that are not all digits. + "rev_0190f3a0000070008000000/../../x1", + " rev_0190f3a00000700080000000000000d1", + ] { + assert_eq!( + refused.parse::(), + Err(InvalidPublicKey), + "{refused:?}" + ); + } + } + + #[test] + fn a_returned_review_must_be_the_deployment_that_was_named() { + let requested: PublicKey = key().parse().unwrap(); + assert_eq!(validate(&detail(REVIEW, KIND), requested), Ok(())); + let other = "0190f3a0-0000-7000-8000-0000000000d2"; + assert_eq!( + validate(&detail(other, KIND), requested), + Err(DeploymentError::WrongReview { + requested, + returned: Uuid::parse_str(other).unwrap(), + }) + ); + // Untrusted server text is contained before it reaches the terminal. + let refused = validate(&detail(REVIEW, "PULL_\u{1b}[31mREQUEST"), requested).unwrap_err(); + assert!(matches!(refused, DeploymentError::NotADeployment { .. })); + assert!(!refused.to_string().contains('\u{1b}')); + } +} diff --git a/src/lib.rs b/src/lib.rs index 6096711..8dfe771 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ mod agent; pub mod api; mod coverage; pub mod credentials; +pub mod deployment; pub mod device; pub mod git; mod github_actions; @@ -158,6 +159,72 @@ enum CiCommand { /// Such a job on a `pull_request` event that finds no review after two /// minutes asks once for a withheld review of its head. Review(CiReviewArgs), + /// Wait for the deployment review of the commit being deployed and report it. + /// + /// A deploy job runs this to hold its pipeline to Proofline's result for + /// that exact commit. It authenticates as `ci review` does and only reads: + /// the review API has no operation that requests a deployment review. + Deployment(CiDeploymentArgs), +} + +/// Which review of the commit under test a CI job waits for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CiKind { + PullRequest, + Deployment, +} + +impl CiKind { + /// The review `kind` the API lists. + const fn api(self) -> &'static str { + match self { + Self::PullRequest => "PULL_REQUEST", + Self::Deployment => deployment::KIND, + } + } + + const fn noun(self) -> &'static str { + match self { + Self::PullRequest => "pull-request review", + Self::Deployment => "deployment review", + } + } +} + +#[derive(Debug, Args)] +struct CiDeploymentArgs { + /// Full commit SHA being deployed. Defaults to `COMMIT_SHA`, then the + /// GitHub Actions job's commit. + #[arg(long, value_name = "SHA")] + commit: Option, + /// Print JSON instead of text. + #[arg(long)] + json: bool, + /// Minutes to wait for the review to appear and finish. + #[arg(long, default_value_t = 30, value_name = "MINUTES")] + timeout: u64, + /// Exit 3 when the completed review has an open finding at or above this + /// severity, as `ci review --fail-on` does. Without this flag, findings + /// never fail the job. An incomplete review exits 2 whatever it found. + #[arg(long, value_enum, value_name = "SEVERITY")] + fail_on: Option, + #[command(flatten)] + repository: RepositoryArgs, +} + +impl From for CiReviewArgs { + /// A deployment job waits as a pull-request job does. It writes no SARIF: + /// that projection is of a retained pull-request review. + fn from(args: CiDeploymentArgs) -> Self { + Self { + commit: args.commit, + sarif: None, + json: args.json, + timeout: args.timeout, + fail_on: args.fail_on, + repository: args.repository, + } + } } #[derive(Debug, Args)] @@ -310,6 +377,45 @@ struct Selector { /// This review. #[arg(long, value_name = "ID")] review: Option, + /// This deployment review, by its public key: `rev_` and 32 hexadecimal + /// digits, as its console address shows. + #[arg(long, value_name = "KEY")] + deployment: Option, +} + +/// How a command addresses the review it reads: by identifier, or by a +/// deployment review's public key through the operation that serves it. +#[derive(Debug, Clone, Copy)] +enum Address { + Review(Uuid), + Deployment(deployment::PublicKey), +} + +impl Address { + const fn review_id(self) -> Uuid { + match self { + Self::Review(id) => id, + Self::Deployment(key) => key.review_id(), + } + } + + /// One read. A deployment key's answer must be that deployment review. + async fn fetch(self, api: &Api) -> anyhow::Result<(serde_json::Value, ReviewDetail)> { + match self { + Self::Review(id) => Ok(api.review(id).await?), + Self::Deployment(key) => { + let (raw, detail) = api.deployment_review(key).await?; + deployment::validate(&detail, key)?; + Ok((raw, detail)) + } + } + } +} + +impl From for Address { + fn from(id: Uuid) -> Self { + Self::Review(id) + } } #[derive(Debug, Args)] @@ -320,7 +426,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", "head", "deployment"])] sarif: bool, #[command(flatten)] repository: RepositoryArgs, @@ -350,7 +456,8 @@ pub enum Verdict { /// Proofline did not answer: it was unreachable, failed on its side, or /// had no finished review before the deadline. Unavailable, - /// A complete review has an open finding at or above `ci review --fail-on`. + /// A complete review has an open finding at or above the `--fail-on` of + /// `ci review` or `ci deployment`. ThresholdReached, /// A Git hook's exit policy refuses the commit or push. Blocked, @@ -511,12 +618,16 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + Command::Ci(command) => { + let (kind, args) = match command { + CiCommand::Review(args) => (CiKind::PullRequest, args), + CiCommand::Deployment(args) => (CiKind::Deployment, args.into()), + }; 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 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, kind, &args, &commit).await; match result { Err(error) if unavailable(&error) => { say(&format!("proofline: {error:#}")); @@ -931,6 +1042,17 @@ async fn finish(api: &Api, review_id: Uuid, args: &ReviewArgs) -> anyhow::Result } async fn findings(api: &Api, args: &FindingsArgs) -> anyhow::Result { + if let Some(key) = args.selector.deployment { + let format = OutputFormat::from_json(args.output.json); + return show( + api, + Address::Deployment(key), + args.wait, + &args.output, + format, + ) + .await; + } let review_id = match (&args.selector.review, args.selector.pr) { (Some(id), _) => *id, (None, Some(number)) => { @@ -980,13 +1102,15 @@ fn poll_deadline(minutes: u64) -> Result, deadline: Option, sarif: bool, ) -> anyhow::Result<(serde_json::Value, ReviewDetail, Option)> { + let address = address.into(); + let review_id = address.review_id(); let mut delay = FIRST_POLL_SECONDS; loop { - let (raw, detail) = api.review(review_id).await?; + let (raw, detail) = address.fetch(api).await?; if sarif { sarif::validate_subject(&detail, review_id)?; } @@ -1011,18 +1135,20 @@ async fn read_review( /// Prints the review, after waiting for it to finish when `wait` is set. async fn show( api: &Api, - review_id: Uuid, + address: impl Into
, wait: bool, output: &OutputArgs, format: OutputFormat, ) -> anyhow::Result { + let address = address.into(); + let review_id = address.review_id(); let deadline = if wait { Some(poll_deadline(output.timeout)?) } else { None }; let sarif = matches!(format, OutputFormat::Sarif); - let (raw, detail, state) = read_review(api, review_id, deadline, sarif).await?; + let (raw, detail, state) = read_review(api, address, deadline, sarif).await?; print_review(api, review_id, raw, &detail, state, format)?; match state { Some(Outcome::Completed) => return Ok(Verdict::Done), @@ -1084,32 +1210,40 @@ async fn ci_job( issuer: Option, event: &str, org: Option, + kind: CiKind, args: &CiReviewArgs, commit: &str, ) -> anyhow::Result { - let (api, request) = match (token, issuer) { - (None, Some(issuer)) => { + let (api, request) = match (token, issuer, kind) { + (None, Some(issuer), CiKind::PullRequest) => { let head = github_actions::pull_request_head(event, commit); let api = github_actions::api(http.clone(), &issuer, org, head).await?; let request = github_actions::ReviewRequest::for_event(event, http, issuer, commit); (api, request) } - (token, _) => (connect(http, token, org).await?, None), + // A deployment job names no pull-request head for the exchange to + // verify, and the review API has nothing for it to request. + (None, Some(issuer), CiKind::Deployment) => { + (github_actions::api(http, &issuer, org, None).await?, None) + } + (token, _, _) => (connect(http, token, org).await?, None), }; - ci_review(&api, args, commit, request.as_ref()).await + ci_review(&api, kind, args, commit, 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); -/// 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 the `kind` of review Proofline runs at `commit`, the pull +/// request's head or the deployed commit, 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, + kind: CiKind, args: &CiReviewArgs, commit: &str, mut request: Option<&github_actions::ReviewRequest>, @@ -1120,7 +1254,7 @@ async fn ci_review( let mut delay = FIRST_POLL_SECONDS; let review_id = loop { let found = latest(api, repository_id, commit, |item| { - item.kind == "PULL_REQUEST" && item.head_commit_sha.as_deref() == Some(commit) + item.kind == kind.api() && item.head_commit_sha.as_deref() == Some(commit) }) .await?; if let Some(id) = found { @@ -1128,8 +1262,15 @@ async fn ci_review( } let now = tokio::time::Instant::now(); if now >= deadline { + let noun = kind.noun(); + let hint = match kind { + CiKind::PullRequest => { + " Proofline reviews a commit once it is the head of an open pull request." + } + CiKind::Deployment => "", + }; say(&format!( - "No pull-request review of {name} has head commit {commit} after {} minutes. Proofline reviews a commit once it is the head of an open pull request.", + "No {noun} of {name} has head commit {commit} after {} minutes.{hint}", args.timeout )); return Ok(Verdict::Unavailable); @@ -1150,8 +1291,13 @@ async fn ci_review( )), } } + // The pull-request wording is unchanged from before `ci deployment`. + let waiting = match kind { + CiKind::PullRequest => "review", + CiKind::Deployment => kind.noun(), + }; say(&format!( - "No review of {name} at {commit} yet; checking again in {delay} seconds." + "No {waiting} of {name} at {commit} yet; checking again in {delay} seconds." )); let wake = if request.is_some() { deadline.min(request_at) @@ -1434,13 +1580,33 @@ 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), + let exchange = "POST /api/v1/ci/github-actions/credentials".to_owned(); + // Whether the job holds `PROOFLINE_TOKEN`, its event, the review it + // waits for, and the verdict. + for (stored_token, event, kind, verdict) in [ + (false, "pull_request", CiKind::PullRequest, Verdict::Done), + ( + true, + "pull_request", + CiKind::PullRequest, + Verdict::Unavailable, + ), + (false, "push", CiKind::PullRequest, Verdict::Unavailable), + // A deployment job never asks, whatever event started it. + ( + false, + "pull_request", + CiKind::Deployment, + Verdict::Unavailable, + ), + ( + false, + "deployment", + CiKind::Deployment, + Verdict::Unavailable, + ), ] { - let case = format!("token {stored_token}, {event}"); + let case = format!("token {stored_token}, {event}, {kind:?}"); let start = tokio::time::Instant::now(); let (origin, received) = console(start).await; let http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); @@ -1461,7 +1627,7 @@ 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 ended = ci_job(http, token, Some(issuer), event, org, kind, &args, HEAD) .await .unwrap(); assert_eq!(ended, verdict, "{case}"); @@ -1494,6 +1660,15 @@ mod tests { assert!(last >= Duration::from_secs(180), "{case}: {last:?}"); assert_eq!(issued, usize::from(!stored_token), "{case}"); } + if kind == CiKind::Deployment { + // Its exchange names no pull-request head to verify. + let exchanges: Vec<_> = received + .iter() + .filter(|(request, ..)| *request == exchange) + .map(|(.., query)| query.as_str()) + .collect(); + assert_eq!(exchanges, [""], "{case}"); + } } ticker.abort(); } diff --git a/tests/contract.rs b/tests/contract.rs index 1cd1a83..0b1cdc7 100644 --- a/tests/contract.rs +++ b/tests/contract.rs @@ -233,6 +233,10 @@ fn operations_the_cli_calls_exist() { for (method, path) in [ ("get", "/api/v1/organizations/{org_id}/reviews"), ("get", "/api/v1/organizations/{org_id}/reviews/{review_id}"), + ( + "get", + "/api/v1/organizations/{org_id}/reviews/deployments/{public_key}", + ), ("get", "/api/v1/organizations/{org_id}/repository-names"), ( "post", @@ -270,6 +274,13 @@ fn operations_the_cli_calls_exist() { resolve(&document, detail), schema(&document, "CustomerReviewDetail") ); + // `findings --deployment` reads the reply as it reads any review. + let deployment = &document["paths"]["/api/v1/organizations/{org_id}/reviews/deployments/{public_key}"] + ["get"]["responses"]["200"]["content"]["application/json"]["schema"]; + assert_eq!( + resolve(&document, deployment), + schema(&document, "CustomerReviewDetail") + ); let list = &document["paths"]["/api/v1/organizations/{org_id}/reviews"]["get"]["parameters"]; for name in ["repository", "search", "cursor", "limit"] { assert!( diff --git a/tests/deployment.rs b/tests/deployment.rs new file mode 100644 index 0000000..388655c --- /dev/null +++ b/tests/deployment.rs @@ -0,0 +1,368 @@ +//! Deployment reviews against a loopback stand-in for the console: reading +//! one by its public key with `findings --deployment`, and holding a deploy +//! job to the review of its commit with `ci deployment`. + +use std::sync::{Arc, Mutex}; + +use axum::extract::Path; +use axum::http::{HeaderMap, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use axum::{Json, Router}; +use serde_json::{Value, json}; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const TOKEN: &str = "pld_secretsecretsecret"; +const REPOSITORY: &str = "0190f3a0-0000-7000-8000-0000000000f0"; +const HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; + +/// A complete deployment review, and its public key. +const COMPLETE: &str = "0190f3a0-0000-7000-8000-0000000000d1"; +const COMPLETE_KEY: &str = "rev_0190f3a00000700080000000000000d1"; +/// A deployment review whose environment assessment did not finish. +const INCOMPLETE: &str = "0190f3a0-0000-7000-8000-0000000000d2"; +const INCOMPLETE_KEY: &str = "rev_0190f3a00000700080000000000000d2"; +/// A key the console answers with another review. +const SUBSTITUTED_KEY: &str = "rev_0190f3a00000700080000000000000d3"; +/// A key that addresses a pull-request review. +const PULL_REQUEST: &str = "0190f3a0-0000-7000-8000-0000000000d4"; +const PULL_REQUEST_KEY: &str = "rev_0190f3a00000700080000000000000d4"; +/// A key the console does not know. +const UNKNOWN_KEY: &str = "rev_0190f3a00000700080000000000000d5"; + +/// Every request the console received, as `METHOD path`. +type Requests = Arc>>; + +fn review(id: &str, kind: &str, assessment: &str, open: Option<[u64; 2]>) -> Value { + let findings = match open { + Some([count, _]) if count > 0 => json!([{ + "id": "0190f3a0-0000-7000-8000-0000000000e1", + "severity": "SERIOUS", + "risk_domain": "iam_permissions", + "claim": "The task role cannot read the new queue.", + "impact": "workers fail at start", + "lifecycle_state": "NEW", + "evidence_refs": [], + }]), + _ => json!([]), + }; + json!({ + "id": id, + "kind": kind, + "status": "COMPLETED", + "head_commit_sha": HEAD, + "repository_full_name": "acme/app", + "assessment_count": 1, + "open_items": open.map(|[open_findings, serious_findings]| json!({ + "open_findings": open_findings, + "serious_findings": serious_findings, + "accepted_risks": 0, + "not_assessed": [], + })), + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-0000000000e2", + "environment_display_name": "production", + "status": assessment, + "findings": findings, + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + }], + }) +} + +/// A console that serves deployment reviews by public key, and lists one +/// review of `HEAD` in `acme/app` as `listed` whose detail counts `open` as +/// its open and serious findings. +async fn console(listed: &'static str, open: Option<[u64; 2]>) -> (String, Requests) { + let requests = Requests::default(); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/deployments/{{key}}"), + get(|Path(key): Path, headers: HeaderMap| async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + let document = match key.as_str() { + COMPLETE_KEY => review(COMPLETE, "DEPLOYMENT", "COMPLETED", Some([0, 0])), + INCOMPLETE_KEY => review(INCOMPLETE, "DEPLOYMENT", "INCOMPLETE", None), + SUBSTITUTED_KEY => review(COMPLETE, "DEPLOYMENT", "COMPLETED", None), + PULL_REQUEST_KEY => review(PULL_REQUEST, "PULL_REQUEST", "COMPLETED", None), + _ => return problem(StatusCode::NOT_FOUND, "No such deployment review."), + }; + Json(document).into_response() + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ "repositories": [{ "id": REPOSITORY, "full_name": "acme/app" }] })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(move || async move { + Json(json!({ + "items": [{ + "id": COMPLETE, + "kind": listed, + "status": "COMPLETED", + "created_at": "2026-10-01T00:00:00Z", + "head_commit_sha": HEAD, + "pull_request_number": null, + "repository_id": REPOSITORY, + "run_number": null, + }], + "next_cursor": null, + "truncated": false, + "filters": { "repositories": [], "environments": [], "authors": [] }, + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{COMPLETE}"), + get(move || async move { Json(review(COMPLETE, "DEPLOYMENT", "COMPLETED", open)) }), + ); + let observed = Arc::clone(&requests); + let app = app.layer(axum::middleware::from_fn( + move |request: axum::extract::Request, next: axum::middleware::Next| { + let observed = Arc::clone(&observed); + async move { + observed.lock().unwrap().push(format!( + "{} {}", + request.method(), + request.uri().path() + )); + next.run(request).await + } + }, + )); + 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, requests) +} + +fn problem(status: StatusCode, detail: &str) -> Response { + ( + status, + [(header::CONTENT_TYPE, "application/problem+json")], + Json(json!({ "title": "Not found", "status": status.as_u16(), "detail": detail })), + ) + .into_response() +} + +async fn cli(origin: &str, args: &[&str]) -> std::process::Output { + let directory = tempfile::tempdir().unwrap(); + tokio::time::timeout( + std::time::Duration::from_secs(15), + tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["--base-url", origin, "--org", ORG]) + .args(args) + .env("PROOFLINE_TOKEN", TOKEN) + .env("COMMIT_SHA", HEAD) + .env_remove("GITHUB_SHA") + .env_remove("ACTIONS_ID_TOKEN_REQUEST_URL") + .env("PATH", "") + .current_dir(directory.path()) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap() +} + +fn deployment_path(key: &str) -> String { + format!("GET /api/v1/organizations/{ORG}/reviews/deployments/{key}") +} + +#[tokio::test] +async fn findings_reads_a_deployment_review_by_its_public_key() { + let (origin, requests) = console("DEPLOYMENT", None).await; + + let output = cli(&origin, &["findings", "--deployment", COMPLETE_KEY]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{stderr}"); + let text = String::from_utf8_lossy(&output.stdout); + assert!( + text.starts_with("acme/app at 89abcdef0123: COMPLETED\n"), + "{text}" + ); + assert!( + text.contains("production: COMPLETED, no findings"), + "{text}" + ); + // The link is the review's console page, addressed by its identifier. + assert!( + text.contains(&format!("/orgs/by-id/{ORG}/reviews/{COMPLETE}")), + "{text}" + ); + + let output = cli( + &origin, + &["findings", "--deployment", COMPLETE_KEY, "--json"], + ) + .await; + assert_eq!(output.status.code(), Some(0)); + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["outcome"], "COMPLETED"); + assert_eq!(document["review"]["id"], COMPLETE); + assert_eq!(document["review"]["kind"], "DEPLOYMENT"); + + // One read each, through the deployment operation and no other. + assert_eq!( + *requests.lock().unwrap(), + [deployment_path(COMPLETE_KEY), deployment_path(COMPLETE_KEY)] + ); + assert!(!stderr.contains(TOKEN)); +} + +#[tokio::test] +async fn an_incomplete_deployment_review_is_not_success() { + let (origin, _) = console("DEPLOYMENT", None).await; + for wait in [false, true] { + let mut args = vec!["findings", "--deployment", INCOMPLETE_KEY]; + if wait { + args.extend(["--wait", "--timeout", "0"]); + } + let output = cli(&origin, &args).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "wait={wait}: {stderr}"); + assert!(stderr.contains("incomplete"), "{stderr}"); + } +} + +#[tokio::test] +async fn a_key_is_held_to_the_deployment_review_it_names() { + let (origin, requests) = console("DEPLOYMENT", None).await; + for (key, expected) in [ + (SUBSTITUTED_KEY, "but the server returned review"), + (PULL_REQUEST_KEY, "has kind PULL_REQUEST, not DEPLOYMENT"), + (UNKNOWN_KEY, "HTTP 404: No such deployment review."), + ] { + let output = cli(&origin, &["findings", "--deployment", key, "--json"]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(1), "{key}: {stderr}"); + assert!(stderr.contains(expected), "{key}: {stderr}"); + // Nothing is printed as the named deployment's result. + assert!(output.stdout.is_empty(), "{key}"); + } + assert_eq!(requests.lock().unwrap().len(), 3); +} + +#[tokio::test] +async fn a_malformed_key_or_a_second_selector_is_refused_before_any_request() { + let (origin, requests) = console("DEPLOYMENT", None).await; + let digits = COMPLETE_KEY.strip_prefix("rev_").unwrap(); + let uppercase = format!("rev_{}", digits.to_ascii_uppercase()); + for args in [ + vec!["findings", "--deployment", COMPLETE], + vec!["findings", "--deployment", digits], + vec!["findings", "--deployment", uppercase.as_str()], + vec!["findings", "--deployment", "rev_../../reviews"], + vec![ + "findings", + "--deployment", + COMPLETE_KEY, + "--review", + COMPLETE, + ], + vec!["findings", "--deployment", COMPLETE_KEY, "--pr", "7"], + vec!["findings", "--deployment", COMPLETE_KEY, "--head", HEAD], + // SARIF is a projection of a retained pull-request review. + vec!["findings", "--deployment", COMPLETE_KEY, "--sarif"], + ] { + let output = cli(&origin, &args).await; + assert_eq!(output.status.code(), Some(1), "{args:?}"); + assert!(output.stdout.is_empty(), "{args:?}"); + } + assert!(requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn ci_deployment_waits_for_the_deployment_review_of_the_commit() { + // What the console lists at the commit, its open and serious counts, the + // `--fail-on` threshold, and the exit code. + for (listed, open, fail_on, code) in [ + ("DEPLOYMENT", Some([0, 0]), None, 0), + ("DEPLOYMENT", Some([1, 1]), None, 0), + ("DEPLOYMENT", Some([1, 1]), Some("serious"), 3), + ("DEPLOYMENT", Some([1, 0]), Some("serious"), 0), + ("DEPLOYMENT", Some([1, 0]), Some("warning"), 3), + // A threshold that cannot be measured is never a pass. + ("DEPLOYMENT", None, Some("warning"), 4), + // A pull-request review of the same commit is not the deployment's. + ("PULL_REQUEST", Some([0, 0]), None, 4), + ] { + let (origin, requests) = console(listed, open).await; + let mut args = vec![ + "ci", + "deployment", + "--repo", + "acme/app", + "--timeout", + "0", + "--json", + ]; + if let Some(threshold) = fail_on { + args.extend(["--fail-on", threshold]); + } + let output = cli(&origin, &args).await; + let stderr = String::from_utf8_lossy(&output.stderr); + let case = format!("{listed} {open:?} {fail_on:?}"); + assert_eq!(output.status.code(), Some(code), "{case}: {stderr}"); + assert!(!stderr.contains(TOKEN)); + let requests = requests.lock().unwrap(); + // A deployment job reads; it never requests or stops a review. + assert!( + requests.iter().all(|request| request.starts_with("GET ")), + "{requests:?}" + ); + if listed == "DEPLOYMENT" { + let document: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(document["review"]["id"], COMPLETE, "{case}"); + assert_eq!(document["review"]["kind"], "DEPLOYMENT", "{case}"); + } else { + assert!(output.stdout.is_empty(), "{case}"); + assert!( + stderr.contains("No deployment review of acme/app"), + "{case}: {stderr}" + ); + } + } +} + +#[tokio::test] +async fn ci_deployment_takes_a_full_commit_and_writes_no_sarif() { + let (origin, requests) = console("DEPLOYMENT", Some([0, 0])).await; + for args in [ + // Only a full SHA names the deployed commit, never a ref. + vec!["ci", "deployment", "--repo", "acme/app", "--commit", "main"], + vec![ + "ci", + "deployment", + "--repo", + "acme/app", + "--sarif", + "out.sarif", + ], + ] { + let output = cli(&origin, &args).await; + assert_eq!(output.status.code(), Some(1), "{args:?}"); + } + assert!(requests.lock().unwrap().is_empty()); + + let other = "0123456789abcdef0123456789abcdef01234567"; + let args = [ + "ci", + "deployment", + "--repo", + "acme/app", + "--timeout", + "0", + "--commit", + other, + ]; + let output = cli(&origin, &args).await; + let stderr = String::from_utf8_lossy(&output.stderr); + // The listed review is of another commit, so there is no answer yet. + assert_eq!(output.status.code(), Some(4), "{stderr}"); + assert!(stderr.contains(other), "{stderr}"); +}