From 18e16ca10d8405c5b0ef05ee3b68ab27fb2e93dd Mon Sep 17 00:00:00 2001 From: Ganesh Sarkaar Date: Fri, 27 Nov 2026 21:57:16 +0530 Subject: [PATCH] Preserve transient OIDC issuer errors across CI startup and renewal --- src/api.rs | 32 +++++++-- src/github_actions.rs | 106 +++++++++++++++++++++++------ src/lib.rs | 153 +++++++++++++++++++++++++++++++++++++++++- tests/http.rs | 15 ++++- 4 files changed, 278 insertions(+), 28 deletions(-) diff --git a/src/api.rs b/src/api.rs index 4f84754..b37ae3f 100644 --- a/src/api.rs +++ b/src/api.rs @@ -45,19 +45,20 @@ pub enum ApiError { /// A CI job's credential could not be renewed before a request: the /// runner issued no identity, or the exchange named another organization. #[error("could not renew this job's credential: {reason}")] - Renewal { reason: String }, + Renewal { transient: bool, reason: String }, } impl ApiError { /// Whether another read could succeed: the request did not reach - /// Proofline or timed out, or Proofline answered with a 5xx status. A - /// refusal, an unreadable answer and a credential that could not be - /// renewed are not. + /// Proofline or timed out, Proofline answered with a 5xx status, or the + /// runner's OIDC issuer failed transiently during renewal. A refusal, an + /// unreadable answer and a permanent renewal failure are not. pub(crate) const fn transient(&self) -> bool { match self { Self::Transport { .. } => true, Self::Problem { status, .. } => *status >= 500, - Self::Protocol { .. } | Self::Renewal { .. } => false, + Self::Renewal { transient, .. } => *transient, + Self::Protocol { .. } => false, } } } @@ -144,6 +145,27 @@ impl ApiError { Self::Transport { .. } | Self::Protocol { .. } | Self::Renewal { .. } => None, } } + + /// Reattributes an error from a non-Proofline upstream such as GitHub Actions. + pub(crate) fn with_origin(self, upstream: impl Into) -> Self { + let origin = upstream.into(); + match self { + Self::Problem { + status, + detail, + code, + .. + } => Self::Problem { + origin, + status, + detail, + code, + }, + Self::Transport { reason, .. } => Self::Transport { origin, reason }, + Self::Protocol { reason, .. } => Self::Protocol { origin, reason }, + Self::Renewal { .. } => self, + } + } } #[derive(Deserialize)] diff --git a/src/github_actions.rs b/src/github_actions.rs index 8022934..79392ad 100644 --- a/src/github_actions.rs +++ b/src/github_actions.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use std::time::Duration; -use anyhow::{Context as _, anyhow, bail}; +use anyhow::{Context as _, bail}; use secrecy::{ExposeSecret as _, SecretString}; use serde::Deserialize; use uuid::Uuid; @@ -48,7 +48,7 @@ impl Issuer { } /// A newly issued OIDC token whose audience is this origin's CI routes. - async fn token(&self, http: &Http) -> anyhow::Result { + async fn token(&self, http: &Http) -> Result { let mut request_url = self.url.clone(); request_url .query_pairs_mut() @@ -59,21 +59,15 @@ impl Issuer { .bearer_auth(self.token.expose_secret()), ) .await - .map_err(|error| { - let reason = match error { - ApiError::Transport { reason, .. } => reason, - other => other.to_string(), - }; - anyhow!("GitHub Actions could not issue the job's OIDC token: {reason}") - })?; + .map_err(|error| error.with_origin("GitHub Actions"))?; if !reply.status.is_success() { - bail!( - "GitHub Actions refused to issue the job's OIDC token with HTTP {}", - reply.status - ); + return Err(http.problem(&reply).with_origin("GitHub Actions")); } - let issued: IssuedToken = serde_json::from_slice(&reply.body) - .map_err(|_| anyhow!("GitHub Actions sent a malformed OIDC token response"))?; + let issued: IssuedToken = + serde_json::from_slice(&reply.body).map_err(|_| ApiError::Protocol { + origin: "GitHub Actions".to_owned(), + reason: "the OIDC token response is malformed".to_owned(), + })?; Ok(SecretString::from(issued.value)) } } @@ -210,6 +204,10 @@ struct Exchanged { /// lifetime when that is shorter. const RENEW_BEFORE: Duration = Duration::from_secs(5 * 60); +/// Minimum delay before renewing when clock skew makes `expires_at <= now`, +/// preventing a tight OIDC re-issuance loop on every poll. +const SKEWED_RENEW_FLOOR: Duration = Duration::from_secs(30); + /// Exchanges a runner-issued `identity` for a read credential. A /// `pull_request_head` is exchanged only if it is the pull request's live /// head; otherwise the exchange refuses and names the head to rerun at. @@ -236,9 +234,18 @@ async fn exchange( let exchanged: Exchanged = serde_json::from_slice(&reply.body).map_err(|_| malformed())?; let expires_at = unix_seconds(&exchanged.expires_at).ok_or_else(malformed)?; let now = i64::try_from(crate::device::now()).map_err(|_| malformed())?; - let lifetime = Duration::from_secs(u64::try_from(expires_at - now).unwrap_or(0)); + let seconds = expires_at + .checked_sub(now) + .and_then(|remaining| u64::try_from(remaining).ok()) + .unwrap_or(0); + let lifetime = Duration::from_secs(seconds); + let renew_after = if lifetime.is_zero() { + SKEWED_RENEW_FLOOR + } else { + lifetime.saturating_sub(RENEW_BEFORE.min(lifetime / 2)) + }; let renew_at = tokio::time::Instant::now() - .checked_add(lifetime.saturating_sub(RENEW_BEFORE.min(lifetime / 2))) + .checked_add(renew_after) .ok_or_else(malformed)?; let lease = Lease { token: SecretString::from(exchanged.token), @@ -298,8 +305,9 @@ pub struct Renewal { impl Renewal { /// The current credential, exchanged again once it is due for renewal. - /// A refused renewal, or one that names another organization, ends the - /// caller's request with [`ApiError::Renewal`] or the exchange's own error. + /// A failed renewal, or one that names another organization, ends the + /// caller's request with [`ApiError::Renewal`] or the exchange's own error; + /// transient issuer failures stay transient. pub(crate) async fn token(&self) -> Result { let mut lease = self.lease.lock().await; if tokio::time::Instant::now() >= lease.renew_at { @@ -308,12 +316,14 @@ impl Renewal { .token(&self.http) .await .map_err(|error| ApiError::Renewal { + transient: error.transient(), reason: format!("{error:#}"), })?; let (organization_id, renewed) = exchange(&self.http, &identity, self.pull_request_head.as_deref()).await?; if organization_id != self.organization_id { return Err(ApiError::Renewal { + transient: false, reason: format!( "the exchange named organization {organization_id}, not {}", self.organization_id @@ -407,3 +417,61 @@ impl ReviewRequest { Ok(requested.review_id) } } + +#[cfg(test)] +mod tests { + use axum::routing::{get, post}; + use axum::{Json, Router}; + use serde_json::json; + + use super::*; + use crate::origin::Origin; + + #[tokio::test] + async fn exchange_clamps_past_expiry_without_overflow_or_immediate_renewal() { + for expires_at in ["1970-01-01T00:00:00Z", "0000-01-01T00:00:00Z"] { + let app = Router::new() + .route( + "/github/token", + get(|| async { Json(json!({ "value": "job-identity" })) }), + ) + .route( + "/api/v1/ci/github-actions/credentials", + post(move || async move { + Json(json!({ + "organization_id": "0190f3a0-0000-7000-8000-000000000001", + "token": "plj_skewed", + "expires_at": expires_at, + })) + }), + ); + 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 http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); + let (_, lease) = exchange(&http, &SecretString::from("job-identity"), None) + .await + .unwrap(); + assert!( + lease.renew_at > tokio::time::Instant::now(), + "{expires_at} should delay renewal rather than tight-looping" + ); + } + } + + #[tokio::test] + async fn malformed_oidc_response_names_github_actions_and_is_not_transient() { + let app = Router::new().route("/github/token", get(|| async { "not json" })); + 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 http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); + let issuer = Issuer::new( + format!("{origin}/github/token").parse().unwrap(), + SecretString::from("runner-secret"), + ); + let error = issuer.token(&http).await.unwrap_err(); + assert!(!error.transient(), "{error:#}"); + assert!(error.to_string().contains("GitHub Actions"), "{error:#}"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 0fd8d78..ac4cea3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1820,21 +1820,43 @@ mod tests { start: tokio::time::Instant, grant: Grant, exchange: Exchange, + ) -> (String, Arc>>) { + console_with(start, grant, exchange, &[]).await + } + + async fn console_with( + start: tokio::time::Instant, + grant: Grant, + exchange: Exchange, + issuer_statuses: &[u16], ) -> (String, Arc>>) { let issued = Arc::new(Mutex::new(0_u32)); let exchanged = Arc::new(Mutex::new(0_u32)); + let exchanged_for_deploys = Arc::clone(&exchanged); + let issuer_statuses = issuer_statuses.to_vec(); let app = Router::new() .route( "/github/token", get(move || { let issued = Arc::clone(&issued); + let issuer_statuses = issuer_statuses.clone(); async move { let number = { let mut issued = issued.lock().unwrap(); *issued += 1; *issued }; - Json(json!({ "value": format!("job-identity-{number}") })) + let status = issuer_statuses + .get(usize::try_from(number - 1).unwrap()) + .or_else(|| issuer_statuses.last()) + .copied() + .unwrap_or(200); + if status != 200 { + let status = axum::http::StatusCode::from_u16(status).unwrap(); + return (status, Json(json!({ "message": "oidc unavailable" }))) + .into_response(); + } + Json(json!({ "value": format!("job-identity-{number}") })).into_response() } }), ) @@ -1903,6 +1925,37 @@ mod tests { })) }), ) + .route( + &format!( + "/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/commits/{HEAD}/deploy-verifications" + ), + get(move || { + let exchanged = Arc::clone(&exchanged_for_deploys); + async move { + let count = *exchanged.lock().unwrap(); + let twenty_min = (count >= 2).then_some("HEALTHY"); + Json(json!({ + "recorded": true, + "deploys": [{ + "environment_id": "0190f3a0-0000-7000-8000-0000000000e0", + "github_environment": "production", + "deployment_task": "deploy", + "workflow_run_id": 7, + "workflow_run_attempt": 1, + "workflow_run_attempts": [1], + "state": "NOT_YET_DUE", + "regressed": false, + "checkpoints": [ + { "checkpoint": "LANDING", "result": "HEALTHY", "due_at": "2026-11-21T00:00:00Z" }, + { "checkpoint": "MINUTES_20", "result": twenty_min, "due_at": "2026-11-21T00:20:00Z" } + ], + "gaps": [], + "deploy_url": "https://console.proofline.example/deploys/1", + }] + })) + } + }), + ) .route( &format!("/api/v1/organizations/{ORG}/reviews/{REQUESTED}"), get(move || async move { @@ -2046,6 +2099,14 @@ mod tests { async fn pull_request_job( grant: Grant, exchange: Exchange, + ) -> (anyhow::Result, Vec) { + pull_request_job_with(grant, exchange, &[]).await + } + + async fn pull_request_job_with( + grant: Grant, + exchange: Exchange, + issuer_statuses: &[u16], ) -> (anyhow::Result, Vec) { // As in the test above, a 10 ms ticker bounds each jump of the clock. let ticker = tokio::spawn(async { @@ -2054,7 +2115,7 @@ mod tests { } }); let start = tokio::time::Instant::now(); - let (origin, received) = console(start, grant, exchange).await; + let (origin, received) = console_with(start, grant, exchange, issuer_statuses).await; let http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); let issuer = github_actions::Issuer::new( format!("{origin}/github/token").parse().unwrap(), @@ -2164,6 +2225,94 @@ mod tests { } } + /// Runner OIDC 5xx outages at startup or renewal keep `Unavailable` (exit 4) + /// attribution to GitHub Actions, while runner 4xx refusals remain non-transient (exit 1). + #[tokio::test(start_paused = true)] + async fn oidc_issuer_outages_remain_unavailable_and_refusals_do_not() { + for (case, exchange, statuses, exit_four) in [ + ("startup 503", HOURLY, &[503][..], true), + ("startup 403", HOURLY, &[403][..], false), + ("renewal 503", Exchange::Grants(100), &[200, 503][..], true), + ("renewal 403", Exchange::Grants(100), &[200, 403][..], false), + ] { + let (verdict, received) = + pull_request_job_with(Grant::Completes, exchange, statuses).await; + let error = verdict.unwrap_err(); + assert_eq!(unavailable(&error), exit_four, "{case}: {error:#}"); + let message = format!("{error:#}"); + assert!(message.contains("GitHub Actions"), "{case}: {message}"); + assert_eq!(review_requests(&received), 0, "{case}: {received:?}"); + } + } + + /// Long `ci deploy` waits renew through transient runner OIDC blips using + /// `FAILED_READS`, fail with exit 4 once exhausted, and abort immediately on 4xx. + #[tokio::test(start_paused = true)] + async fn deploy_wait_tolerates_transient_oidc_renewal_outages_and_aborts_on_refusal() { + let deploy_args = match Cli::try_parse_from([ + "proofline", + "ci", + "deploy", + "--repo", + "acme/app", + "--until", + "20m", + ]) + .unwrap() + .command + { + Command::Ci(CiCommand::Deploy(args)) => args, + other => panic!("{other:?}"), + }; + let run_deploy = |statuses: &'static [u16]| async { + let ticker = tokio::spawn(async { + for _ in 0..1_000_000 { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }); + let start = tokio::time::Instant::now(); + let (origin, received) = + console_with(start, Grant::Completes, Exchange::Grants(100), statuses).await; + let http = Http::new(Origin::parse(&origin).unwrap()).unwrap(); + let issuer = github_actions::Issuer::new( + format!("{origin}/github/token").parse().unwrap(), + SecretString::from("runner-secret"), + ); + let verdict = async { + let api = github_actions::api(http, &issuer, None, None).await?; + deploy::wait(&api, &deploy_args, HEAD, None).await + } + .await; + ticker.abort(); + let received = received.lock().unwrap().clone(); + (verdict, received) + }; + + // Two transient OIDC 503s at renewal stay inside FAILED_READS = 5 and recover. + let (verdict, received) = run_deploy(&[200, 503, 503, 200]).await; + assert_eq!(verdict.unwrap(), Verdict::Done, "{received:?}"); + + // Five consecutive OIDC 503s exhaust FAILED_READS and exit 4 (Unavailable). + let (verdict, received) = run_deploy(&[200, 503]).await; + let error = verdict.unwrap_err(); + assert!(unavailable(&error), "sustained 503: {error:#}"); + let token_calls = received + .iter() + .filter(|(request, ..)| request == "GET /github/token") + .count(); + assert_eq!(token_calls, 6, "{received:?}"); + + // An OIDC 403 refusal aborts on the first failure without spending retries. + let (verdict, received) = run_deploy(&[200, 403]).await; + let error = verdict.unwrap_err(); + assert!(!unavailable(&error), "refused 403: {error:#}"); + let token_calls = received + .iter() + .filter(|(request, ..)| request == "GET /github/token") + .count(); + assert_eq!(token_calls, 2, "{received:?}"); + } + #[test] fn the_wait_wakes_for_a_pending_request_and_never_sleeps_past_the_deadline() { let now = tokio::time::Instant::now(); diff --git a/tests/http.rs b/tests/http.rs index ed8a0c7..6deee50 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -1774,16 +1774,27 @@ async fn failing_exchange(status: StatusCode) -> String { origin } +/// A runner whose OIDC token endpoint answers `status`. +async fn failing_oidc(status: StatusCode) -> String { + let app = Router::new().route("/github/token", get(move || async move { status })); + 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 +} + #[tokio::test] async fn ci_review_in_github_actions_exchanges_the_jobs_oidc_token_for_its_credential() { let (console, requests) = ci_console("PULL_REQUEST", StatusCode::OK, "COMPLETED", None, None).await; - // A refused exchange is the caller's error. One Proofline could not serve - // is an outage, like any other request it fails. + // A refused exchange or runner token request is the caller's error. One + // either upstream could not serve is an outage, like any other request. let cases = [ (console, 0), (failing_exchange(StatusCode::NOT_FOUND).await, 1), (failing_exchange(StatusCode::SERVICE_UNAVAILABLE).await, 4), + (failing_oidc(StatusCode::FORBIDDEN).await, 1), + (failing_oidc(StatusCode::SERVICE_UNAVAILABLE).await, 4), ]; for (origin, code) in cases { let directory = tempfile::tempdir().unwrap();