From bc7ac16b8fb9fa5488b159f781918bb482d6c929 Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:29:06 +0000 Subject: [PATCH 1/6] feat: require a named environment in CI reviews --- README.md | 12 + src/lib.rs | 21 ++ src/required_environment.rs | 289 +++++++++++++++++++++++ tests/required_environment.rs | 425 ++++++++++++++++++++++++++++++++++ 4 files changed, 747 insertions(+) create mode 100644 src/required_environment.rs create mode 100644 tests/required_environment.rs diff --git a/README.md b/README.md index d363b33..545111d 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,18 @@ Repository commands use the checkout’s `origin` by default. Use `--remote NAME 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. +A pull-request job can require the review to have checked a particular environment: + +```sh +proofline ci review --require-environment production --fail-on serious +``` + +Use the environment's exact external key (`environment_external_key` in the review's `environments` array), not its display name. The final review response must contain exactly one entry with that key and state `CHECKED`. A staging-only or code-only review cannot satisfy a requirement for production. The command exits 2 with an explanation on stderr if evidence is missing, unreadable, duplicated or unchecked. If any entry has a malformed field used by this check, the requirement fails. A `CHECKED` entry that also records a reason it was not checked does not satisfy it either. + +The existing review identity and completeness checks still run first. Only after the environment requirement is met does `--fail-on` apply, including its check for available finding counts. An unmet environment requirement therefore exits 2 even when findings would cause exit 3 or missing counts would cause exit 4. Without `--require-environment`, behaviour is unchanged. The option adds no API request and does not start a separate environment check. + +With `--json`, the review document and its completeness `outcome` are unchanged. The command can therefore exit 2 even when the review says `COMPLETED`, just as it can exit 3 under `--fail-on`. Always read the process exit code. This option applies to pull-request reviews; it does not verify a deployment or establish that a change is safe. + 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 successful CodePipeline executions and failed, stopped or cancelled ones it ties to the ECS rollout that served the commit. A reader inside a still-running execution finds no matching deploy, 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/lib.rs b/src/lib.rs index 41b26bc..8a2d69b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,6 +19,7 @@ pub mod origin; pub mod outcome; mod preflight; pub mod render; +mod required_environment; mod result; mod sarif; mod scan; @@ -247,6 +248,11 @@ struct CiReviewArgs { /// review exits 2 whatever it found. #[arg(long, value_enum, value_name = "SEVERITY")] fail_on: Option, + /// Require the final pull-request review to report this environment as + /// CHECKED. Use its exact external key, not its display name. Missing, + /// ambiguous or unchecked evidence exits 2 before --fail-on is measured. + #[arg(long, value_name = "KEY", value_parser = required_environment::key)] + require_environment: Option, #[command(flatten)] repository: RepositoryArgs, } @@ -1639,6 +1645,15 @@ async fn ci_review( if args.annotations { annotations::write(&detail, &mut std::io::stderr().lock())?; } + let environment_gap = if state == Some(Outcome::Completed) { + args.require_environment.as_deref().and_then(|key| { + required_environment::check(&raw, key) + .err() + .map(|gap| gap.message(key)) + }) + } else { + None + }; print_review( api, review_id, @@ -1647,6 +1662,10 @@ async fn ci_review( state, OutputFormat::from_json(args.json), )?; + if let Some(message) = environment_gap { + say(&message); + return Ok(Verdict::NotComplete); + } let verdict = ci_verdict(state, detail.open_items.as_ref(), args.fail_on); say_ci_ending(api, review_id, &detail, state, verdict, args.timeout); Ok(verdict) @@ -2172,6 +2191,7 @@ mod tests { json: false, timeout: 3, fail_on: None, + require_environment: None, repository: RepositoryArgs { repo: Some("acme/app".to_owned()), source_provider: None, @@ -2244,6 +2264,7 @@ mod tests { json: false, timeout: 3, fail_on: None, + require_environment: None, repository: RepositoryArgs { repo: Some("acme/app".to_owned()), source_provider: None, diff --git a/src/required_environment.rs b/src/required_environment.rs new file mode 100644 index 0000000..5842d3f --- /dev/null +++ b/src/required_environment.rs @@ -0,0 +1,289 @@ +//! An explicit CI requirement, separate from the review's own completeness. + +use serde::Deserialize; +use serde_json::Value; + +use crate::text; + +/// Decode only on the opt-in path. An older response without environment +/// evidence must still work when the caller has not required an environment. +/// Unknown fields and future state/reason strings remain readable. +/// Malformed decoded fields anywhere in the list prevent establishing the requirement. +#[derive(Debug, Deserialize)] +struct Environment { + environment_external_key: String, + state: String, + reason: Option, + #[serde(default)] + reason_unrecorded: bool, + #[serde(default)] + unfinished_inventory_incomplete: bool, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum Gap { + Unavailable, + Malformed, + Missing, + Ambiguous, + Unchecked { + state: String, + reason: Option, + }, + Contradictory, +} + +impl Gap { + pub(crate) fn message(&self, key: &str) -> String { + let why = match self { + Self::Unavailable => "the review has no environment evidence".to_owned(), + Self::Malformed => "the review's environment evidence could not be read".to_owned(), + Self::Missing => "the review has no entry with that exact external key".to_owned(), + Self::Ambiguous => { + "the review has more than one entry with that external key".to_owned() + } + Self::Unchecked { state, reason } => { + let mut detail = format!( + "the review reports {} rather than CHECKED", + text::one_line(state) + ); + if let Some(reason) = reason { + detail.push_str(" ("); + detail.push_str(&text::one_line(reason)); + detail.push(')'); + } + detail + } + Self::Contradictory => { + "the CHECKED entry also records evidence that it was not checked".to_owned() + } + }; + format!( + "Required environment `{}` was not established: {why}.", + text::one_line(key) + ) + } +} + +/// Require one exact key in the final response, independently of display names. +/// The caller must first check the review's identity and completeness; CHECKED +/// alone neither completes the review nor establishes a safe deployment. +pub(crate) fn check(review: &Value, key: &str) -> Result<(), Gap> { + let evidence = review + .get("environments") + .filter(|value| !value.is_null()) + .ok_or(Gap::Unavailable)?; + let environments = Vec::::deserialize(evidence).map_err(|_| Gap::Malformed)?; + let mut matching = environments + .into_iter() + .filter(|environment| environment.environment_external_key == key); + let environment = matching.next().ok_or(Gap::Missing)?; + // Never choose a favorable entry from conflicting duplicates. + if matching.next().is_some() { + return Err(Gap::Ambiguous); + } + if environment.state != "CHECKED" { + return Err(Gap::Unchecked { + state: environment.state, + reason: environment.reason, + }); + } + // These fields describe why an environment was not checked. A conflicting + // CHECKED value must not turn them into evidence for the requirement. + if environment.reason.is_some() + || environment.reason_unrecorded + || environment.unfinished_inventory_incomplete + { + return Err(Gap::Contradictory); + } + Ok(()) +} + +/// A key is an exact identifier. Reject an empty argument without normalising +/// one that is supplied: display names, case folding and trimming can select +/// another environment. +pub(crate) fn key(value: &str) -> Result { + if value.trim().is_empty() { + Err("name a non-empty environment external key".to_owned()) + } else { + Ok(value.to_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn checked(key: &str) -> Value { + json!({"environment_external_key": key, "environment_display_name": "production", "state": "CHECKED"}) + } + + #[test] + fn only_one_exact_key_satisfies_the_requirement() { + let document = json!({"environments": [checked("staging"), checked("production")]}); + assert_eq!(check(&document, "production"), Ok(())); + for key in ["Production", " production", "production "] { + assert_eq!(check(&document, key), Err(Gap::Missing)); + } + assert_eq!( + check(&json!({"environments": [checked("staging")]}), "production"), + Err(Gap::Missing) + ); + for state in ["CHECKED", "NOT_CHECKED"] { + let mut duplicate = checked("production"); + duplicate["state"] = json!(state); + assert_eq!( + check( + &json!({"environments": [checked("production"), duplicate]}), + "production" + ), + Err(Gap::Ambiguous) + ); + } + } + + #[test] + fn unavailable_or_unreadable_metadata_never_passes() { + assert_eq!(check(&json!({}), "production"), Err(Gap::Unavailable)); + assert_eq!( + check(&json!({"environments": null}), "production"), + Err(Gap::Unavailable) + ); + assert_eq!( + check(&json!({"environments": []}), "production"), + Err(Gap::Missing) + ); + for evidence in [ + json!({}), + json!(false), + json!([null]), + json!([{"state": "CHECKED"}]), + json!([{"environment_external_key": 42, "state": "CHECKED"}]), + json!([{"environment_external_key": "production"}]), + json!([{"environment_external_key": "production", "state": null}]), + json!([checked("production"), {"state": "CHECKED"}]), + ] { + assert_eq!( + check(&json!({"environments": evidence}), "production"), + Err(Gap::Malformed) + ); + } + for (field, value) in [ + ("reason", json!(3)), + ("reason_unrecorded", Value::Null), + ("unfinished_inventory_incomplete", json!("false")), + ] { + let mut environment = checked("production"); + environment[field] = value; + assert_eq!( + check(&json!({"environments": [environment]}), "production"), + Err(Gap::Malformed) + ); + } + } + + #[test] + fn only_checked_passes_including_future_states() { + for state in [ + "CHECKING", + "NOT_CHECKED", + "NOT_APPLICABLE", + "FUTURE_STATE", + "checked", + "", + ] { + let mut environment = checked("production"); + environment["state"] = json!(state); + environment["reason"] = json!("FUTURE_REASON"); + assert_eq!( + check(&json!({"environments": [environment]}), "production"), + Err(Gap::Unchecked { + state: state.to_owned(), + reason: Some("FUTURE_REASON".to_owned()) + }) + ); + } + } + + #[test] + fn checked_must_not_contradict_its_recorded_evidence() { + for (field, value) in [ + ("reason", json!("UNFINISHED")), + ("reason_unrecorded", json!(true)), + ("unfinished_inventory_incomplete", json!(true)), + ] { + let mut environment = checked("production"); + environment[field] = value; + assert_eq!( + check(&json!({"environments": [environment]}), "production"), + Err(Gap::Contradictory) + ); + } + let mut environment = checked("production"); + environment["reason"] = Value::Null; + environment["reason_unrecorded"] = json!(false); + environment["unfinished_inventory_incomplete"] = json!(false); + environment["future_metadata"] = json!({"retained": true}); + assert_eq!( + check(&json!({"environments": [environment]}), "production"), + Ok(()) + ); + } + + #[test] + fn diagnostics_cannot_inject_terminal_or_workflow_commands() { + let hostile = "production\n::error::injected\u{1b}[2J\u{202e}\t"; + let message = Gap::Unchecked { + state: hostile.to_owned(), + reason: Some(hostile.to_owned()), + } + .message(hostile); + assert_eq!(message.lines().count(), 1); + assert!(!message.chars().any(|c| c.is_control() || c == '\u{202e}')); + assert!(message.starts_with("Required environment `")); + } + + #[test] + fn keys_are_validated_without_rewriting_them() { + for empty in ["", " ", "\t\n", "\u{a0}"] { + assert!(key(empty).is_err()); + } + for literal in ["production", "Production", " production "] { + assert_eq!(key(literal), Ok(literal.to_owned())); + } + } + + #[test] + fn requirement_uses_fields_in_the_bundled_contract() { + let contract: Value = serde_json::from_str(include_str!(concat!( + env!("OUT_DIR"), + "/openapi.public.json" + ))) + .unwrap(); + let schemas = &contract["components"]["schemas"]; + assert_eq!( + schemas["CustomerReviewDetail"]["properties"]["environments"]["items"]["$ref"], + "#/components/schemas/EnvironmentCheck" + ); + let fields = schemas["EnvironmentCheck"]["properties"] + .as_object() + .unwrap(); + for field in [ + "environment_external_key", + "state", + "reason", + "reason_unrecorded", + "unfinished_inventory_incomplete", + ] { + assert!(fields.contains_key(field), "{field}"); + } + assert!( + schemas["EnvironmentCheckState"]["oneOf"] + .as_array() + .unwrap() + .iter() + .any(|state| state["const"] == "CHECKED") + ); + } +} diff --git a/tests/required_environment.rs b/tests/required_environment.rs new file mode 100644 index 0000000..1693391 --- /dev/null +++ b/tests/required_environment.rs @@ -0,0 +1,425 @@ +//! CI policy against a local console. No account or cloud connection is used. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use axum::http::{HeaderMap, header}; +use axum::routing::get; +use axum::{Json, Router}; +use serde_json::{Value, json}; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const REPO: &str = "0190f3a0-0000-7000-8000-000000000002"; +const REVIEW: &str = "0190f3a0-0000-7000-8000-000000000003"; +const HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; + +fn environment(key: &str, state: &str) -> Value { + json!({ + "environment_external_key": key, + // A display name is deliberately not the key. + "environment_display_name": "Shared display name", + "state": state, + "reason": null, + }) +} + +fn review() -> Value { + json!({ + "id": REVIEW, "kind": "PULL_REQUEST", "status": "COMPLETED", + "head_commit_sha": HEAD, "repository_id": REPO, + "pull_request_number": 12, "run_number": 1, + "assessment_count": 1, + "assessments": [{ + "id": "0190f3a0-0000-7000-8000-000000000004", + "environment_display_name": "Shared display name", + "status": "COMPLETED", "findings": [], + "checks": {"receipt_recorded": true, "status": "READY", "families": []}, + }], + "open_items": {"open_findings": 0, "serious_findings": 0}, + "environments": [environment("production", "CHECKED")], + }) +} + +struct Console { + origin: String, + requests: Arc>>, + server: tokio::task::JoinHandle<()>, +} + +impl Drop for Console { + fn drop(&mut self) { + self.server.abort(); + } +} + +async fn console(responses: Vec) -> Console { + assert!(!responses.is_empty()); + let reads = Arc::new(AtomicUsize::new(0)); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/repository-names"), + get(|| async { + Json(json!({"repositories": [{"id": REPO, "full_name": "acme/app"}]})) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews"), + get(|| async { + Json(json!({ + "items": [{ + "id": REVIEW, "kind": "PULL_REQUEST", "status": "COMPLETED", + "created_at": "2026-12-01T00:00:00Z", "head_commit_sha": HEAD, + "repository_id": REPO, "pull_request_number": 12, "run_number": 1, + }], + "next_cursor": null, "truncated": false, + "filters": {"repositories": [], "environments": [], "authors": []}, + })) + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{REVIEW}"), + get(move |headers: HeaderMap| { + assert_eq!(headers[header::AUTHORIZATION], "Bearer test-only-token"); + let i = reads + .fetch_add(1, Ordering::SeqCst) + .min(responses.len() - 1); + let response = responses[i].clone(); + async { Json(response) } + }), + ); + let requests = Arc::new(Mutex::new(Vec::new())); + 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())); + 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()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + Console { + origin, + requests, + server, + } +} + +async fn run(console: &Console, extra: &[&str]) -> std::process::Output { + let mut args = vec!["--json"]; + args.extend_from_slice(extra); + run_output(console, &args).await +} + +async fn run_output(console: &Console, extra: &[&str]) -> std::process::Output { + let directory = tempfile::tempdir().unwrap(); + // The polling test waits through the CLI's initial five-second interval. + tokio::time::timeout( + std::time::Duration::from_secs(15), + tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) + .env_clear() + .env("PROOFLINE_TOKEN", "test-only-token") + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .env("PATH", "") + .args(["--base-url", &console.origin, "--org", ORG, "ci", "review"]) + .args(["--repo", "acme/app", "--commit", HEAD]) + .args(extra) + .current_dir(directory.path()) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap() +} + +#[tokio::test] +async fn required_environment_blocks_a_staging_only_review() { + let mut document = review(); + let mut production = environment("production", "NOT_APPLICABLE"); + production["reason"] = json!("PULL_REQUEST_REVIEWS_OFF"); + document["environments"] = json!([environment("staging", "CHECKED"), production]); + let console = console(vec![document.clone()]).await; + + let ordinary = run(&console, &[]).await; + assert_eq!( + ordinary.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&ordinary.stderr) + ); + let staging = run(&console, &["--require-environment", "staging"]).await; + assert_eq!( + staging.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&staging.stderr) + ); + assert_eq!(ordinary.stdout, staging.stdout); + + let production = run(&console, &["--require-environment", "production"]).await; + assert_eq!( + production.status.code(), + Some(2), + "{}", + String::from_utf8_lossy(&production.stderr) + ); + let stderr = String::from_utf8_lossy(&production.stderr); + assert!( + stderr.contains("production") && stderr.contains("NOT_APPLICABLE"), + "{stderr}" + ); + assert!(stderr.contains("PULL_REQUEST_REVIEWS_OFF"), "{stderr}"); + assert!(!stderr.contains("without `open_items`"), "{stderr}"); + assert_eq!(ordinary.stdout, production.stdout); + let result: Value = serde_json::from_slice(&production.stdout).unwrap(); + assert_eq!(result["outcome"], "COMPLETED"); + assert_eq!(result["review"], document); + + // The policy adds no API call or review request. + let requests = console.requests.lock().unwrap(); + assert_eq!(requests.len(), 9); + for group in requests.chunks_exact(3) { + assert!(group[0].ends_with("/repository-names")); + assert!(group[1].contains("/reviews?")); + assert!(group[2].ends_with(&format!("/reviews/{REVIEW}"))); + assert!(group.iter().all(|request| request.starts_with("GET "))); + } +} + +#[tokio::test] +async fn required_environment_preserves_completeness_and_findings_precedence() { + for (assessment, target, open, expected) in [ + ("COMPLETED", "CHECKED", Some([0, 0]), 0), + ("COMPLETED", "CHECKED", Some([1, 1]), 3), + ("COMPLETED", "CHECKED", None, 4), + ("COMPLETED", "NOT_CHECKED", Some([1, 1]), 2), + ("COMPLETED", "NOT_CHECKED", None, 2), + ("INCOMPLETE", "CHECKED", Some([1, 1]), 2), + ] { + let mut document = review(); + document["assessments"][0]["status"] = json!(assessment); + document["environments"][0]["state"] = json!(target); + document["open_items"] = open.map_or( + Value::Null, + |[all, serious]| json!({"open_findings": all, "serious_findings": serious}), + ); + let console = console(vec![document]).await; + let output = run( + &console, + &[ + "--require-environment", + "production", + "--fail-on", + "serious", + ], + ) + .await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!( + output.status.code(), + Some(expected), + "{assessment} {target} {open:?}: {stderr}" + ); + assert_eq!(stderr.contains("without `open_items`"), expected == 4); + assert_eq!( + stderr.contains("at or above the --fail-on severity"), + expected == 3 + ); + if assessment == "INCOMPLETE" { + assert!(!stderr.contains("Required environment"), "{stderr}"); + } + } +} + +#[tokio::test] +async fn required_environment_uses_the_final_poll_response() { + let mut running = review(); + running["status"] = json!("RUNNING"); + let mut completed = review(); + completed.as_object_mut().unwrap().remove("environments"); + let console = console(vec![running, completed.clone()]).await; + let output = run(&console, &["--require-environment", "production"]).await; + assert_eq!( + output.status.code(), + Some(2), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(result["review"], completed); + assert_eq!(console.requests.lock().unwrap().len(), 4); +} + +#[tokio::test] +async fn required_environment_cannot_override_the_requested_subject() { + for field in ["id", "kind", "head_commit_sha", "repository_id"] { + let mut document = review(); + document[field] = match field { + "kind" => json!("DEPLOYMENT"), + "head_commit_sha" => json!("fedcba9876543210fedcba9876543210fedcba98"), + _ => json!("0190f3a0-0000-7000-8000-000000000099"), + }; + let console = console(vec![document]).await; + let output = run(&console, &["--require-environment", "production"]).await; + assert_eq!( + output.status.code(), + Some(1), + "{field}: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty()); + } +} + +#[tokio::test] +async fn required_environment_rejects_empty_or_repeated_keys_before_http() { + let console = console(vec![review()]).await; + for args in [ + vec!["--require-environment", ""], + vec!["--require-environment", " \t"], + vec![ + "--require-environment", + "production", + "--require-environment", + "staging", + ], + ] { + let output = run(&console, &args).await; + assert_eq!( + output.status.code(), + Some(1), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stdout.is_empty()); + } + assert!(console.requests.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn required_environment_reports_gaps_without_changing_the_default_path() { + let mut conflicting = environment("production", "CHECKED"); + conflicting["unfinished_inventory_incomplete"] = json!(true); + for (evidence, explanation) in [ + (None, "no environment evidence"), + (Some(Value::Null), "no environment evidence"), + (Some(json!([])), "no entry with that exact external key"), + (Some(json!({})), "could not be read"), + ( + Some(json!([environment("Production", "CHECKED")])), + "no entry with that exact external key", + ), + ( + Some(json!([ + environment("production", "CHECKED"), + environment("production", "NOT_CHECKED") + ])), + "more than one entry", + ), + ( + Some(json!([environment("production", "CHECKING")])), + "CHECKING rather than CHECKED", + ), + ( + Some(json!([environment("production", "FUTURE_STATE")])), + "FUTURE_STATE rather than CHECKED", + ), + (Some(json!([conflicting])), "also records evidence"), + ] { + let mut document = review(); + if let Some(evidence) = evidence { + document["environments"] = evidence; + } else { + document.as_object_mut().unwrap().remove("environments"); + } + let console = console(vec![document]).await; + let ordinary = run(&console, &[]).await; + assert_eq!( + ordinary.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&ordinary.stderr) + ); + let required = run(&console, &["--require-environment", "production"]).await; + let stderr = String::from_utf8_lossy(&required.stderr); + assert_eq!(required.status.code(), Some(2), "{stderr}"); + assert!(stderr.contains(explanation), "{stderr}"); + assert_eq!(ordinary.stdout, required.stdout); + } +} + +#[tokio::test] +async fn required_environment_does_not_treat_code_only_as_environment_evidence() { + let mut document = review(); + document.as_object_mut().unwrap().remove("environments"); + document["assessments"] = json!([]); + document["assessment_count"] = json!(0); + document["code_assessment"] = json!({ + "id": "0190f3a0-0000-7000-8000-000000000005", + "status": "COMPLETED", "head_commit_sha": HEAD, + "base_commit_sha": "0123456789abcdef0123456789abcdef01234567", + "findings": [], + }); + let console = console(vec![document]).await; + let ordinary = run(&console, &[]).await; + assert_eq!( + ordinary.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&ordinary.stderr) + ); + let required = run(&console, &["--require-environment", "production"]).await; + assert_eq!( + required.status.code(), + Some(2), + "{}", + String::from_utf8_lossy(&required.stderr) + ); + assert_eq!(ordinary.stdout, required.stdout); +} + +#[tokio::test] +async fn required_environment_preserves_unfinished_review_outcomes() { + for (status, exit) in [("RUNNING", 4), ("FAILED", 2), ("STOPPED", 2)] { + let mut document = review(); + document["status"] = json!(status); + document.as_object_mut().unwrap().remove("environments"); + let console = console(vec![document]).await; + let output = run( + &console, + &["--timeout", "0", "--require-environment", "production"], + ) + .await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(exit), "{status}: {stderr}"); + assert!(!stderr.contains("Required environment"), "{stderr}"); + assert_eq!(console.requests.lock().unwrap().len(), 3); + } +} + +#[tokio::test] +async fn required_environment_explains_the_gap_in_text_mode() { + let mut document = review(); + document["environments"] = json!([environment("staging", "CHECKED")]); + let console = console(vec![document]).await; + let output = run_output(&console, &["--require-environment", "production"]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!( + stderr.contains("Required environment `production`"), + "{stderr}" + ); + assert!( + stderr.contains("no entry with that exact external key"), + "{stderr}" + ); + assert!(!output.stdout.is_empty()); + assert!(serde_json::from_slice::(&output.stdout).is_err()); +} From 7cc41b92a016c55676d358ac8053bb30391d4be6 Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:10:48 +0000 Subject: [PATCH 2/6] fix: reject positional environment evidence in CI --- src/required_environment.rs | 22 ++++++++++++++++++++++ tests/required_environment.rs | 23 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/required_environment.rs b/src/required_environment.rs index 5842d3f..0ad0a98 100644 --- a/src/required_environment.rs +++ b/src/required_environment.rs @@ -73,6 +73,12 @@ pub(crate) fn check(review: &Value, key: &str) -> Result<(), Gap> { .get("environments") .filter(|value| !value.is_null()) .ok_or(Gap::Unavailable)?; + let entries = evidence.as_array().ok_or(Gap::Malformed)?; + // Serde also accepts positional arrays for derived structs. The API + // requires objects with named evidence fields, including unrelated entries. + if entries.iter().any(|entry| !entry.is_object()) { + return Err(Gap::Malformed); + } let environments = Vec::::deserialize(evidence).map_err(|_| Gap::Malformed)?; let mut matching = environments .into_iter() @@ -183,6 +189,22 @@ mod tests { } } + #[test] + fn positional_environment_arrays_are_malformed() { + for evidence in [ + json!([["production", "CHECKED", null, false, false]]), + json!([ + checked("production"), + ["staging", "CHECKED", null, false, false] + ]), + ] { + assert_eq!( + check(&json!({"environments": evidence}), "production"), + Err(Gap::Malformed) + ); + } + } + #[test] fn only_checked_passes_including_future_states() { for state in [ diff --git a/tests/required_environment.rs b/tests/required_environment.rs index 1693391..2c94a81 100644 --- a/tests/required_environment.rs +++ b/tests/required_environment.rs @@ -355,6 +355,29 @@ async fn required_environment_reports_gaps_without_changing_the_default_path() { } } +#[tokio::test] +async fn required_environment_rejects_positional_environment_arrays() { + for evidence in [ + json!([["production", "CHECKED", null, false, false]]), + json!([ + environment("production", "CHECKED"), + ["staging", "CHECKED", null, false, false] + ]), + ] { + let mut document = review(); + document["environments"] = evidence; + let console = console(vec![document]).await; + let ordinary = run(&console, &[]).await; + assert_eq!(ordinary.status.code(), Some(0)); + let required = run(&console, &["--require-environment", "production"]).await; + let stderr = String::from_utf8_lossy(&required.stderr); + assert_eq!(required.status.code(), Some(2), "{stderr}"); + assert!(stderr.contains("could not be read"), "{stderr}"); + assert_eq!(ordinary.stdout, required.stdout); + assert_eq!(console.requests.lock().unwrap().len(), 6); + } +} + #[tokio::test] async fn required_environment_does_not_treat_code_only_as_environment_evidence() { let mut document = review(); From 722810f8c990fc91c94e42ab52498cfaa1193dea Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:30:49 +0000 Subject: [PATCH 3/6] fix: escape legacy workflow commands in environment diagnostics --- src/required_environment.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/required_environment.rs b/src/required_environment.rs index 0ad0a98..1006114 100644 --- a/src/required_environment.rs +++ b/src/required_environment.rs @@ -62,6 +62,8 @@ impl Gap { "Required environment `{}` was not established: {why}.", text::one_line(key) ) + // Actions' legacy command parser also searches within a line. + .replace("##[", "##\\[") } } @@ -266,6 +268,40 @@ mod tests { assert!(message.starts_with("Required environment `")); } + #[test] + fn diagnostics_do_not_form_legacy_workflow_commands() { + // Actions' legacy parser finds ##[ anywhere, then reads a command + // name through the next space or ]. A fixed line prefix is not enough. + // https://github.com/actions/runner/blob/main/src/Runner.Common/ActionCommand.cs + fn legacy_command(message: &str) -> Option<&str> { + let (_, rest) = message.split_once("##[")?; + let (info, _) = rest.split_once(']')?; + let command = info.split(' ').next()?; + ["warning", "error", "notice"] + .contains(&command) + .then_some(command) + } + + let hostile = "production##[warning]forged"; + // Confirm this consumer-rule check catches an embedded command. + assert_eq!( + legacy_command(&format!("prefix {hostile}")), + Some("warning") + ); + for (key, state, reason) in [ + (hostile, "NOT_CHECKED", None), + ("production", hostile, None), + ("production", "NOT_CHECKED", Some(hostile)), + ] { + let message = Gap::Unchecked { + state: state.to_owned(), + reason: reason.map(str::to_owned), + } + .message(key); + assert_eq!(legacy_command(&message), None, "{message}"); + } + } + #[test] fn keys_are_validated_without_rewriting_them() { for empty in ["", " ", "\t\n", "\u{a0}"] { From 97676e372ca47b5d683e330e8e78047fc7064bc3 Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:03:49 +0000 Subject: [PATCH 4/6] docs: illustrate CI review outcomes for a webshop checkout --- README.md | 2 ++ docs/diagrams/production-checked.svg | 29 ++++++++++++++++++++ docs/diagrams/staging-only-review.svg | 38 +++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 docs/diagrams/production-checked.svg create mode 100644 docs/diagrams/staging-only-review.svg diff --git a/README.md b/README.md index 545111d..6795348 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ The existing review identity and completeness checks still run first. Only after With `--json`, the review document and its completeness `outcome` are unchanged. The command can therefore exit 2 even when the review says `COMPLETED`, just as it can exit 3 under `--fail-on`. Always read the process exit code. This option applies to pull-request reviews; it does not verify a deployment or establish that a change is safe. +See [a staging-only review](docs/diagrams/staging-only-review.svg) and [a review that checked production](docs/diagrams/production-checked.svg) for examples of the CI exit codes. + 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 successful CodePipeline executions and failed, stopped or cancelled ones it ties to the ECS rollout that served the commit. A reader inside a still-running execution finds no matching deploy, 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/docs/diagrams/production-checked.svg b/docs/diagrams/production-checked.svg new file mode 100644 index 0000000..9ec1bb2 --- /dev/null +++ b/docs/diagrams/production-checked.svg @@ -0,0 +1,29 @@ + + When the review checks production + A completed review of a webshop checkout change reports production checked. With fail-on serious, zero open serious findings gives exit 0, one or more open serious findings gives exit 3, and missing finding counts give exit 4. + + + When the review checks production + Proofline’s completed review of the webshop checkout includes the live shop. + + proofline ci review --require-environment production --fail-on serious + + + + + + PRODUCTION CHECKED + What did thereview find? + + + No open serious findingsPass · exit 0 + + At least one open serious findingStop · exit 3 + + Finding counts unavailableStop · exit 4 + + diff --git a/docs/diagrams/staging-only-review.svg b/docs/diagrams/staging-only-review.svg new file mode 100644 index 0000000..07a2758 --- /dev/null +++ b/docs/diagrams/staging-only-review.svg @@ -0,0 +1,38 @@ + + One checkout change, two CI decisions + The completed review of a webshop checkout checked staging and skipped production. CI passes by default. Requiring production makes the same review exit 2. + + + One checkout change, two CI decisions + A developer changes the webshop’s checkout. Proofline finishes its review. + + + + FINAL REVIEWCompleted + STAGING · TEST SHOPChecked + PRODUCTION · LIVE SHOPSkipped + + + + + + + Default CI check + + Pass · exit 0 + CI only required a completed review. + + + + --require-environment production + + Stop · exit 2 + The review skipped the live shop. + + From 404cf4d2382ff36fd474072ae3585f89b74c4d2d Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:41:24 +0000 Subject: [PATCH 5/6] docs: explain the CI use case with Mermaid diagrams --- README.md | 2 +- docs/diagrams/production-checked.svg | 29 ------------ docs/diagrams/required-environment.md | 63 +++++++++++++++++++++++++++ docs/diagrams/staging-only-review.svg | 38 ---------------- 4 files changed, 64 insertions(+), 68 deletions(-) delete mode 100644 docs/diagrams/production-checked.svg create mode 100644 docs/diagrams/required-environment.md delete mode 100644 docs/diagrams/staging-only-review.svg diff --git a/README.md b/README.md index 6795348..008829d 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ The existing review identity and completeness checks still run first. Only after With `--json`, the review document and its completeness `outcome` are unchanged. The command can therefore exit 2 even when the review says `COMPLETED`, just as it can exit 3 under `--fail-on`. Always read the process exit code. This option applies to pull-request reviews; it does not verify a deployment or establish that a change is safe. -See [a staging-only review](docs/diagrams/staging-only-review.svg) and [a review that checked production](docs/diagrams/production-checked.svg) for examples of the CI exit codes. +See [who configures this check and what happens on a checkout pull request](docs/diagrams/required-environment.md). 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 successful CodePipeline executions and failed, stopped or cancelled ones it ties to the ECS rollout that served the commit. A reader inside a still-running execution finds no matching deploy, 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. diff --git a/docs/diagrams/production-checked.svg b/docs/diagrams/production-checked.svg deleted file mode 100644 index 9ec1bb2..0000000 --- a/docs/diagrams/production-checked.svg +++ /dev/null @@ -1,29 +0,0 @@ - - When the review checks production - A completed review of a webshop checkout change reports production checked. With fail-on serious, zero open serious findings gives exit 0, one or more open serious findings gives exit 3, and missing finding counts give exit 4. - - - When the review checks production - Proofline’s completed review of the webshop checkout includes the live shop. - - proofline ci review --require-environment production --fail-on serious - - - - - - PRODUCTION CHECKED - What did thereview find? - - - No open serious findingsPass · exit 0 - - At least one open serious findingStop · exit 3 - - Finding counts unavailableStop · exit 4 - - diff --git a/docs/diagrams/required-environment.md b/docs/diagrams/required-environment.md new file mode 100644 index 0000000..4faa3e3 --- /dev/null +++ b/docs/diagrams/required-environment.md @@ -0,0 +1,63 @@ +# Requiring a production review for a webshop checkout + +## Who uses the check? + +The webshop has a test shop called `staging` and a live shop called `production`. A release engineer configures CI once to require evidence that the review checked production. Developers see the result on each checkout pull request. + +```mermaid +flowchart LR + accTitle: Who uses the production review requirement? + accDescr: The release engineer configures the requirement, CI checks the review for production coverage, and the checkout developer reads the result on the pull request. + engineer["Release engineer"] + ci["Webshop CI"] + developer["Checkout developer"] + subgraph workflow["Webshop pull-request workflow"] + policy(["Require evidence that the review
checked the live shop"]) + verify(["Check the review for
production coverage"]) + result(["Read the result and
any failure reason"]) + end + engineer --- policy + ci --- verify + developer --- result + classDef actor fill:#19384d,color:#ffffff,stroke:#7796ab + classDef goal fill:#e7f2fa,color:#183247,stroke:#88aabf + class engineer,ci,developer actor + class policy,verify,result goal +``` + +The release engineer adds this step to a CI job that already uses the Proofline CLI: + +```yaml +- name: Require production coverage for this pull request + run: proofline ci review --require-environment production --fail-on serious +``` + +## What happens when a developer opens a checkout PR? + +CI reads the completed review for this commit. With `--fail-on serious`, the CLI uses the server’s count of open serious findings. + +```mermaid +sequenceDiagram + accTitle: A checkout pull request with production required + accDescr: CI reads the completed Proofline review. If the review skipped production, the job exits 2. If production was checked, the open serious findings determine the result. + actor Dev as Checkout developer + participant CI as Webshop CI + participant CLI as Proofline CLI + participant API as Proofline API + Dev->>CI: Open a checkout PR + CI->>CLI: Run the configured review step + CLI->>API: Read the PR review for this commit + API-->>CLI: Final review and recorded results + alt Only the test shop was checked + CLI-->>CI: Stop (exit 2), production check missing + else Live shop checked, no open serious findings + CLI-->>CI: Pass (exit 0) + else Live shop checked, open serious findings + CLI-->>CI: Stop (exit 3) + else Live shop checked, finding counts unavailable + CLI-->>CI: Stop (exit 4) + end + CI-->>Dev: Show the check result on the PR +``` + +With the default `proofline ci review` command, the same staging-only review can pass. Adding `--require-environment production` makes CI stop when the final review lacks evidence that production was checked. diff --git a/docs/diagrams/staging-only-review.svg b/docs/diagrams/staging-only-review.svg deleted file mode 100644 index 07a2758..0000000 --- a/docs/diagrams/staging-only-review.svg +++ /dev/null @@ -1,38 +0,0 @@ - - One checkout change, two CI decisions - The completed review of a webshop checkout checked staging and skipped production. CI passes by default. Requiring production makes the same review exit 2. - - - One checkout change, two CI decisions - A developer changes the webshop’s checkout. Proofline finishes its review. - - - - FINAL REVIEWCompleted - STAGING · TEST SHOPChecked - PRODUCTION · LIVE SHOPSkipped - - - - - - - Default CI check - - Pass · exit 0 - CI only required a completed review. - - - - --require-environment production - - Stop · exit 2 - The review skipped the live shop. - - From 84a0dd91fe6f7267ea469499ea67eef920425468 Mon Sep 17 00:00:00 2001 From: Stig-Johnny <7141115+Stig-Johnny@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:47:18 +0000 Subject: [PATCH 6/6] docs: prevent clipping in Mermaid use-case labels --- docs/diagrams/required-environment.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/diagrams/required-environment.md b/docs/diagrams/required-environment.md index 4faa3e3..6b01876 100644 --- a/docs/diagrams/required-environment.md +++ b/docs/diagrams/required-environment.md @@ -5,16 +5,20 @@ The webshop has a test shop called `staging` and a live shop called `production`. A release engineer configures CI once to require evidence that the review checked production. Developers see the result on each checkout pull request. ```mermaid +--- +config: + htmlLabels: false +--- flowchart LR accTitle: Who uses the production review requirement? accDescr: The release engineer configures the requirement, CI checks the review for production coverage, and the checkout developer reads the result on the pull request. engineer["Release engineer"] ci["Webshop CI"] - developer["Checkout developer"] - subgraph workflow["Webshop pull-request workflow"] - policy(["Require evidence that the review
checked the live shop"]) - verify(["Check the review for
production coverage"]) - result(["Read the result and
any failure reason"]) + developer["Developer"] + subgraph workflow["Checkout pull request"] + policy(["Require production"]) + verify(["Check coverage"]) + result(["Read CI result"]) end engineer --- policy ci --- verify