From 630305a61500f547303762d0a2212f1565a836da Mon Sep 17 00:00:00 2001 From: Tran Hoang Tu Date: Tue, 1 Dec 2026 22:10:46 +0700 Subject: [PATCH] Add ci deploy --annotations for GitHub Actions workflow commands Add an opt-in --annotations flag to `proofline ci deploy` that writes `::error` and `::warning` workflow commands on stderr for regressed and unestablished deploy checks while leaving stdout JSON untouched. Shared escaping and job-level command formatting live in `src/annotations.rs`, so values from server responses and GitHub metadata are sanitized through `text::terminal_safe` and escaped like `@actions/core` without duplication. Clean `HEALTHY` runs with no gaps and transport/auth failures emit no deploy annotations. --- README.md | 2 + src/annotations.rs | 110 +++++++-- src/deploy.rs | 605 ++++++++++++++++++++++++++++++++++++++++++--- tests/http.rs | 272 ++++++++++++++++++++ 4 files changed, 937 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index 6a124c3..177fda3 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,8 @@ For a CodePipeline execution or Amplify job, run `proofline ci deploy --commit S `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. +In GitHub Actions, pass `--annotations` to `proofline ci deploy` to emit workflow annotations on stderr on every GitHub plan: `::error` for each deploy that failed or recorded `REGRESSED`, and `::warning` when a check is not established or no matching deploy is recorded. When no regression is observed (`HEALTHY` with no gap), no annotation is emitted, and `--json` output on stdout stays unchanged. + ## Scans Proofline cannot analyze a scan's files yet. An accepted scan reads the repository's files at its commit but analyzes none of them, so a scan of a repository with files ends `FAILED` or `INCOMPLETE` with no findings, and the command exits 2. That empty finding list says nothing about the code. diff --git a/src/annotations.rs b/src/annotations.rs index bf62f73..a53199d 100644 --- a/src/annotations.rs +++ b/src/annotations.rs @@ -1,8 +1,9 @@ -//! Findings as GitHub Actions workflow commands. The runner reads each -//! `::error file=...,line=...::message` line from a step's output and shows it -//! on the pull request's diff, on every GitHub plan. Findings quote reviewer -//! output and repository content, so every value is escaped: a newline in a -//! claim must never start a second command. +//! Findings and deploy checks as GitHub Actions workflow commands. The runner +//! reads each `::error ...::message` or `::warning ...::message` line from a +//! step's output and shows it on the pull request's diff or run summary, on +//! every GitHub plan. Values quote untrusted reviewer, server, and repository +//! content, so every value is escaped: a newline must never start a second +//! command. use std::io::Write; @@ -10,6 +11,24 @@ use crate::model::{Finding, ReviewDetail}; use crate::severity::Severity; use crate::{outcome, sarif, text}; +/// Severity of a GitHub Actions workflow annotation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Level { + Error, + Warning, + Notice, +} + +impl Level { + const fn as_str(self) -> &'static str { + match self { + Self::Error => "error", + Self::Warning => "warning", + Self::Notice => "notice", + } + } +} + /// Writes one annotation per finding that is not resolved. A finding with a /// verified location at the review's head is placed on that file and line; /// any other finding is annotated on the job without a location. @@ -28,6 +47,18 @@ pub(super) fn write(detail: &ReviewDetail, out: &mut impl Write) -> std::io::Res Ok(()) } +/// Writes a job-level workflow annotation (`::error`, `::warning`, or +/// `::notice` with `title=...`) with both the title property and message +/// escaped. +pub(crate) fn write_job( + out: &mut impl Write, + level: Level, + title: &str, + message: &str, +) -> std::io::Result<()> { + write_command(out, level, None, title, message) +} + fn annotate( out: &mut impl Write, finding: &Finding, @@ -38,29 +69,40 @@ fn annotate( return Ok(()); } // A severity this CLI does not know yet is still shown, as a notice. - let command = match Severity::parse(&finding.severity) { - Some(Severity::Serious) => "error", - Some(Severity::Warning) => "warning", - None => "notice", + let level = match Severity::parse(&finding.severity) { + Some(Severity::Serious) => Level::Error, + Some(Severity::Warning) => Level::Warning, + None => Level::Notice, }; - let mut properties = Vec::new(); - if let Some((path, start, end)) = finding + let location = finding .evidence_refs .iter() - .find_map(|reference| sarif::location(reference, head)) - { + .find_map(|reference| sarif::location(reference, head)); + let title = format!("Proofline {lane}: {}", finding.risk_domain); + let message = format!("{}\n\n{}", finding.claim, finding.impact); + write_command(out, level, location, &title, &message) +} + +fn write_command( + out: &mut impl Write, + level: Level, + location: Option<(&str, u32, u32)>, + title: &str, + message: &str, +) -> std::io::Result<()> { + let mut properties = Vec::new(); + if let Some((path, start, end)) = location { properties.push(format!("file={}", escape_property(path))); properties.push(format!("line={start}")); properties.push(format!("endLine={end}")); } - let title = format!("Proofline {lane}: {}", finding.risk_domain); - properties.push(format!("title={}", escape_property(&title))); - let message = format!("{}\n\n{}", finding.claim, finding.impact); + properties.push(format!("title={}", escape_property(title))); writeln!( out, - "::{command} {}::{}", + "::{} {}::{}", + level.as_str(), properties.join(","), - escape_data(&message) + escape_data(message) ) } @@ -68,14 +110,14 @@ fn annotate( /// Control characters other than a newline or a tab, `\r` among them, are /// replaced first, so nothing reaches the log that the runner or a terminal /// would interpret. -fn escape_data(value: &str) -> String { +pub(crate) fn escape_data(value: &str) -> String { text::terminal_safe(value) .replace('%', "%25") .replace('\n', "%0A") } /// A property value of a workflow command, where `:` and `,` also delimit. -fn escape_property(value: &str) -> String { +pub(crate) fn escape_property(value: &str) -> String { escape_data(value).replace(':', "%3A").replace(',', "%2C") } @@ -93,4 +135,32 @@ mod tests { assert_eq!(escape_property("a:b,c%\nd"), "a%3Ab%2Cc%25%0Ad"); assert_eq!(escape_data("ok\u{1b}[2J"), "ok\u{FFFD}[2J"); } + + #[test] + fn write_job_escapes_title_and_message_onto_one_line() { + let mut out = Vec::new(); + write_job( + &mut out, + Level::Error, + "Proofline deploy: prod:web,100%\r\n\u{1b}[31m", + "50% drop\n::add-mask::secret\u{202E}", + ) + .unwrap(); + write_job( + &mut out, + Level::Warning, + "Proofline deploy: LANDING", + "Not established.", + ) + .unwrap(); + let written = String::from_utf8(out).unwrap(); + let lines: Vec<&str> = written.lines().collect(); + assert_eq!( + lines, + [ + "::error title=Proofline deploy%3A prod%3Aweb%2C100%25\u{FFFD}%0A\u{FFFD}[31m::50%25 drop%0A::add-mask::secret\u{FFFD}", + "::warning title=Proofline deploy%3A LANDING::Not established.", + ] + ); + } } diff --git a/src/deploy.rs b/src/deploy.rs index 4102ae8..db3fdab 100644 --- a/src/deploy.rs +++ b/src/deploy.rs @@ -11,6 +11,7 @@ use anyhow::bail; use clap::{Args, ValueEnum}; use uuid::Uuid; +use crate::annotations; use crate::api::Api; use crate::github_actions::ProducingRun; use crate::model::{CommitDeploy, CommitDeployRollback, RollbackDeploy}; @@ -109,6 +110,12 @@ pub(crate) struct CiDeployArgs { /// check is due, and at least 30. `--until 1d` needs an explicit value. #[arg(long, value_name = "MINUTES")] timeout: Option, + /// Also print regressed or unestablished deploy checks as GitHub Actions + /// workflow commands (`::error` or `::warning`) on `stderr`, so they + /// appear on the run summary on every GitHub plan while keeping `--json` + /// output on `stdout` untouched. + #[arg(long)] + annotations: bool, /// Print the route's response as JSON instead of text. #[arg(long)] json: bool, @@ -358,7 +365,15 @@ pub(crate) async fn wait( commit: &str, reader_run: Option, ) -> anyhow::Result { - wait_with_output(api, args, commit, reader_run, &mut std::io::stdout()).await + wait_with_output( + api, + args, + commit, + reader_run, + &mut std::io::stdout(), + &mut std::io::stderr(), + ) + .await } async fn wait_with_output( @@ -367,6 +382,7 @@ async fn wait_with_output( commit: &str, reader_run: Option, stdout: &mut impl Write, + stderr: &mut impl Write, ) -> anyhow::Result { let started = tokio::time::Instant::now(); let started_unix = i64::try_from(crate::device::now()).unwrap_or(i64::MAX); @@ -438,9 +454,18 @@ async fn wait_with_output( None => {} } let Some((raw, read)) = last.as_ref() else { - say(&format!( + let message = format!( "Proofline did not answer a verification read for {name} at {commit} within {timeout_minutes} minutes. The result is not established." - )); + ); + if args.annotations { + annotations::write_job( + stderr, + annotations::Level::Warning, + &format!("Proofline deploy: {checkpoint}"), + &message, + )?; + } + say(&message); return Ok(Verdict::NotComplete); }; let selected: Vec<&CommitDeploy> = read @@ -488,11 +513,26 @@ async fn wait_with_output( .saturating_duration_since(started) .as_secs() .div_ceil(60); - let ended = match (ended_run, args.run) { - (Some((conclusion, _)), Some(run)) => { + let followed_unsuccessful = + ended_run.and_then(|(conclusion, _)| args.run.map(|run| (run, conclusion))); + if args.annotations { + write_annotations( + stderr, + verdict, + &judged, + read.deploys.len(), + followed_unsuccessful, + &name, + commit, + args.until, + waited, + )?; + } + let ended = match followed_unsuccessful { + Some((run, conclusion)) => { no_deploy_from_run(run, conclusion, &name, commit, waited) } - _ => ending( + None => ending( verdict, &judged, read.deploys.len(), @@ -567,27 +607,28 @@ fn count(deploys: usize) -> String { } } -/// The deploy's environment, task, run and attempts, as its lines start. -fn label(deploy: &CommitDeploy) -> String { +/// The deploy's environment, task, run and attempts without terminal folding. +fn deploy_label(deploy: &CommitDeploy) -> String { if let (Some(provider), Some(run)) = (&deploy.aws_provider, &deploy.aws_run_id) { let name = match provider.as_str() { "AWS_CODEPIPELINE" => "CodePipeline", "AWS_AMPLIFY" => "Amplify", other => other, }; - return format!("{} run {}", text::one_line(name), text::one_line(run)); + return format!("{name} run {run}"); } - let mut label = vec![ + let mut parts = vec![ deploy .github_environment .as_deref() - .map_or_else(|| "(no environment)".to_owned(), text::one_line), + .unwrap_or("(no environment)") + .to_owned(), ]; if let Some(task) = &deploy.deployment_task { - label.push(text::one_line(task)); + parts.push(task.clone()); } if let Some(run) = deploy.workflow_run_id { - label.push(format!("run {run}")); + parts.push(format!("run {run}")); } if !deploy.workflow_run_attempts.is_empty() { let attempts: Vec = deploy @@ -595,9 +636,14 @@ fn label(deploy: &CommitDeploy) -> String { .iter() .map(i64::to_string) .collect(); - label.push(format!("attempt {}", attempts.join(","))); + parts.push(format!("attempt {}", attempts.join(","))); } - label.join(" ") + parts.join(" ") +} + +/// The deploy's environment, task, run and attempts, as its lines start. +fn label(deploy: &CommitDeploy) -> String { + text::one_line(&deploy_label(deploy)) } /// The later checkpoints than `until` that recorded `REGRESSED`. Any of them @@ -608,6 +654,41 @@ fn later_regressions(deploy: &CommitDeploy, until: Until) -> impl Iterator impl Iterator + '_ { + Until::ALL + .into_iter() + .filter(move |checkpoint| *checkpoint <= until) + .chain(later_regressions(deploy, until)) +} + +fn deploy_gaps(deploy: &CommitDeploy, until: Until) -> Vec<&str> { + let mut gaps = Vec::new(); + for checkpoint in checkpoints_in_scope(deploy, until) { + for gap in result_and_gaps(deploy, checkpoint).1 { + if !gaps.contains(&gap.as_str()) { + gaps.push(gap.as_str()); + } + } + } + gaps +} + +fn regressed_checkpoints(deploy: &CommitDeploy) -> Vec<&str> { + let mut regressed: Vec<&str> = Until::ALL + .into_iter() + .filter(|checkpoint| result_and_gaps(deploy, *checkpoint).0 == Some("REGRESSED")) + .map(Until::api_name) + .collect(); + for check in &deploy.checkpoints { + if check.result.as_deref() == Some("REGRESSED") + && !regressed.contains(&check.checkpoint.as_str()) + { + regressed.push(check.checkpoint.as_str()); + } + } + regressed +} + /// One line for each check of `deploy` through `until`, and for each later /// check that recorded `REGRESSED`: the deploy, the checkpoint, its result and /// gap codes, and the deploy's page. A rollback first gets one line naming the @@ -630,11 +711,7 @@ fn write_lines(out: &mut impl Write, deploy: &CommitDeploy, until: Until) -> std "{label}: rolled back; the newest check found an earlier deploy serving again" )?; } - let printed = Until::ALL - .into_iter() - .filter(|checkpoint| *checkpoint <= until) - .chain(later_regressions(deploy, until)); - for checkpoint in printed { + for checkpoint in checkpoints_in_scope(deploy, until) { let (result, gaps) = result_and_gaps(deploy, checkpoint); let result = result.map_or_else(|| "NOT_RECORDED".to_owned(), text::one_line); let gaps = if gaps.is_empty() { @@ -654,27 +731,200 @@ fn write_lines(out: &mut impl Write, deploy: &CommitDeploy, until: Until) -> std Ok(()) } -/// `rollback; restores PAGE; rolls back PAGE, PAGE`, each deploy named by its -/// page, else by its landing. -fn rollback_line(rollback: &CommitDeployRollback) -> String { - let named = |deploy: &RollbackDeploy| { +fn deploy_rollback(rollback: &CommitDeployRollback) -> String { + fn named(deploy: &RollbackDeploy) -> &str { deploy .deploy_url .as_deref() .or(deploy.landed_at.as_deref()) - .map_or_else(|| "(no page)".to_owned(), text::one_line) - }; + .unwrap_or("(no page)") + } let mut parts = vec!["rollback".to_owned()]; if let Some(restores) = &rollback.restores { parts.push(format!("restores {}", named(restores))); } if !rollback.rolls_back.is_empty() { - let rolled_back: Vec = rollback.rolls_back.iter().map(named).collect(); + let rolled_back: Vec<&str> = rollback.rolls_back.iter().map(named).collect(); parts.push(format!("rolls back {}", rolled_back.join(", "))); } parts.join("; ") } +/// `rollback; restores PAGE; rolls back PAGE, PAGE`, each deploy named by its +/// page, else by its landing. +fn rollback_line(rollback: &CommitDeployRollback) -> String { + text::one_line(&deploy_rollback(rollback)) +} + +fn append_deploy_details(parts: &mut Vec, deploy: &CommitDeploy, until: Until) { + if let Some(rollback) = &deploy.rollback { + parts.push(deploy_rollback(rollback)); + } + if deploy.rolled_back { + parts + .push("rolled back; the newest check found an earlier deploy serving again".to_owned()); + } + let gaps = deploy_gaps(deploy, until); + if !gaps.is_empty() { + parts.push(format!("gaps {}", gaps.join(","))); + } + if let Some(url) = &deploy.deploy_url { + parts.push(url.clone()); + } +} + +fn write_annotations( + out: &mut impl Write, + verdict: Verdict, + judged: &[(&CommitDeploy, Reading)], + recorded: usize, + followed_unsuccessful: Option<(i64, &str)>, + name: &str, + commit: &str, + until: Until, + minutes: u64, +) -> std::io::Result<()> { + match verdict { + Verdict::Regressed => { + for (deploy, reading) in judged { + if *reading != Reading::Regressed { + continue; + } + let deploy_name = deploy_label(deploy); + let title = format!("Proofline deploy: {deploy_name}"); + let message = regressed_annotation_message(deploy, &deploy_name, until); + annotations::write_job(out, annotations::Level::Error, &title, &message)?; + } + } + Verdict::NotComplete => { + if judged.is_empty() { + let title = format!("Proofline deploy: {}", until.api_name()); + let message = match followed_unsuccessful { + Some((run, conclusion)) => format!( + "Run {run} concluded {conclusion} and recorded no deploy of {name} at {commit} that this job selects; Proofline waited {minutes} minutes for one. The result is not established." + ), + None if recorded > 0 => format!( + "Proofline recorded {} of {name} at {commit}, and none matches --environment-id, --aws-run, --environment, --task, --deployment, --run or --attempt after {minutes} minutes. The result is not established.", + count(recorded) + ), + None => format!( + "No deploy of {name} at {commit} was recorded after {minutes} minutes. The result is not established." + ), + }; + annotations::write_job(out, annotations::Level::Warning, &title, &message)?; + } else { + for (deploy, reading) in judged { + if *reading == Reading::NoRegression { + continue; + } + let deploy_name = deploy_label(deploy); + let title = format!("Proofline deploy: {deploy_name}"); + let message = not_established_annotation_message( + deploy, + *reading, + &deploy_name, + until, + minutes, + ); + annotations::write_job(out, annotations::Level::Warning, &title, &message)?; + } + } + } + Verdict::Done | Verdict::Unavailable | Verdict::ThresholdReached | Verdict::Blocked => {} + } + Ok(()) +} + +fn regressed_annotation_message(deploy: &CommitDeploy, deploy_name: &str, until: Until) -> String { + let regressed = regressed_checkpoints(deploy); + let summary = match (deploy.state == "FAILED", regressed.is_empty()) { + (true, true) => format!("{deploy_name} failed; state {}", deploy.state), + (true, false) => format!( + "{deploy_name} failed and recorded REGRESSED at {}; state {}", + regressed.join(", "), + deploy.state + ), + (false, false) => format!( + "{deploy_name} recorded REGRESSED at {}; state {}", + regressed.join(", "), + deploy.state + ), + (false, true) => format!("{deploy_name} recorded REGRESSED; state {}", deploy.state), + }; + let mut parts = vec![summary]; + append_deploy_details(&mut parts, deploy, until); + parts.join("; ") +} + +fn not_established_annotation_message( + deploy: &CommitDeploy, + reading: Reading, + deploy_name: &str, + until: Until, + minutes: u64, +) -> String { + let checkpoint = until.api_name(); + let state = &deploy.state; + let summary = match reading { + Reading::Waiting => format!( + "{deploy_name}: the {checkpoint} check was not recorded after {minutes} minutes; state {state}; the result is not established" + ), + Reading::Superseded => { + let superseded_at: Vec<&str> = Until::ALL + .into_iter() + .filter(|check| { + *check <= until && result_and_gaps(deploy, *check).0 == Some("SUPERSEDED") + }) + .map(Until::api_name) + .collect(); + format!( + "{deploy_name}: a later deploy replaced this deploy before the {checkpoint} check ({} SUPERSEDED); state {state}; the result is not established", + superseded_at.join(", ") + ) + } + Reading::Unverified => format!( + "{deploy_name}: Proofline has no deploy checks for this deploy; state {state}; the result is not established" + ), + Reading::Inactive => format!( + "{deploy_name}: deploy never landed, so the {checkpoint} check will not be recorded; state {state}; the result is not established" + ), + Reading::Ended => format!( + "{deploy_name}: deploy checks ended without recording the {checkpoint} check; state {state}; the result is not established" + ), + Reading::UnknownState => format!( + "{deploy_name}: reads unknown state {state}; checks are not read as no regression and the result is not established" + ), + Reading::NotEstablished => { + let non_healthy: Vec = Until::ALL + .into_iter() + .filter(|check| *check <= until) + .filter_map(|check| { + let result = result_and_gaps(deploy, check).0; + (result != Some("HEALTHY")).then(|| { + format!("{} {}", check.api_name(), result.unwrap_or("NOT_RECORDED")) + }) + }) + .collect(); + if non_healthy.is_empty() { + format!( + "{deploy_name}: check through {checkpoint} named a gap; state {state}; the result is not established" + ) + } else { + format!( + "{deploy_name}: check through {checkpoint} did not record HEALTHY ({}); state {state}; the result is not established", + non_healthy.join(", ") + ) + } + } + Reading::Regressed | Reading::NoRegression => { + format!("{deploy_name}: state {state}; the result is not established") + } + }; + let mut parts = vec![summary]; + append_deploy_details(&mut parts, deploy, until); + parts.join("; ") +} + /// The line the job ends with. When every deploy that is not established /// never landed, was replaced before the check, has no checks, or ended its /// checks without the named one, it says so and names their pages. @@ -757,10 +1007,9 @@ fn causes(judged: &[(&CommitDeploy, Reading)]) -> String { .iter() .filter(|(_, reading)| *reading == Reading::Regressed) .map(|(deploy, _)| { - let regressed: Vec<&str> = Until::ALL + let regressed: Vec = regressed_checkpoints(deploy) .into_iter() - .filter(|checkpoint| result_and_gaps(deploy, *checkpoint).0 == Some("REGRESSED")) - .map(Until::api_name) + .map(text::one_line) .collect(); let cause = match (deploy.state == "FAILED", regressed.is_empty()) { (true, true) => "failed".to_owned(), @@ -960,6 +1209,17 @@ mod tests { answers: Vec<(u16, Value)>, last_delay: Duration, ) -> (anyhow::Result, usize, Duration, Vec) { + let (verdict, reads, took, stdout, _) = + run_args_with_streams(reader_run, args, answers, last_delay).await; + (verdict, reads, took, stdout) + } + + async fn run_args_with_streams( + reader_run: Option, + args: &CiDeployArgs, + answers: Vec<(u16, Value)>, + last_delay: Duration, + ) -> (anyhow::Result, usize, Duration, Vec, Vec) { // A paused clock jumps to the next timer whenever the runtime waits, // even on a loopback socket about to answer, which would fire the // client's request timeout. A 10 ms ticker bounds each jump. @@ -974,11 +1234,13 @@ mod tests { let api = Api::new(http, SecretString::from("plp_stored"), organization); let started = tokio::time::Instant::now(); let mut stdout = Vec::new(); - let verdict = wait_with_output(&api, args, COMMIT, reader_run, &mut stdout).await; + let mut stderr = Vec::new(); + let verdict = + wait_with_output(&api, args, COMMIT, reader_run, &mut stdout, &mut stderr).await; let took = started.elapsed(); ticker.abort(); let reads = *reads.lock().unwrap(); - (verdict, reads, took, stdout) + (verdict, reads, took, stdout, stderr) } /// Each exit code from a stub console: 0 for a healthy landing with no @@ -2010,4 +2272,283 @@ mod tests { "--attempt names an attempt of --run" ); } + + #[tokio::test(start_paused = true)] + async fn annotations_report_regressions_and_unestablished_checks_as_escaped_commands() { + async fn run_annotated( + args: &CiDeployArgs, + answers: Vec<(u16, Value)>, + delay: Duration, + ) -> (anyhow::Result, usize, Duration, Vec, Vec) { + run_args_with_streams(None, args, answers, delay).await + } + let commands = |stderr: &[u8]| -> Vec { + String::from_utf8(stderr.to_vec()) + .unwrap() + .lines() + .map(str::to_owned) + .collect() + }; + + // Opt-in: without `--annotations`, even a regression emits nothing. + let regressed_plain = recorded(&[deploy("deploy", &[1], &["REGRESSED"], &[])]); + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--timeout", "0"]), + vec![regressed_plain], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::Regressed); + assert!(stderr.is_empty()); + + // `Verdict::Done` (`HEALTHY`, no gaps, or gap only on a later checkpoint + // than `--until`) emits zero annotations even with `--annotations`. + let healthy = deploy("deploy", &[1], &["HEALTHY"], &[]); + let mut later_gap = healthy.clone(); + for checkpoint in later_gap["checkpoints"].as_array_mut().unwrap() { + checkpoint["gaps"] = json!([]); + } + later_gap["checkpoints"][1]["gaps"] = json!(["SIGNAL_NO_DATA"]); + for answer in [ + recorded(std::slice::from_ref(&healthy)), + recorded(&[later_gap]), + ] { + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--timeout", "0"]), + vec![answer], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::Done); + assert!(stderr.is_empty()); + } + + // `Verdict::Regressed`: emits one `::error` per regressed deploy (including + // later regressions after `--until`, failed deploys, AWS runs, rollback + // info, gaps, and `deploy_url`), skips healthy/waiting siblings, keeps + // `--json` on stdout valid, and escapes injection payloads. + let mut injected_later = deploy( + "deploy:api,100%\n::add-mask::secret", + &[1], + &["HEALTHY", "HEALTHY", "REGRESSED"], + &["METRIC_SPIKE:100%\r\n::error title=forged::bad"], + ); + injected_later["github_environment"] = json!("prod:eu\u{1b}[2J\u{202E}"); + injected_later["state"] = json!("INCOMPLETE"); + injected_later["deploy_url"] = + json!("https://console.proofline.example/deploys/2?a=1%2&b=\n::notice::x"); + injected_later["rollback"] = json!({ + "restores": { "deploy_url": "https://console.proofline.example/deploys/0" }, + "rolls_back": [{ "deploy_url": "https://console.proofline.example/deploys/1" }], + }); + injected_later["rolled_back"] = json!(true); + + let mut failed_only = deploy("deploy:worker", &[2], &["HEALTHY"], &[]); + failed_only["state"] = json!("FAILED"); + failed_only["deploy_url"] = json!("https://console.proofline.example/deploys/3"); + + let aws_regressed = json!({ + "environment_id": ORG, + "aws_provider": "AWS_AMPLIFY", + "aws_run_id": "job:42,100%\n::add-mask::aws", + "state": "FAILED", + "regressed": true, + "checkpoints": [{ + "checkpoint": "LANDING", + "result": "REGRESSED", + "due_at": "2026-11-21T00:00:00Z", + }], + "gaps": [], + "deploy_url": "https://console.proofline.example/deploys/4", + }); + + let waiting_sibling = deploy("deploy:docs", &[1], &[], &[]); + let regressed_payload = recorded(&[ + healthy.clone(), + waiting_sibling, + injected_later, + failed_only, + aws_regressed, + ]); + let (verdict, _, _, stdout, stderr) = run_annotated( + &args(&["--annotations", "--json", "--timeout", "0"]), + vec![regressed_payload.clone()], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::Regressed); + assert_eq!( + serde_json::from_slice::(&stdout).unwrap(), + regressed_payload.1 + ); + let lines = commands(&stderr); + assert_eq!(lines.len(), 3, "{lines:?}"); + assert!(lines.iter().all(|line| line.starts_with("::error title="))); + assert!( + lines[0].contains("title=Proofline deploy%3A prod%3Aeu\u{FFFD}[2J\u{FFFD} deploy%3Aapi%2C100%25%0A%3A%3Aadd-mask%3A%3Asecret run 7 attempt 1::"), + "{}", + lines[0] + ); + assert!( + lines[0].contains("recorded REGRESSED at HOUR_1; state INCOMPLETE; rollback; restores https://console.proofline.example/deploys/0; rolls back https://console.proofline.example/deploys/1; rolled back; the newest check found an earlier deploy serving again; gaps METRIC_SPIKE:100%25\u{FFFD}%0A::error title=forged::bad; https://console.proofline.example/deploys/2?a=1%252&b=%0A::notice::x"), + "{}", + lines[0] + ); + assert_eq!( + lines[1], + "::error title=Proofline deploy%3A production deploy%3Aworker run 7 attempt 2::production deploy:worker run 7 attempt 2 failed; state FAILED; https://console.proofline.example/deploys/3" + ); + assert_eq!( + lines[2], + "::error title=Proofline deploy%3A Amplify run job%3A42%2C100%25%0A%3A%3Aadd-mask%3A%3Aaws::Amplify run job:42,100%25%0A::add-mask::aws failed and recorded REGRESSED at LANDING; state FAILED; https://console.proofline.example/deploys/4" + ); + + // `Verdict::NotComplete`: every non-established reading gets a `::warning`, + // skipping healthy siblings. + let waiting = deploy("deploy:waiting", &[1], &[], &[]); + let superseded = deploy("deploy:superseded", &[1], &["SUPERSEDED"], &[]); + let mut unverified = deploy("deploy:unverified", &[1], &[], &[]); + unverified["state"] = json!("UNVERIFIED"); + let mut inactive = deploy("deploy:inactive", &[1], &[], &[]); + inactive["state"] = json!("INACTIVE"); + let mut ended = deploy("deploy:ended", &[1], &["HEALTHY"], &[]); + ended["state"] = json!("UNRECORDED"); + ended["verification_ended"] = json!(true); + let mut unknown = deploy("deploy:unknown", &[1], &["HEALTHY", "HEALTHY"], &[]); + unknown["state"] = json!("ROLLING_OUT\n::add-mask::x"); + let mut incomplete = deploy( + "deploy:incomplete", + &[1], + &["HEALTHY", "INCOMPLETE"], + &["SIGNAL_NO_DATA"], + ); + incomplete["state"] = json!("INCOMPLETE"); + let mut gap_only = deploy( + "deploy:gap", + &[1], + &["HEALTHY", "HEALTHY"], + &["RUNTIME_STALE"], + ); + gap_only["state"] = json!("INCOMPLETE"); + let healthy_20m = deploy("deploy:ok", &[1], &["HEALTHY", "HEALTHY"], &[]); + + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--until", "20m", "--timeout", "0"]), + vec![recorded(&[ + healthy_20m, + waiting, + superseded, + unverified, + inactive, + ended, + unknown, + incomplete, + gap_only, + ])], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::NotComplete); + let lines = commands(&stderr); + assert_eq!(lines.len(), 8, "{lines:?}"); + assert!( + lines + .iter() + .all(|line| line.starts_with("::warning title=Proofline deploy%3A ")) + ); + assert!( + lines[0].contains("was not recorded after 0 minutes") && lines[0].contains("deploys/1") + ); + assert!(lines[1].contains("LANDING SUPERSEDED")); + assert!(lines[2].contains("no deploy checks")); + assert!(lines[3].contains("never landed")); + assert!(lines[4].contains("deploy checks ended without recording the MINUTES_20 check")); + assert!(lines[5].contains("reads unknown state ROLLING_OUT%0A::add-mask::x")); + assert!( + lines[6].contains("MINUTES_20 INCOMPLETE") && lines[6].contains("gaps SIGNAL_NO_DATA") + ); + assert!(lines[7].contains("named a gap") && lines[7].contains("gaps RUNTIME_STALE")); + + // Zero matching deploys: empty, filtered out when `recorded > 0`, followed + // unsuccessful `workflow_run`, and unanswered verification read. + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--timeout", "0"]), + vec![recorded(&[])], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::NotComplete); + assert_eq!( + commands(&stderr), + [ + "::warning title=Proofline deploy%3A LANDING::No deploy of acme/app at 89abcdef0123456789abcdef0123456789abcdef was recorded after 0 minutes. The result is not established." + ] + ); + + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--task", "missing", "--timeout", "0"]), + vec![recorded(std::slice::from_ref(&healthy))], + Duration::ZERO, + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::NotComplete); + assert_eq!( + commands(&stderr), + [ + "::warning title=Proofline deploy%3A LANDING::Proofline recorded 1 deploy of acme/app at 89abcdef0123456789abcdef0123456789abcdef, and none matches --environment-id, --aws-run, --environment, --task, --deployment, --run or --attempt after 0 minutes. The result is not established." + ] + ); + + let payload = json!({ "workflow_run": { + "head_sha": COMMIT, "id": 7, "run_attempt": 1, "conclusion": "failure\n::add-mask::c" + } }); + let mut followed = args(&["--annotations"]); + followed.follow( + &ProducingRun::parse(payload.to_string().as_bytes()).unwrap(), + false, + ); + let (verdict, _, _, _, stderr) = + run_annotated(&followed, vec![recorded(&[])], Duration::ZERO).await; + assert_eq!(verdict.unwrap(), Verdict::NotComplete); + assert_eq!( + commands(&stderr), + [ + "::warning title=Proofline deploy%3A LANDING::Run 7 concluded failure%0A::add-mask::c and recorded no deploy of acme/app at 89abcdef0123456789abcdef0123456789abcdef that this job selects; Proofline waited 5 minutes for one. The result is not established." + ] + ); + + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--timeout", "1"]), + vec![(503, json!({ "detail": "unavailable" }))], + Duration::from_secs(15), + ) + .await; + assert_eq!(verdict.unwrap(), Verdict::NotComplete); + assert_eq!( + commands(&stderr), + [ + "::warning title=Proofline deploy%3A LANDING::Proofline did not answer a verification read for acme/app at 89abcdef0123456789abcdef0123456789abcdef within 1 minutes. The result is not established." + ] + ); + + // Auth/usage refusals and transient unavailability errors emit nothing. + for answers in [ + vec![(401, json!({ "detail": "unauthorized" }))], + vec![(403, json!({ "detail": "forbidden" }))], + vec![(503, json!({ "detail": "unavailable" }))], + vec![ + recorded(&[deploy("deploy", &[1], &[], &[])]), + (502, json!({ "detail": "bad gateway" })), + ], + ] { + let (verdict, _, _, _, stderr) = run_annotated( + &args(&["--annotations", "--until", "20m"]), + answers, + Duration::ZERO, + ) + .await; + assert!(verdict.is_err()); + assert!(stderr.is_empty()); + } + } } diff --git a/tests/http.rs b/tests/http.rs index eb15b98..57b6da6 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -2580,6 +2580,278 @@ async fn ci_review_annotations_put_open_findings_on_the_diff_as_escaped_workflow assert_eq!(result["outcome"], "COMPLETED"); } +#[tokio::test] +async fn ci_deploy_annotations_report_regressions_and_unestablished_deploys_as_escaped_commands() { + let response: Arc> = + Arc::new(Mutex::new((StatusCode::OK, json!({})))); + let served = Arc::clone(&response); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({ "repositories": [{ "id": CI_REPOSITORY, "full_name": "acme/app" }] })) + }), + ) + .route( + &format!( + "/api/v1/organizations/{ORG}/repositories/{CI_REPOSITORY}/commits/{CI_HEAD}/deploy-verifications" + ), + get(move || { + let served = Arc::clone(&served); + async move { + let (status, body) = served.lock().unwrap().clone(); + (status, Json(body)).into_response() + } + }), + ); + 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() }); + + let commands = |output: &std::process::Output| -> Vec { + String::from_utf8_lossy(&output.stderr) + .lines() + .filter(|line| line.starts_with("::")) + .map(str::to_owned) + .collect() + }; + + // Healthy deploy with no gaps: exit 0 and no annotations even with `--annotations`. + let healthy_body = json!({ + "recorded": true, + "deploys": [{ + "environment_id": "0190f3a0-0000-7000-8000-0000000000e0", + "github_environment": "production", + "deployment_task": "deploy:web", + "workflow_run_id": 7, + "workflow_run_attempts": [1], + "state": "VERIFIED", + "regressed": false, + "checkpoints": [{ + "checkpoint": "LANDING", + "result": "HEALTHY", + "due_at": "2026-11-21T00:00:00Z", + "gaps": [], + }], + "gaps": [], + "deploy_url": "https://console.proofline.example/deploys/10", + }], + }); + *response.lock().unwrap() = (StatusCode::OK, healthy_body.clone()); + let healthy = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--json", + "--annotations", + ], + ) + .await; + assert_eq!(healthy.status.code(), Some(0)); + assert!(commands(&healthy).is_empty()); + assert_eq!( + serde_json::from_slice::(&healthy.stdout).unwrap(), + healthy_body + ); + + // Regression recorded after `--until` with injection payloads across + // environment, task, and gaps: opt-in by default, escaped `::error` with + // `--annotations`, and `stdout` stays valid JSON. + let regressed_body = json!({ + "recorded": true, + "deploys": [{ + "environment_id": "0190f3a0-0000-7000-8000-0000000000e0", + "github_environment": "prod:eu\r\n::add-mask::secret", + "deployment_task": "deploy:api,100%\u{1b}[31m", + "workflow_run_id": 7, + "workflow_run_attempts": [1], + "state": "NOT_YET_DUE", + "regressed": true, + "checkpoints": [ + { + "checkpoint": "LANDING", + "result": "HEALTHY", + "due_at": "2026-11-21T00:00:00Z", + "gaps": [], + }, + { + "checkpoint": "MINUTES_20", + "result": "HEALTHY", + "due_at": "2026-11-21T00:20:00Z", + "gaps": [], + }, + { + "checkpoint": "HOUR_1", + "result": "REGRESSED", + "due_at": "2026-11-21T01:00:00Z", + "gaps": ["LATENCY_SPIKE:100%\n::add-mask::secret"], + }, + ], + "gaps": [], + "deploy_url": "https://console.proofline.example/deploys/11", + }], + }); + *response.lock().unwrap() = (StatusCode::OK, regressed_body.clone()); + let plain = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--json", + ], + ) + .await; + assert_eq!(plain.status.code(), Some(3)); + assert!(commands(&plain).is_empty(), "annotations are opt-in"); + + let regressed = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--json", + "--annotations", + ], + ) + .await; + assert_eq!(regressed.status.code(), Some(3)); + assert_eq!( + commands(®ressed), + [ + "::error title=Proofline deploy%3A prod%3Aeu\u{FFFD}%0A%3A%3Aadd-mask%3A%3Asecret deploy%3Aapi%2C100%25\u{FFFD}[31m run 7 attempt 1::prod:eu\u{FFFD}%0A::add-mask::secret deploy:api,100%25\u{FFFD}[31m run 7 attempt 1 recorded REGRESSED at HOUR_1; state NOT_YET_DUE; gaps LATENCY_SPIKE:100%25%0A::add-mask::secret; https://console.proofline.example/deploys/11", + ] + ); + assert_eq!( + serde_json::from_slice::(®ressed.stdout).unwrap(), + regressed_body + ); + + // Non-established verdicts: `Ended` deploy and zero matching deploys both + // exit 2 and emit `::warning`. + let ended_body = json!({ + "recorded": true, + "deploys": [{ + "environment_id": "0190f3a0-0000-7000-8000-0000000000e0", + "github_environment": "production", + "deployment_task": "deploy:web", + "workflow_run_id": 7, + "workflow_run_attempts": [1], + "state": "UNRECORDED", + "regressed": false, + "verification_ended": true, + "checkpoints": [{ + "checkpoint": "LANDING", + "result": "HEALTHY", + "due_at": "2026-11-21T00:00:00Z", + "gaps": [], + }], + "gaps": [], + "deploy_url": "https://console.proofline.example/deploys/12", + }], + }); + *response.lock().unwrap() = (StatusCode::OK, ended_body.clone()); + let ended = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--until", + "20m", + "--timeout", + "0", + "--json", + "--annotations", + ], + ) + .await; + assert_eq!(ended.status.code(), Some(2)); + assert_eq!( + commands(&ended), + [ + "::warning title=Proofline deploy%3A production deploy%3Aweb run 7 attempt 1::production deploy:web run 7 attempt 1: deploy checks ended without recording the MINUTES_20 check; state UNRECORDED; the result is not established; https://console.proofline.example/deploys/12", + ] + ); + assert_eq!( + serde_json::from_slice::(&ended.stdout).unwrap(), + ended_body + ); + + let unmatched = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--task", + "deploy:missing", + "--timeout", + "0", + "--json", + "--annotations", + ], + ) + .await; + assert_eq!(unmatched.status.code(), Some(2)); + assert_eq!( + commands(&unmatched), + [format!( + "::warning title=Proofline deploy%3A LANDING::Proofline recorded 1 deploy of acme/app at {CI_HEAD}, and none matches --environment-id, --aws-run, --environment, --task, --deployment, --run or --attempt after 0 minutes. The result is not established." + )] + ); + + // Server unavailability (exit 4) and auth refusal (exit 1) emit no annotations. + for (status, exit_code) in [ + (StatusCode::SERVICE_UNAVAILABLE, 4), + (StatusCode::UNAUTHORIZED, 1), + ] { + *response.lock().unwrap() = (status, json!({ "detail": "no" })); + let output = cli( + &origin, + &[ + "ci", + "deploy", + "--repo", + "acme/app", + "--commit", + CI_HEAD, + "--timeout", + "0", + "--json", + "--annotations", + ], + ) + .await; + assert_eq!(output.status.code(), Some(exit_code)); + assert!(commands(&output).is_empty()); + } +} + #[tokio::test] async fn native_tools_keep_tenant_paths_and_reruns_make_one_attempt() { let requests = Arc::new(Mutex::new(Vec::new()));