diff --git a/api/src/client/mod.rs b/api/src/client/mod.rs index 7293c81b..1e2e6a4b 100644 --- a/api/src/client/mod.rs +++ b/api/src/client/mod.rs @@ -4,7 +4,7 @@ use std::sync::mpsc::Sender; use constants::{DEFAULT_ORIGIN, TRUNK_PUBLIC_API_ADDRESS_ENV}; use display::message::DisplayMessage; -use http::{HeaderValue, header::HeaderMap}; +use http::{HeaderName, HeaderValue, header::HeaderMap}; use reqwest::{Client, Response, StatusCode, header}; use serde::de::DeserializeOwned; use tokio::fs; @@ -53,8 +53,13 @@ pub struct ApiClient { pub telemetry_host: String, s3_client: Client, trunk_api_client: Client, - /// Only a client holding an API token can call v2, which takes it as a bearer credential. + /// Holds the run's v2 credential: an API token from the start, or a fork pull request's Trunk + /// login once it has one. trunk_api_v2_client: Option, + /// `--allow-forked-pr-uploads` with no token and no public repo id. + credential_free: bool, + /// A credential-free GitHub Actions fork PR run, which on v2 swaps its `GITHUB_TOKEN` for a login. + github_fork_pull_request: Option, telemetry_client: Client, version_path_prefix: String, org_url_slug: String, @@ -63,6 +68,53 @@ pub struct ApiClient { missing_test_collection: bool, } +/// A GitHub Actions run of a pull request from a fork, as its event payload names it. +pub struct GithubForkPullRequest { + pub number: u64, + /// `pull_request.head.sha`, not `GITHUB_SHA`, which is the merge commit on a PR run. + pub head_sha: String, + /// The job's `GITHUB_TOKEN`, when the step was given it. + pub github_token: Option, +} + +/// What a v2 call presents. The gateway takes only an API key on `Authorization`, so a Trunk login +/// goes on `x-trunk-token` and the two are never sent together. +pub(crate) enum V2Credential { + ApiKey(String), + TrunkLogin(String), +} + +impl V2Credential { + const TRUNK_TOKEN_HEADER: HeaderName = HeaderName::from_static("x-trunk-token"); + + fn client(&self) -> anyhow::Result { + let (name, value, error) = match self { + Self::ApiKey(token) => ( + header::AUTHORIZATION, + format!("Bearer {token}"), + "Trunk API token is not ASCII", + ), + Self::TrunkLogin(jwt) => ( + Self::TRUNK_TOKEN_HEADER, + jwt.clone(), + "Trunk login is not ASCII", + ), + }; + let mut value = HeaderValue::from_str(&value).map_err(|_| anyhow::Error::msg(error))?; + value.set_sensitive(true); + let mut headers = HeaderMap::new(); + headers.append( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + headers.append(name, value); + Ok(Client::builder() + .timeout(ApiClient::TRUNK_API_TIMEOUT) + .default_headers(headers) + .build()?) + } +} + pub fn get_api_host() -> String { std::env::var(TRUNK_PUBLIC_API_ADDRESS_ENV) .ok() @@ -94,8 +146,8 @@ impl ApiClient { // request. Fork PRs can't read repo secrets, so they rely on the public repo id. let api_token = api_token.filter(|token| !token.trim().is_empty()); let public_repo_id = public_repo_id.filter(|id| !id.trim().is_empty()); - // The forked-PR lane presents no credential at all: the collection id already in the - // request authorizes it, gated on that collection's opt-in server-side. + // The forked-PR lane presents no credential at all on v1: the collection id already in + // the request authorizes it, gated on that collection's opt-in server-side. if api_token.is_none() && public_repo_id.is_none() && !allow_forked_pr_uploads { return Err(anyhow::anyhow!( "Either a Trunk API token, a public repo id, or --allow-forked-pr-uploads is required." @@ -160,25 +212,11 @@ impl ApiClient { .build()?; let trunk_api_v2_client = api_token - .as_deref() - .map(|token| { - let mut headers = HeaderMap::new(); - headers.append( - header::CONTENT_TYPE, - HeaderValue::from_static("application/json"), - ); - headers.append( - header::AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {token}")) - .map_err(|_| anyhow::Error::msg("Trunk API token is not ASCII"))?, - ); - Client::builder() - .timeout(Self::TRUNK_API_TIMEOUT) - .default_headers(headers) - .build() - .map_err(anyhow::Error::from) - }) + .clone() + .map(|token| V2Credential::ApiKey(token).client()) .transpose()?; + let credential_free = + allow_forked_pr_uploads && api_token.is_none() && public_repo_id.is_none(); let mut telemetry_client_default_headers = HeaderMap::new(); telemetry_client_default_headers.append( @@ -217,6 +255,8 @@ impl ApiClient { s3_client, trunk_api_client, trunk_api_v2_client, + credential_free, + github_fork_pull_request: None, telemetry_client, version_path_prefix, org_url_slug, @@ -240,6 +280,13 @@ impl ApiClient { self.upload_api_version } + /// Lets a credential-free run of a GitHub Actions fork PR ask for v2. Ignored for any other run. + pub fn set_github_fork_pull_request(&mut self, pull_request: GithubForkPullRequest) { + if self.credential_free { + self.github_fork_pull_request = Some(pull_request); + } + } + /// Which API the run's quarantine lookup and upload use. Every later call follows it. pub fn set_upload_api_version(&mut self, upload_api_version: UploadApiVersion) { self.upload_api_version = upload_api_version; @@ -247,7 +294,8 @@ impl ApiClient { /// Asks Trunk whether this run uses v2. Anything but an explicit `v2`, a failed call /// included, is v1, so this never fails a run. A timeout, a connection error or a 5xx is - /// retried once; any other answer is final. + /// retried once; any other answer is final. Only a run with an API token or a credential-free + /// GitHub Actions fork PR run asks. /// /// A run that names no collection asks too, by its repository: Trunk may answer `v2` with the /// collection it inferred. A `v2` that names none is v1, since every v2 route needs one. A `v1` @@ -265,7 +313,9 @@ impl ApiClient { .as_ref() .and_then(message::named_repo) .is_some(); - let decision = if self.trunk_api_v2_client.is_none() || (requested.is_none() && !has_repo) { + let can_use_v2 = + self.trunk_api_v2_client.is_some() || self.github_fork_pull_request.is_some(); + let decision = if !can_use_v2 || (requested.is_none() && !has_repo) { message::UploadApiDecision::default() } else { match self.request_upload_api_version(request).await { diff --git a/api/src/client/v2.rs b/api/src/client/v2.rs index 97bbc0e0..8608fb46 100644 --- a/api/src/client/v2.rs +++ b/api/src/client/v2.rs @@ -3,9 +3,12 @@ use std::collections::HashSet; use base64::{Engine as _, engine::general_purpose::STANDARD}; use reqwest::{Client, StatusCode}; -use super::{ApiClient, CheckNotFound, CheckUnauthorized, StatusCodeHelp, status_code_help}; +use super::{ + ApiClient, CheckNotFound, CheckUnauthorized, GithubForkPullRequest, StatusCodeHelp, + V2Credential, status_code_help, +}; use crate::call_api::CallApi; -use crate::message; +use crate::message::{self, UploadApiVersion}; use crate::quarantine::{QuarantineLookup, QuarantinedTestSet, QuarantinedTests}; use crate::urls::TestCaseGuidScope; @@ -13,6 +16,85 @@ impl ApiClient { const QUARANTINE_STATUS_MAX_IDENTIFIERS: usize = 2_000; const ALL_QUARANTINED_TESTS_PAGE_SIZE: usize = 25_000; + /// Sets the API the run uses, taking the decision route's answer as given. The one exception is a + /// GitHub Actions fork PR run, which holds no v2 credential: on v2 it swaps the job's + /// `GITHUB_TOKEN` for a Trunk login, and stays on v1's collection lane if that fails. + pub async fn use_upload_api_version(&mut self, version: UploadApiVersion) { + self.upload_api_version = match &self.github_fork_pull_request { + Some(pull_request) + if version == UploadApiVersion::V2 && self.trunk_api_v2_client.is_none() => + { + match self.log_in_github_fork_pull_request(pull_request).await { + Ok(client) => { + self.trunk_api_v2_client = Some(client); + UploadApiVersion::V2 + } + Err(reason) => { + tracing::warn!( + "Could not log in to the Trunk API v2 for this fork pull request ({reason}); uploading with Trunk API v1" + ); + UploadApiVersion::V1 + } + } + } + _ => version, + }; + } + + /// `POST /v2/auth/github-actions/login` with the job's `GITHUB_TOKEN`. The error is a reason + /// fit to log: it never holds the token, the login, or a parse error that could quote them. + async fn log_in_github_fork_pull_request( + &self, + pull_request: &GithubForkPullRequest, + ) -> Result { + let github_token = pull_request + .github_token + .as_deref() + .filter(|token| !token.trim().is_empty()) + .ok_or("GITHUB_TOKEN is not set")?; + let mut url = url::Url::parse(&self.api_host).map_err(|error| error.to_string())?; + url.path_segments_mut() + .map_err(|_| format!("invalid Trunk API address {}", self.api_host))? + .pop_if_empty() + .extend(["v2", "auth", "github-actions", "login"]); + let response = Client::builder() + .timeout(Self::TRUNK_API_TIMEOUT) + .build() + .map_err(|error| error.to_string())? + .post(url) + .header(Self::TRUNK_ALLOW_FORKED_PR_UPLOADS_HEADER, "true") + .json(&message::GithubActionsForkLoginRequest { + github_token, + pull_request_number: pull_request.number, + sha: &pull_request.head_sha, + }) + .send() + .await + .map_err(|error| format!("the request failed: {}", error.without_url()))?; + let status = response.status(); + if status != StatusCode::OK { + let code = response + .json::() + .await + .ok() + .and_then(|refusal| refusal.error.code); + return Err(match code { + Some(code) => format!("Trunk answered {status}, {code}"), + None => format!("Trunk answered {status}"), + }); + } + let login = response + .json::() + .await + .ok() + .filter(|login| !login.jwt.is_empty()) + .ok_or("Trunk's answer could not be read")?; + tracing::debug!("Logged in to the Trunk API v2 until {}", login.expires_at); + V2Credential::TrunkLogin(login.jwt) + .client() + .map_err(|error| error.to_string()) + } + fn v2_client(&self) -> anyhow::Result<&Client> { self.trunk_api_v2_client .as_ref() diff --git a/api/src/message.rs b/api/src/message.rs index e0684164..d456b0b6 100644 --- a/api/src/message.rs +++ b/api/src/message.rs @@ -129,6 +129,28 @@ pub struct GetUploadApiVersionResponse { pub missing_test_collection: bool, } +/// The fork lane's body for `POST /v2/auth/github-actions/login`. It holds the job's +/// `GITHUB_TOKEN`, so it has no `Debug`. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct GithubActionsForkLoginRequest<'a> { + pub github_token: &'a str, + pub pull_request_number: u64, + pub sha: &'a str, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GithubActionsLogin { + pub jwt: String, + pub expires_at: String, +} + +#[derive(Debug, Deserialize)] +pub struct GithubActionsLoginRefusal { + pub error: ClientErrorBody, +} + /// Which API a run uses and, on v2 for a run that named no test collection, the collection Trunk /// inferred from its repository. #[derive(Debug, Clone, PartialEq, Eq, Default)] diff --git a/api/tests/v2_client.rs b/api/tests/v2_client.rs index 846c47dc..5ab0fb29 100644 --- a/api/tests/v2_client.rs +++ b/api/tests/v2_client.rs @@ -1,6 +1,6 @@ use std::{collections::HashSet, time::Duration}; -use api::client::ApiClient; +use api::client::{ApiClient, GithubForkPullRequest}; use api::message::{self, UploadApiCaller, UploadApiDecision, UploadApiVersion}; use api::quarantine::{QuarantineLookup, QuarantinedTestSet, QuarantinedTests}; use api::urls::TestCaseGuidScope; @@ -717,3 +717,292 @@ async fn reports_a_failed_v2_lookup_without_falling_back_to_v1() { .any(|request| matches!(request, RequestPayload::GetQuarantineConfig(_))) ); } + +const LOGIN_ROUTE: &str = "/v2/auth/github-actions/login"; +const HEAD_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; + +fn fork_pull_request(github_token: Option<&str>) -> GithubForkPullRequest { + GithubForkPullRequest { + number: 42, + head_sha: String::from(HEAD_SHA), + github_token: github_token.map(String::from), + } +} + +fn fork_pr_client(state: &SharedMockServerState, github_token: Option<&str>) -> ApiClient { + let mut client = ApiClient::new(None, None, true, "acme", None).unwrap(); + client.api_host.clone_from(&state.host); + client.set_github_fork_pull_request(fork_pull_request(github_token)); + client +} + +fn version_route( + answer: (StatusCode, &'static str), +) -> (&'static str, MethodRouter) { + ( + VERSION_ROUTE, + post( + move |State(state): State, headers: HeaderMap, uri: Uri| async move { + // A fork PR run asks as v1's collection lane does: the opt-in and no credential. + assert_eq!( + headers + .get("x-trunk-allow-forked-pr-uploads") + .and_then(|value| value.to_str().ok()), + Some("true") + ); + assert!(headers.get("x-api-token").is_none()); + state.record_route_request(&headers, &uri, None); + answer + }, + ), + ) +} + +fn login_route( + answer: (StatusCode, &'static str), +) -> (&'static str, MethodRouter) { + ( + LOGIN_ROUTE, + post( + move |State(state): State, + headers: HeaderMap, + uri: Uri, + Json(body): Json| async move { + assert_eq!( + headers + .get("x-trunk-allow-forked-pr-uploads") + .and_then(|value| value.to_str().ok()), + Some("true") + ); + state.record_route_request(&headers, &uri, Some(body)); + answer + }, + ), + ) +} + +const LOGIN: &str = r#"{"jwt":"trunk-jwt","expiresAt":"2026-11-06T17:15:00Z","organization":{"id":"o","slug":"acme","name":"Acme"},"repository":{"id":"r","name":"acme/web"}}"#; + +fn uploads_route() -> (&'static str, MethodRouter) { + ( + UPLOADS_ROUTE, + post( + |State(state): State, headers: HeaderMap, uri: Uri| async move { + state.record_route_request(&headers, &uri, None); + ( + StatusCode::CREATED, + Json(json!({ + "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", + "status": "awaitingData", + "uploadUrl": "https://bundles.example/key?sig=1", + "expiresAt": "2026-10-06T17:00:00.000Z", + "testCollectionUuid": COLLECTION_UUID, + "repositoryId": REPO_ID, + "createdAt": "2026-10-06T16:00:00.000Z", + })), + ) + }, + ), + ) +} + +fn upload_request() -> message::CreateBundleUploadRequest { + message::CreateBundleUploadRequest { + repo: repo(), + org_url_slug: String::from("acme"), + client_version: String::from("trunk-analytics-cli 0.17.0"), + remote_urls: vec![], + external_id: None, + test_collection_short_id: Some(String::from(SHORT_ID)), + } +} + +#[tokio::test] +async fn a_fork_pr_run_on_v2_swaps_its_github_token_and_sends_the_login_on_x_trunk_token() { + let state = serve(vec![ + version_route((StatusCode::OK, r#"{"apiVersion":"v2"}"#)), + login_route((StatusCode::OK, LOGIN)), + quarantine_status_route(true), + all_quarantined_tests_route(true), + uploads_route(), + ]) + .await; + let mut client = fork_pr_client(&state, Some("ghs_job-token")); + + let decision = client + .get_upload_api_version(&version_request(Some(SHORT_ID))) + .await; + client.use_upload_api_version(decision.version).await; + assert_eq!(client.upload_api_version(), UploadApiVersion::V2); + client + .get_quarantining_config(&quarantine_request(vec![failure(0)])) + .await + .unwrap(); + client + .get_quarantined_test_set(&quarantine_request(vec![])) + .await + .unwrap(); + client + .create_bundle_upload(&upload_request()) + .await + .unwrap(); + + let requests = state.route_requests.lock().unwrap().clone(); + let route = |uri: &str| uri.split('?').next().unwrap().to_string(); + let with_login = |path: String| (path, None, Some(String::from("trunk-jwt"))); + assert_eq!( + requests + .iter() + .map(|request| ( + route(&request.uri), + request.authorization.clone(), + request.trunk_token.clone() + )) + .collect::>(), + vec![ + (String::from(VERSION_ROUTE), None, None), + (String::from(LOGIN_ROUTE), None, None), + with_login(format!("/v2/test-collections/{SHORT_ID}/quarantine-status")), + with_login(format!( + "/v2/test-collections/{SHORT_ID}/all-quarantined-tests" + )), + with_login(format!( + "/v2/test-collections/{SHORT_ID}/all-quarantined-tests" + )), + with_login(format!("/v2/test-collections/{SHORT_ID}/uploads")), + ] + ); + assert_eq!( + requests[1].body, + Some(json!({ + "githubToken": "ghs_job-token", + "pullRequestNumber": 42, + "sha": HEAD_SHA, + })) + ); +} + +#[tokio::test] +async fn a_fork_pr_run_stays_on_v1_when_the_swap_is_refused() { + for answer in [ + ( + StatusCode::BAD_REQUEST, + r#"{"error":{"code":"INVALID_ARGUMENT","message":"bad"}}"#, + ), + ( + StatusCode::UNAUTHORIZED, + r#"{"error":{"code":"UNAUTHENTICATED","message":"no"}}"#, + ), + ( + StatusCode::UNPROCESSABLE_ENTITY, + r#"{"error":{"code":"SHA_NOT_PR_HEAD","message":"moved"}}"#, + ), + (StatusCode::BAD_GATEWAY, ""), + (StatusCode::SERVICE_UNAVAILABLE, ""), + (StatusCode::TOO_MANY_REQUESTS, ""), + (StatusCode::OK, r#"{"expiresAt":"2026-11-06T17:15:00Z"}"#), + ] { + let state = serve(vec![login_route(answer)]).await; + let mut client = fork_pr_client(&state, Some("ghs_job-token")); + + client.use_upload_api_version(UploadApiVersion::V2).await; + + assert_eq!( + client.upload_api_version(), + UploadApiVersion::V1, + "{answer:?}" + ); + assert_eq!(uris(&state), vec![LOGIN_ROUTE], "{answer:?}"); + } +} + +#[tokio::test] +async fn a_fork_pr_run_without_github_token_stays_on_v1_without_a_swap() { + for github_token in [None, Some(""), Some(" ")] { + let state = serve(vec![login_route((StatusCode::OK, LOGIN))]).await; + let mut client = fork_pr_client(&state, github_token); + + client.use_upload_api_version(UploadApiVersion::V2).await; + + assert_eq!(client.upload_api_version(), UploadApiVersion::V1); + assert!(uris(&state).is_empty(), "{github_token:?}"); + } +} + +#[tokio::test] +async fn a_fork_pr_run_does_not_swap_on_v1() { + for answer in [ + (StatusCode::OK, r#"{"apiVersion":"v1"}"#), + (StatusCode::UNAUTHORIZED, ""), + ] { + let state = serve(vec![ + version_route(answer), + login_route((StatusCode::OK, LOGIN)), + ]) + .await; + let mut client = fork_pr_client(&state, Some("ghs_job-token")); + + let decision = client + .get_upload_api_version(&version_request(Some(SHORT_ID))) + .await; + client.use_upload_api_version(decision.version).await; + + assert_eq!( + client.upload_api_version(), + UploadApiVersion::V1, + "{answer:?}" + ); + assert_eq!(uris(&state), vec![VERSION_ROUTE], "{answer:?}"); + } +} + +#[tokio::test] +async fn a_credential_free_run_that_is_not_a_fork_pr_never_asks() { + let state = serve(vec![ + version_route((StatusCode::OK, r#"{"apiVersion":"v2"}"#)), + login_route((StatusCode::OK, LOGIN)), + ]) + .await; + let mut client = ApiClient::new(None, None, true, "acme", None).unwrap(); + client.api_host.clone_from(&state.host); + + let decision = client + .get_upload_api_version(&version_request(Some(SHORT_ID))) + .await; + client.use_upload_api_version(decision.version).await; + + assert_eq!(client.upload_api_version(), UploadApiVersion::V1); + assert!(uris(&state).is_empty()); +} + +#[tokio::test] +async fn a_run_with_a_token_never_swaps() { + let state = serve(vec![login_route((StatusCode::OK, LOGIN)), uploads_route()]).await; + let mut client = + ApiClient::new(Some(String::from("org-key")), None, true, "acme", None).unwrap(); + client.api_host.clone_from(&state.host); + client.set_github_fork_pull_request(fork_pull_request(Some("ghs_job-token"))); + + client.use_upload_api_version(UploadApiVersion::V2).await; + client + .create_bundle_upload(&upload_request()) + .await + .unwrap(); + + let requests = state.route_requests.lock().unwrap().clone(); + assert_eq!( + requests + .iter() + .map(|request| ( + request.uri.clone(), + request.authorization.clone(), + request.trunk_token.clone() + )) + .collect::>(), + vec![( + format!("/v2/test-collections/{SHORT_ID}/uploads"), + Some(String::from("Bearer org-key")), + None + )] + ); +} diff --git a/cli/src/upload_command.rs b/cli/src/upload_command.rs index 039c2af7..58b3d188 100644 --- a/cli/src/upload_command.rs +++ b/cli/src/upload_command.rs @@ -3,7 +3,7 @@ use std::env; use std::path::PathBuf; use std::sync::mpsc::Sender; -use api::client::{ApiClient, ApiErrorEndpoint}; +use api::client::{ApiClient, ApiErrorEndpoint, GithubForkPullRequest}; use api::message::{GetUploadApiVersionRequest, UploadApiCaller, UploadApiDecision}; use api::urls::TestCaseGuidScope; use bundle::{BundleMeta, BundlerUtil, QuarantineResolutionMode, unzip_tarball}; @@ -116,7 +116,7 @@ pub struct UploadArgs { #[arg( long, env = constants::TRUNK_ALLOW_FORKED_PR_UPLOADS_ENV, - help = "Allow uploading from a forked pull request, which cannot read repository secrets. Requires --test-collection-id; the collection must have forked-PR uploads enabled in Trunk." + help = "Upload with no Trunk credential, as a forked pull request must since it cannot read repository secrets. Works with no credential on Trunk API v1. On Trunk API v2 it works only for a fork pull request on GitHub Actions, using the job's GITHUB_TOKEN: trunk-io/analytics-uploader passes it by default; when running the CLI directly, set `GITHUB_TOKEN: ${{ github.token }}` on the step. Requires --test-collection-id; the collection must have forked-PR uploads enabled in Trunk." )] pub allow_forked_pr_uploads: bool, #[arg( @@ -590,6 +590,13 @@ pub async fn run_upload( &upload_args.org_url_slug, render_sender, )?; + if upload_args.allow_forked_pr_uploads + && let Some(pull_request) = env::var("GITHUB_EVENT_PATH") + .ok() + .and_then(|event_path| github_fork_pull_request(&event_path)) + { + api_client.set_github_fork_pull_request(pull_request); + } let PreTestContext { mut meta, @@ -643,7 +650,7 @@ pub async fn run_upload( tracing::warn!("{message}"); notices.push(Notice::upload_skipped(message)); } - api_client.set_upload_api_version(upload_api_version); + api_client.use_upload_api_version(upload_api_version).await; api_client.set_missing_test_collection(skip_upload); if let Some(bep_result) = &bep_result { @@ -932,15 +939,39 @@ pub fn is_fork_pr(github_event_path: Option<&str>, envs: &context::env::EnvVars) .is_some_and(|number| !number.is_empty()) } -fn github_event_is_fork_pr(event_path: &str) -> Option { - let event: serde_json::Value = +fn github_event_pull_request(event_path: &str) -> Option { + let mut event: serde_json::Value = serde_json::from_reader(std::fs::File::open(event_path).ok()?).ok()?; - let pull_request = event.get("pull_request")?; + Some(event.get_mut("pull_request")?.take()) +} + +fn pull_request_is_from_fork(pull_request: &serde_json::Value) -> Option { let head = pull_request.pointer("/head/repo/full_name")?.as_str()?; let base = pull_request.pointer("/base/repo/full_name")?.as_str()?; Some(!head.eq_ignore_ascii_case(base)) } +fn github_event_is_fork_pr(event_path: &str) -> Option { + pull_request_is_from_fork(&github_event_pull_request(event_path)?) +} + +/// The fork pull request a GitHub Actions run builds, with the job's `GITHUB_TOKEN`; `None` for +/// any other run. +fn github_fork_pull_request(event_path: &str) -> Option { + let pull_request = github_event_pull_request(event_path)?; + if !pull_request_is_from_fork(&pull_request)? { + return None; + } + Some(GithubForkPullRequest { + number: pull_request.get("number")?.as_u64()?, + head_sha: pull_request + .pointer("/head/sha")? + .as_str()? + .to_ascii_lowercase(), + github_token: env::var("GITHUB_TOKEN").ok(), + }) +} + struct UploadedBundle { tarball: PathBuf, // directory is removed on drop diff --git a/cli/tests/common/command_builder.rs b/cli/tests/common/command_builder.rs index c2aa7657..67497f79 100644 --- a/cli/tests/common/command_builder.rs +++ b/cli/tests/common/command_builder.rs @@ -27,6 +27,7 @@ pub struct UploadArgs { validation_report: Option, dry_run: bool, public_repo_id: Option, + forked_pr: bool, } impl UploadArgs { @@ -53,6 +54,7 @@ impl UploadArgs { validation_report: None, dry_run: false, public_repo_id: None, + forked_pr: false, } } @@ -65,6 +67,9 @@ impl UploadArgs { auth_args.push(String::from("--public-repo-id")); auth_args.push(public_repo_id.clone()); } + None if self.forked_pr => { + auth_args.push(String::from("--allow-forked-pr-uploads")); + } None => { auth_args.push(String::from("--token")); auth_args.push(String::from("test-token")); @@ -581,6 +586,17 @@ impl<'b> CommandBuilder<'b> { self } + /// No credential, as a forked pull request's run has: `--allow-forked-pr-uploads` in place of + /// `--token`. + pub fn forked_pr(&mut self) -> &mut Self { + if let CommandType::Upload { upload_args, .. } | CommandType::Test { upload_args, .. } = + &mut self.command_type + { + upload_args.forked_pr = true; + } + self + } + pub fn repo_url(&mut self, new_value: &str) -> &mut Self { self.command_type.repo_url(new_value); self diff --git a/cli/tests/upload.rs b/cli/tests/upload.rs index 03d8cd05..5aa21288 100644 --- a/cli/tests/upload.rs +++ b/cli/tests/upload.rs @@ -3707,8 +3707,24 @@ async fn a_swift_test_xunit_file_reached_twice_is_uploaded_once() { const V2_UPLOAD_ID: &str = "f47ac10b-58cc-4372-a567-0e02b2c3d479"; const V2_CREATED_AT: &str = "2026-10-06T16:00:00.000Z"; -// (route, collection short id, authorization header) per v2 call -type V2Calls = Arc)>>>; +type V2Call = (String, String, Option, Option); +// (route, collection short id, authorization header, x-trunk-token header) per v2 call +type V2Calls = Arc>>; + +fn v2_call(route: &str, id: String, headers: &axum::http::HeaderMap) -> V2Call { + let header = |name| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(String::from) + }; + ( + String::from(route), + id, + header("authorization"), + header("x-trunk-token"), + ) +} /// A server whose decision route answers `decision`, and which serves the v2 quarantine lookup /// and upload, quarantining every failure. @@ -3731,14 +3747,10 @@ fn v2_mock_server(decision: serde_json::Value) -> (MockServerBuilder, V2Calls) { post(move |Path(id): Path, headers: axum::http::HeaderMap, Json(body): Json| { let calls = calls.clone(); async move { - calls.lock().unwrap().push(( - String::from("quarantine-status"), - id, - headers - .get("authorization") - .and_then(|value| value.to_str().ok()) - .map(String::from), - )); + calls + .lock() + .unwrap() + .push(v2_call("quarantine-status", id, &headers)); let tests: Vec = body["testIdentifiers"] .as_array() .unwrap() @@ -3765,14 +3777,7 @@ fn v2_mock_server(decision: serde_json::Value) -> (MockServerBuilder, V2Calls) { headers: axum::http::HeaderMap| { let calls = calls.clone(); async move { - calls.lock().unwrap().push(( - String::from("uploads"), - id, - headers - .get("authorization") - .and_then(|value| value.to_str().ok()) - .map(String::from), - )); + calls.lock().unwrap().push(v2_call("uploads", id, &headers)); ( StatusCode::CREATED, Json(json!({ @@ -3792,7 +3797,7 @@ fn v2_mock_server(decision: serde_json::Value) -> (MockServerBuilder, V2Calls) { (mock_server_builder, v2_calls) } -fn v2_calls_for(short_id: &str) -> Vec<(String, String, Option)> { +fn v2_calls_for(short_id: &str) -> Vec { ["quarantine-status", "uploads"] .into_iter() .map(|route| { @@ -3800,11 +3805,53 @@ fn v2_calls_for(short_id: &str) -> Vec<(String, String, Option)> { String::from(route), String::from(short_id), Some(String::from("Bearer test-token")), + None, ) }) .collect() } +/// Serves the GitHub Actions login with `answer`, recording each login request's body. +fn github_actions_login_route( + mock_server_builder: &mut MockServerBuilder, + answer: (StatusCode, &'static str), +) -> Arc>> { + use axum::routing::post; + + let logins: Arc>> = Arc::default(); + let recorded = logins.clone(); + mock_server_builder.route( + "/v2/auth/github-actions/login", + post( + move |headers: axum::http::HeaderMap, Json(body): Json| { + assert!(headers.get("authorization").is_none()); + assert!(headers.get("x-trunk-token").is_none()); + recorded.lock().unwrap().push(body); + async move { answer } + }, + ), + ); + logins +} + +/// A GitHub Actions `pull_request` event payload for PR #42, from `head` into `acme/web`. +fn github_pull_request_event(temp_dir: &tempfile::TempDir, head: &str) -> String { + let path = temp_dir.path().join("github-event.json"); + std::fs::write( + &path, + serde_json::json!({ + "pull_request": { + "number": 42, + "head": {"sha": FORK_HEAD_SHA.to_uppercase(), "repo": {"full_name": head}}, + "base": {"repo": {"full_name": "acme/web"}}, + } + }) + .to_string(), + ) + .unwrap(); + path.to_string_lossy().into_owned() +} + fn assert_no_v1_calls(state: &SharedMockServerState) { let requests = state.requests.lock().unwrap().clone(); assert!( @@ -3986,6 +4033,231 @@ async fn upload_on_v1_when_trunk_chooses_v2_but_names_no_collection() { ); } +const GITHUB_ACTIONS_LOGIN: &str = r#"{"jwt":"trunk-jwt","expiresAt":"2026-11-06T17:15:00Z","organization":{"id":"o","slug":"acme","name":"Acme"},"repository":{"id":"r","name":"acme/web"}}"#; +const FORK_HEAD_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; +const GITHUB_TOKEN: &str = "ghs_job-token"; + +fn assert_uploaded_on_the_v1_collection_lane(state: &SharedMockServerState) { + let requests = state.requests.lock().unwrap().clone(); + assert!( + requests + .iter() + .any(|request| matches!(request, RequestPayload::CreateBundleUpload(_))), + "the run must have uploaded on v1" + ); + let headers = state.request_headers.lock().unwrap(); + let upload_headers = headers.get("createBundleUpload").unwrap(); + assert_eq!( + upload_headers + .get("x-trunk-allow-forked-pr-uploads") + .and_then(|value| value.to_str().ok()), + Some("true") + ); + assert!(upload_headers.get("x-api-token").is_none()); +} + +// NOTE: must be multi threaded to start a mock server +#[tokio::test(flavor = "multi_thread")] +async fn upload_a_fork_pr_run_on_v2_with_its_github_actions_login() { + let temp_dir = tempdir().unwrap(); + generate_mock_git_repo(&temp_dir); + generate_mock_valid_junit_xmls_with_failures(&temp_dir); + + let (mut mock_server_builder, v2_calls) = + v2_mock_server(serde_json::json!({"apiVersion": "v2"})); + let logins = github_actions_login_route( + &mut mock_server_builder, + (StatusCode::OK, GITHUB_ACTIONS_LOGIN), + ); + let state = mock_server_builder.spawn_mock_server().await; + + CommandBuilder::upload(temp_dir.path(), state.host.clone()) + .verbose(true) + .forked_pr() + .command() + .arg("--test-collection-id") + .arg("aB3xY9kQ") + .env( + "GITHUB_EVENT_PATH", + github_pull_request_event(&temp_dir, "someone/web"), + ) + .env("GITHUB_TOKEN", GITHUB_TOKEN) + .assert() + // every failure is quarantined + .success() + .stderr(predicate::str::contains(GITHUB_TOKEN).not()) + .stderr(predicate::str::contains("trunk-jwt").not()); + + assert_eq!( + logins.lock().unwrap().clone(), + vec![serde_json::json!({ + "githubToken": GITHUB_TOKEN, + "pullRequestNumber": 42, + "sha": FORK_HEAD_SHA, + })] + ); + assert_eq!( + v2_calls.lock().unwrap().clone(), + ["quarantine-status", "uploads"] + .into_iter() + .map(|route| ( + String::from(route), + String::from("aB3xY9kQ"), + None, + Some(String::from("trunk-jwt")), + )) + .collect::>() + ); + assert_no_v1_calls(&state); +} + +#[rstest::rstest] +#[case::unauthorized( + StatusCode::UNAUTHORIZED, + r#"{"error":{"code":"UNAUTHENTICATED","message":"unauthenticated"}}"#, + "401 Unauthorized, UNAUTHENTICATED" +)] +#[case::moved_head( + StatusCode::UNPROCESSABLE_ENTITY, + r#"{"error":{"code":"SHA_NOT_PR_HEAD","message":"the head moved"}}"#, + "422 Unprocessable Entity, SHA_NOT_PR_HEAD" +)] +#[case::github_down(StatusCode::SERVICE_UNAVAILABLE, "", "503 Service Unavailable")] +#[case::rate_limited(StatusCode::TOO_MANY_REQUESTS, "", "429 Too Many Requests")] +#[tokio::test(flavor = "multi_thread")] +async fn upload_a_fork_pr_run_on_v1_when_its_swap_is_refused( + #[case] status: StatusCode, + #[case] body: &'static str, + #[case] reason: &str, +) { + let temp_dir = tempdir().unwrap(); + generate_mock_git_repo(&temp_dir); + generate_mock_valid_junit_xmls(&temp_dir); + + let (mut mock_server_builder, v2_calls) = + v2_mock_server(serde_json::json!({"apiVersion": "v2"})); + let logins = github_actions_login_route(&mut mock_server_builder, (status, body)); + let state = mock_server_builder.spawn_mock_server().await; + + CommandBuilder::upload(temp_dir.path(), state.host.clone()) + .verbose(true) + .forked_pr() + .command() + .arg("--test-collection-id") + .arg("aB3xY9kQ") + .env("GITHUB_EVENT_PATH", github_pull_request_event(&temp_dir, "someone/web")) + .env("GITHUB_TOKEN", GITHUB_TOKEN) + .assert() + .stderr(predicate::str::contains(format!( + "Could not log in to the Trunk API v2 for this fork pull request (Trunk answered {reason}); uploading with Trunk API v1" + ))) + .stderr(predicate::str::contains(GITHUB_TOKEN).not()); + + assert_eq!(logins.lock().unwrap().len(), 1); + assert!(v2_calls.lock().unwrap().is_empty()); + assert_uploaded_on_the_v1_collection_lane(&state); +} + +// NOTE: must be multi threaded to start a mock server +#[tokio::test(flavor = "multi_thread")] +async fn upload_a_fork_pr_run_without_github_token_on_v1() { + let temp_dir = tempdir().unwrap(); + generate_mock_git_repo(&temp_dir); + generate_mock_valid_junit_xmls(&temp_dir); + + let (mut mock_server_builder, v2_calls) = + v2_mock_server(serde_json::json!({"apiVersion": "v2"})); + let logins = github_actions_login_route( + &mut mock_server_builder, + (StatusCode::OK, GITHUB_ACTIONS_LOGIN), + ); + let state = mock_server_builder.spawn_mock_server().await; + + CommandBuilder::upload(temp_dir.path(), state.host.clone()) + .verbose(true) + .forked_pr() + .command() + .arg("--test-collection-id") + .arg("aB3xY9kQ") + .env( + "GITHUB_EVENT_PATH", + github_pull_request_event(&temp_dir, "someone/web"), + ) + .env_remove("GITHUB_TOKEN") + .assert() + .stderr(predicate::str::contains("(GITHUB_TOKEN is not set)")); + + assert!(logins.lock().unwrap().is_empty()); + assert!(v2_calls.lock().unwrap().is_empty()); + assert_uploaded_on_the_v1_collection_lane(&state); +} + +// NOTE: must be multi threaded to start a mock server +#[tokio::test(flavor = "multi_thread")] +async fn upload_a_credential_free_run_that_is_not_a_fork_pr_on_v1() { + let temp_dir = tempdir().unwrap(); + generate_mock_git_repo(&temp_dir); + generate_mock_valid_junit_xmls(&temp_dir); + + let (mut mock_server_builder, v2_calls) = + v2_mock_server(serde_json::json!({"apiVersion": "v2"})); + let logins = github_actions_login_route( + &mut mock_server_builder, + (StatusCode::OK, GITHUB_ACTIONS_LOGIN), + ); + let state = mock_server_builder.spawn_mock_server().await; + + CommandBuilder::upload(temp_dir.path(), state.host.clone()) + .verbose(true) + .forked_pr() + .command() + .arg("--test-collection-id") + .arg("aB3xY9kQ") + .env( + "GITHUB_EVENT_PATH", + github_pull_request_event(&temp_dir, "acme/web"), + ) + .env("GITHUB_TOKEN", GITHUB_TOKEN) + .assert(); + + assert!(logins.lock().unwrap().is_empty()); + assert!(v2_calls.lock().unwrap().is_empty()); + // Trunk would have answered v2, which this run has no credential for: it never asked. + assert_uploaded_on_the_v1_collection_lane(&state); +} + +// NOTE: must be multi threaded to start a mock server +#[tokio::test(flavor = "multi_thread")] +async fn upload_with_a_token_and_allow_forked_pr_uploads_never_swaps() { + let temp_dir = tempdir().unwrap(); + generate_mock_git_repo(&temp_dir); + generate_mock_valid_junit_xmls_with_failures(&temp_dir); + + let (mut mock_server_builder, v2_calls) = + v2_mock_server(serde_json::json!({"apiVersion": "v2"})); + let logins = github_actions_login_route( + &mut mock_server_builder, + (StatusCode::OK, GITHUB_ACTIONS_LOGIN), + ); + let state = mock_server_builder.spawn_mock_server().await; + + CommandBuilder::upload(temp_dir.path(), state.host.clone()) + .command() + .arg("--allow-forked-pr-uploads") + .arg("--test-collection-id") + .arg("aB3xY9kQ") + .env( + "GITHUB_EVENT_PATH", + github_pull_request_event(&temp_dir, "someone/web"), + ) + .env("GITHUB_TOKEN", GITHUB_TOKEN) + .assert() + .success(); + + assert!(logins.lock().unwrap().is_empty()); + assert_eq!(v2_calls.lock().unwrap().clone(), v2_calls_for("aB3xY9kQ")); +} + // A debug log emitted while setting up the API client, so it only shows up with `--verbose`. const DEBUG_LOG_MARKER: &str = "Using public api address"; diff --git a/test_utils/src/mock_server.rs b/test_utils/src/mock_server.rs index 7bf02d5c..680c94fe 100644 --- a/test_utils/src/mock_server.rs +++ b/test_utils/src/mock_server.rs @@ -61,6 +61,7 @@ pub struct MockServerState { pub struct RouteRequest { pub uri: String, pub authorization: Option, + pub trunk_token: Option, pub body: Option, } @@ -71,12 +72,16 @@ impl MockServerState { uri: &axum::http::Uri, body: Option, ) { + let header = |name| { + headers + .get(name) + .and_then(|value| value.to_str().ok()) + .map(String::from) + }; self.route_requests.lock().unwrap().push(RouteRequest { uri: uri.to_string(), - authorization: headers - .get("authorization") - .and_then(|value| value.to_str().ok()) - .map(String::from), + authorization: header("authorization"), + trunk_token: header("x-trunk-token"), body, }); }