diff --git a/README.md b/README.md index 6a124c3..b179bf5 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ 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. +`proofline ci failures --review REVIEW_ID` reads the recorded causes of failed GitHub Actions jobs for a retained pull-request review. It names the reviewed commit and observation time, then one line per job with its attempt, first failed step and cause: caused by the change, already failing on the merge base, flaky or infrastructure, environment state, or not diagnosed. An undiagnosed job shows why: GitHub returned no log, the log was too large or could not cross the credential mask, the attribution decision was unavailable or ran in shadow, or no cause was applied. Timed-out attempts stay in the list. It also says when the pull request's head has moved past the reviewed commit or could not be confirmed, and reports omitted jobs and failed run attempts with pending or unfinished diagnoses. An absent observation or empty job list still exits 0 and says that no cause can be named; a malformed observation or a review that is not a pull request exits 1. + +The command needs `reviews:read` and reads a retained review by UUID, checking that the server answered with that review. It starts no review, picks no commit and needs no checkout. `PROOFLINE_TOKEN` takes precedence; without it, a GitHub Actions job with `id-token: write` uses its OIDC identity, exchanged for a credential bound to the job's repository and used only for reads. A stored sign-in works too. The output is the observation the token may see on that retained review, with no source sent or stored; `proofline findings --review REVIEW_ID --json` prints the full review document. Exit 0 means the inspection succeeded, including when a job failed. A refused, malformed or unauthorized request exits 1, and a connection failure or server outage exits 4. + 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/ci_failures.rs b/src/ci_failures.rs new file mode 100644 index 0000000..afa79aa --- /dev/null +++ b/src/ci_failures.rs @@ -0,0 +1,185 @@ +//! Failed CI jobs as recorded in a pull request's dated observation. + +use std::io::{self, Write}; + +use anyhow::{Context as _, bail}; +use serde::Deserialize; +use uuid::Uuid; + +use crate::api::Api; +use crate::text::one_line; +use crate::{Verdict, read_review_once}; + +/// The pull request review's dated account of its failed CI jobs. The fields +/// that may be absent are optional so an older observation still reads. +#[derive(Deserialize)] +struct Observation { + observed_at: String, + head_state: String, + #[serde(default)] + reviewed_head_sha: Option, + #[serde(default)] + current_head_sha: Option, + #[serde(default)] + ci_failures: Vec, + #[serde(default)] + ci_failures_omitted: u64, + #[serde(default)] + ci_runs_pending: u64, + #[serde(default)] + ci_runs_unfinished: u64, +} + +#[derive(Deserialize)] +struct FailedJob { + job_name: String, + run_attempt: u64, + #[serde(default)] + timed_out: bool, + #[serde(default)] + failed_step: Option, + attribution: String, + #[serde(default)] + undiagnosed: Option, +} + +pub(super) async fn show(api: &Api, review: Uuid) -> anyhow::Result { + let (raw, detail, _) = read_review_once(api, review, false).await?; + if detail.kind != "PULL_REQUEST" { + bail!( + "review {review} has kind {}; CI failure inspection requires a retained pull request review", + one_line(&detail.kind) + ); + } + let mut out = io::stdout().lock(); + let Some(observation) = read_observation(&raw, &mut out)? else { + return Ok(Verdict::Done); + }; + + match observation.head_state.as_str() { + "CURRENT" => writeln!( + out, + "Reviewed head: {}", + head(observation.reviewed_head_sha.as_deref()) + )?, + "OUTDATED" => { + writeln!( + out, + "Reviewed head: {} (PR head has moved; observation is stale)", + head(observation.reviewed_head_sha.as_deref()) + )?; + writeln!( + out, + "Current head: {}", + head(observation.current_head_sha.as_deref()) + )?; + } + "UNKNOWN" => writeln!( + out, + "Reviewed head: {} (PR head could not be confirmed)", + head(observation.reviewed_head_sha.as_deref()) + )?, + state => writeln!( + out, + "Reviewed head: {} (PR head could not be confirmed; head state {})", + head(observation.reviewed_head_sha.as_deref()), + one_line(state) + )?, + } + writeln!(out, "Observed at: {}", one_line(&observation.observed_at))?; + + if observation.ci_failures.is_empty() { + writeln!(out, "No CI job diagnoses are listed.")?; + } + for job in &observation.ci_failures { + let timed_out = if job.timed_out { ", timed out" } else { "" }; + writeln!( + out, + "Job {} (attempt {}{}): {}", + one_line(&job.job_name), + job.run_attempt, + timed_out, + cause(&job.attribution, job.undiagnosed.as_deref()) + )?; + if let Some(step) = &job.failed_step { + writeln!(out, " Failed step: {}", one_line(step))?; + } + } + if observation.ci_failures_omitted > 0 { + writeln!( + out, + "Additional diagnosed jobs omitted: {}", + observation.ci_failures_omitted + )?; + } + if observation.ci_runs_pending > 0 { + writeln!( + out, + "Failed run attempts awaiting diagnosis: {}", + observation.ci_runs_pending + )?; + } + if observation.ci_runs_unfinished > 0 { + writeln!( + out, + "Failed run attempts with unfinished diagnoses: {}", + observation.ci_runs_unfinished + )?; + } + Ok(Verdict::Done) +} + +/// A missing or null observation is a valid answer from the review. A +/// malformed observation is an error and must not be reported as empty. +fn read_observation( + raw: &serde_json::Value, + out: &mut W, +) -> anyhow::Result> { + match raw.get("open_items_observation") { + None | Some(serde_json::Value::Null) => { + writeln!( + out, + "No CI failure observation is recorded; CI status cannot be established from this review." + )?; + Ok(None) + } + Some(value) => Observation::deserialize(value) + .context("reading the review’s CI failure observation") + .map(Some), + } +} + +fn head(sha: Option<&str>) -> String { + sha.map_or_else(|| "unknown".to_owned(), one_line) +} + +fn cause(attribution: &str, undiagnosed: Option<&str>) -> String { + match attribution { + "CAUSED_BY_CHANGE" => "caused by the change".to_owned(), + "PRE_EXISTING_ON_BASE" => "already failing on the merge base".to_owned(), + "FLAKY_OR_INFRASTRUCTURE" => "flaky or infrastructure".to_owned(), + "ENVIRONMENT_STATE" => "environment state".to_owned(), + "UNKNOWN" => undiagnosed.map_or_else( + || "not diagnosed; no reason recorded".to_owned(), + |reason| format!("not diagnosed: {}", undiagnosed_reason(reason)), + ), + other => one_line(other), + } +} + +fn undiagnosed_reason(reason: &str) -> String { + let readable = match reason { + "LOG_UNAVAILABLE" => "GitHub returned no log for the job", + "LOG_TOO_LARGE" => "the complete log exceeds the read bound", + "LOG_NOT_ADMITTED" => { + "the log could not cross the credential mask or protected-value admission" + } + "DECISION_UNAVAILABLE" => { + "the attribution decision fell back: the decision service was unavailable or refused" + } + "SHADOW" => "the attribution decision runs in shadow mode, so its answer is not applied", + "UNDETERMINED" => "the decision applied no cause", + other => return one_line(other), + }; + format!("{readable} ({reason})") +} diff --git a/src/lib.rs b/src/lib.rs index 8bf7a9e..cedf914 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ mod agent; mod annotations; pub mod api; +mod ci_failures; mod config; mod coverage; pub mod credentials; @@ -186,6 +187,16 @@ enum Command { #[derive(Debug, Subcommand)] enum CiCommand { + /// Read the recorded causes of failed CI jobs for a pull-request review. + /// + /// Reads a retained review by UUID with `reviews:read`, starts no review, + /// and needs no commit or checkout. A GitHub Actions job can use its + /// read-only OIDC identity in place of `PROOFLINE_TOKEN`. + Failures { + /// UUID of the retained review to inspect. + #[arg(long, value_name = "REVIEW_ID")] + review: Uuid, + }, /// Wait for the pull-request review of the commit under test and report it. /// /// The job authenticates with `PROOFLINE_TOKEN`. Without it, a GitHub Actions @@ -632,6 +643,15 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let http = Http::new(origin)?; + let result = async { + let api = ci_reader(http, token, cli.org).await?; + ci_failures::show(&api, review).await + } + .await; + ci_ending(result) + } Command::Ci(CiCommand::Review(args)) => { let commit = ci_commit(args.commit.as_deref())?; let http = Http::new(origin)?; @@ -651,14 +671,8 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { - github_actions::api(http, &issuer, cli.org, None).await? - } - (token, _) => connect(http, token, cli.org).await?, - }; + let api = ci_reader(http, token, cli.org).await?; deploy::wait(&api, &args, &commit, reader_run).await } .await; @@ -1498,6 +1512,23 @@ fn ci_commit(flag: Option<&str>) -> anyhow::Result { Ok(git::commit_sha(&raw)?) } +/// Connect for a CI read that never starts a review. `PROOFLINE_TOKEN` wins +/// over GitHub Actions OIDC; without either, the stored sign-in is used. The +/// OIDC exchange binds no pull-request head, so the credential can only read. +async fn ci_reader( + http: Http, + token: Option, + org: Option, +) -> anyhow::Result { + if let Some(token) = token { + return connect(http, Some(token), org).await; + } + match github_actions::Issuer::from_environment() { + Some(issuer) => github_actions::api(http, &issuer, org, None).await, + None => connect(http, None, org).await, + } +} + /// A CI command's result, with a failure that is Proofline's reported as /// unavailable (exit 4) rather than as the caller's error (exit 1). fn ci_ending(result: anyhow::Result) -> anyhow::Result { diff --git a/tests/http.rs b/tests/http.rs index eb15b98..d4b7384 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1369,6 +1369,445 @@ const CI_REPOSITORY: &str = "0190f3a0-0000-7000-8000-0000000000f0"; const CI_REVIEW: &str = "0190f3a0-0000-7000-8000-0000000000f1"; const CI_HEAD: &str = "89abcdef0123456789abcdef0123456789abcdef"; +async fn ci_failures_output(review: Value) -> std::process::Output { + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move |headers: HeaderMap| async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + Json(review) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let output = cli(&origin, &["ci", "failures", "--review", CI_REVIEW]).await; + task.abort(); + output +} + +fn ci_failure_review() -> Value { + json!({ + "id": CI_REVIEW, "kind": "PULL_REQUEST", "status": "COMPLETED", + "assessment_count": 0, "assessments": [], "head_commit_sha": CI_HEAD, + "open_items_observation": { + "observed_at": "2026-10-01T10:00:00Z", "head_state": "CURRENT", + "reviewed_head_sha": CI_HEAD, "current_head_sha": CI_HEAD, + "ci_failures": [{ + "job_name": "linux-integration", "run_attempt": 2, "timed_out": false, + "failed_step": "Run integration tests", "attribution": "CAUSED_BY_CHANGE" + }] + } + }) +} + +#[tokio::test] +async fn ci_failures_distinguishes_a_change_failure_from_a_pre_existing_failure() { + for (attribution, explanation) in [ + ("CAUSED_BY_CHANGE", "caused by the change"), + ("PRE_EXISTING_ON_BASE", "already failing on the merge base"), + ] { + let mut review = ci_failure_review(); + review["open_items_observation"]["ci_failures"][0]["attribution"] = json!(attribution); + let output = ci_failures_output(review).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + for value in [ + CI_HEAD, + "2026-10-01T10:00:00Z", + "linux-integration", + "attempt 2", + "Run integration tests", + explanation, + ] { + assert!(text.contains(value), "missing {value}: {text}"); + } + } +} + +#[tokio::test] +async fn ci_failures_distinguishes_missing_observations_from_incomplete_diagnoses() { + let new_head = "dddddddddddddddddddddddddddddddddddddddd"; + let mut review = ci_failure_review(); + review + .as_object_mut() + .unwrap() + .remove("open_items_observation"); + let output = ci_failures_output(review.clone()).await; + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert!( + String::from_utf8(output.stdout) + .unwrap() + .contains("No CI failure observation") + ); + + review["open_items_observation"] = json!({ + "observed_at": "2026-10-01T10:00:00Z", "head_state": "OUTDATED", + "reviewed_head_sha": CI_HEAD, "current_head_sha": new_head, + "ci_failures_omitted": 2, "ci_runs_pending": 1, "ci_runs_unfinished": 3 + }); + let output = ci_failures_output(review.clone()).await; + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + for value in [ + CI_HEAD, + new_head, + "PR head has moved", + "No CI job diagnoses are listed", + "Additional diagnosed jobs omitted: 2", + "Failed run attempts awaiting diagnosis: 1", + "Failed run attempts with unfinished diagnoses: 3", + ] { + assert!(text.contains(value), "missing {value}: {text}"); + } + + review["open_items_observation"] = json!({ + "observed_at": "2026-10-01T10:00:00Z", "head_state": "UNKNOWN", "ci_failures": [] + }); + let output = ci_failures_output(review).await; + assert!(output.status.success()); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("PR head could not be confirmed")); + assert!(text.contains("No CI job diagnoses are listed")); +} + +#[tokio::test] +async fn ci_failures_explains_an_unknown_cause_with_its_recorded_reason() { + let mut review = ci_failure_review(); + let job = &mut review["open_items_observation"]["ci_failures"][0]; + job["attribution"] = json!("UNKNOWN"); + job["undiagnosed"] = json!("LOG_UNAVAILABLE"); + let output = ci_failures_output(review).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("linux-integration"), "{text}"); + assert!(text.contains("LOG_UNAVAILABLE"), "{text}"); + assert!(text.to_lowercase().contains("no log"), "{text}"); + assert!(!text.contains("caused by the change"), "{text}"); +} + +#[tokio::test] +async fn ci_failures_preserves_a_withheld_timed_out_job_without_a_failed_step() { + let mut review = ci_failure_review(); + let job = &mut review["open_items_observation"]["ci_failures"][0]; + job["job_name"] = json!(""); + job["timed_out"] = json!(true); + job["failed_step"] = Value::Null; + let output = ci_failures_output(review).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains(""), "{text}"); + assert!(text.to_lowercase().contains("timed out"), "{text}"); + assert!(!text.contains("Failed step:"), "{text}"); +} + +#[tokio::test] +async fn ci_failures_renders_future_causes_and_reasons_safely() { + let mut review = ci_failure_review(); + review["open_items_observation"]["ci_failures"] = json!([ + { + "job_name": "future-cause", "run_attempt": 1, "timed_out": false, + "failed_step": null, "attribution": "FUTURE_CAUSE" + }, + { + "job_name": "future-reason", "run_attempt": 1, "timed_out": false, + "failed_step": null, "attribution": "UNKNOWN", + "undiagnosed": "FUTURE_REASON\u{1b}[2J" + } + ]); + let output = ci_failures_output(review).await; + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let text = String::from_utf8(output.stdout).unwrap(); + for value in [ + "future-cause", + "FUTURE_CAUSE", + "future-reason", + "FUTURE_REASON", + ] { + assert!(text.contains(value), "missing {value}: {text}"); + } + assert!(!text.contains('\u{1b}'), "{text}"); + assert!(text.contains('\u{FFFD}'), "{text}"); +} + +/// A console that serves one review detail and records every request, so a +/// test can confirm the exact id was read and nothing else was requested. +async fn ci_failures_console(review: Value) -> (String, Arc>>) { + let seen = Arc::new(Mutex::new(Vec::new())); + let detail_seen = Arc::clone(&seen); + let other_seen = Arc::clone(&seen); + let app = Router::new() + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move |headers: HeaderMap| { + let seen = Arc::clone(&detail_seen); + let review = review.clone(); + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + seen.lock().unwrap().push("GET review".to_owned()); + Json(review) + } + }), + ) + .fallback(move |request: axum::extract::Request| { + let seen = Arc::clone(&other_seen); + async move { + seen.lock() + .unwrap() + .push(format!("{} {}", request.method(), request.uri().path())); + StatusCode::NOT_FOUND + } + }); + 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, seen) +} + +#[tokio::test] +async fn ci_failures_refuses_a_review_whose_id_differs_from_the_request() { + let mut review = ci_failure_review(); + review["id"] = json!(OTHER_REVIEW_ID); + let (origin, requests) = ci_failures_console(review).await; + let output = cli(&origin, &["ci", "failures", "--review", CI_REVIEW]).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_ne!(output.status.code(), Some(0), "{stderr}"); + assert!(stderr.contains("requested review"), "{stderr}"); + assert!(output.stdout.is_empty(), "{stderr}"); + assert!(!stderr.contains(TOKEN)); + assert_eq!( + *requests.lock().unwrap(), + ["GET review"], + "only the exact review id may be read, with no follow-up request" + ); +} + +#[tokio::test] +async fn ci_failures_refuses_a_review_that_is_not_a_pull_request() { + let mut review = ci_failure_review(); + review["kind"] = json!("DEPLOYMENT"); + let output = ci_failures_output(review).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_ne!(output.status.code(), Some(0), "{stderr}"); + assert!(stderr.contains("DEPLOYMENT"), "{stderr}"); + assert!(stderr.to_lowercase().contains("pull"), "{stderr}"); + assert!(output.stdout.is_empty(), "{stderr}"); +} + +#[tokio::test] +async fn ci_failures_distinguishes_a_malformed_observation_from_an_empty_one() { + for observation in [ + json!("not an object"), + json!({"observed_at": "2026-10-01T10:00:00Z", "ci_failures": "not a list"}), + json!({ + "observed_at": "2026-10-01T10:00:00Z", "head_state": "CURRENT", + "ci_failures": [{ + "job_name": "x", "timed_out": false, "run_attempt": "two", + "attribution": "CAUSED_BY_CHANGE" + }] + }), + ] { + let mut review = ci_failure_review(); + review["open_items_observation"] = observation; + let output = ci_failures_output(review).await; + let stderr = String::from_utf8_lossy(&output.stderr); + assert_ne!(output.status.code(), Some(0), "{stderr}"); + assert!(output.stdout.is_empty(), "{stderr}"); + assert!(stderr.contains("observation"), "{stderr}"); + assert!( + !stderr.contains("No CI job diagnoses are listed"), + "{stderr}" + ); + assert!(!stderr.contains(TOKEN)); + } +} + +#[tokio::test] +async fn ci_failures_keeps_refusals_and_outages_distinct_from_an_empty_observation() { + for (status, code) in [ + (StatusCode::UNAUTHORIZED, 1), + (StatusCode::FORBIDDEN, 1), + (StatusCode::SERVICE_UNAVAILABLE, 4), + ] { + let app = Router::new().route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move || async move { + ( + status, + Json(json!({"title": "Unavailable", "status": status.as_u16()})), + ) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let origin = format!("http://{}", listener.local_addr().unwrap()); + let task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let output = cli(&origin, &["ci", "failures", "--review", CI_REVIEW]).await; + task.abort(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(code), "{status}: {stderr}"); + assert!( + !stderr.contains("No CI failure observation"), + "{status}: {stderr}" + ); + assert!(output.stdout.is_empty(), "{status}: {stderr}"); + assert!(!stderr.contains(TOKEN)); + } +} + +/// A console where a GitHub Actions job's only credential is its OIDC token: +/// the runner issues one identity, the exchange grants a read token with no +/// pull-request head, and the review detail is the one read. Every request is +/// recorded so the transport can be checked exactly. +async fn ci_failures_oidc_console(review: Value) -> (String, Arc>>) { + let seen = Arc::new(Mutex::new(Vec::new())); + let token_seen = Arc::clone(&seen); + let exchange_seen = Arc::clone(&seen); + let review_seen = Arc::clone(&seen); + let other_seen = Arc::clone(&seen); + let app = Router::new() + .route( + "/github/token", + get( + move |headers: HeaderMap, + axum::extract::RawQuery(query): axum::extract::RawQuery| { + let seen = Arc::clone(&token_seen); + async move { + assert_eq!(headers[header::AUTHORIZATION], "Bearer runner-secret"); + assert!( + query.unwrap().contains("audience=http%3A%2F%2F"), + "the token must be issued for this origin's CI routes" + ); + seen.lock().unwrap().push("GET /github/token".to_owned()); + Json(json!({ "value": "signed-job-identity" })) + } + }, + ), + ) + .route( + "/api/v1/ci/github-actions/credentials", + post(move |headers: HeaderMap, uri: axum::http::Uri| { + let seen = Arc::clone(&exchange_seen); + async move { + assert_eq!(headers[header::AUTHORIZATION], "Bearer signed-job-identity"); + assert!( + uri.query().is_none(), + "a diagnosis read must not verify a pull-request head" + ); + seen.lock() + .unwrap() + .push("POST /api/v1/ci/github-actions/credentials".to_owned()); + Json(json!({ + "organization_id": ORG, "repository_id": CI_REPOSITORY, + "token": TOKEN, "expires_at": "2099-01-01T00:00:00Z", + })) + } + }), + ) + .route( + &format!("/api/v1/organizations/{ORG}/reviews/{CI_REVIEW}"), + get(move |headers: HeaderMap| { + let seen = Arc::clone(&review_seen); + let review = review.clone(); + async move { + assert_eq!(headers[header::AUTHORIZATION], format!("Bearer {TOKEN}")); + seen.lock().unwrap().push("GET review".to_owned()); + Json(review) + } + }), + ) + .fallback(move |request: axum::extract::Request| { + let seen = Arc::clone(&other_seen); + async move { + seen.lock() + .unwrap() + .push(format!("{} {}", request.method(), request.uri().path())); + StatusCode::NOT_FOUND + } + }); + 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, seen) +} + +#[tokio::test] +async fn ci_failures_reads_with_a_jobs_oidc_token_and_no_checkout() { + let (origin, requests) = ci_failures_oidc_console(ci_failure_review()).await; + let directory = tempfile::tempdir().unwrap(); + let output = tokio::time::timeout( + std::time::Duration::from_secs(15), + tokio::process::Command::new(env!("CARGO_BIN_EXE_proofline")) + .args([ + "--base-url", + &origin, + "--org", + ORG, + "ci", + "failures", + "--review", + CI_REVIEW, + ]) + .env_remove("PROOFLINE_TOKEN") + .env_remove("PROOFLINE_ORGANIZATION_ID") + .env_remove("COMMIT_SHA") + .env_remove("GITHUB_SHA") + .env_remove("GITHUB_EVENT_NAME") + .env_remove("GITHUB_EVENT_PATH") + .env( + "ACTIONS_ID_TOKEN_REQUEST_URL", + format!("{origin}/github/token?api-version=2.0"), + ) + .env("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "runner-secret") + .env("PATH", "") + .current_dir(directory.path()) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{stderr}"); + let text = String::from_utf8(output.stdout).unwrap(); + assert!(text.contains("linux-integration"), "{text}"); + for secret in ["runner-secret", "signed-job-identity", TOKEN] { + assert!(!stderr.contains(secret)); + assert!(!text.contains(secret)); + } + assert_eq!( + *requests.lock().unwrap(), + [ + "GET /github/token", + "POST /api/v1/ci/github-actions/credentials", + "GET review" + ], + "only an OIDC exchange and the one exact review read may happen" + ); +} + #[derive(Debug, Clone, Copy)] struct CiCodeFinding { only: bool,