From 0044000ed3e8bcf2a1f9b133b2d3b59c9a016271 Mon Sep 17 00:00:00 2001 From: konsti Date: Mon, 28 Oct 2024 21:13:43 +0100 Subject: [PATCH] Better trusted publishing error story (#8633) --- crates/uv-publish/src/lib.rs | 40 +++++++++--- crates/uv-publish/src/trusted_publishing.rs | 6 -- crates/uv/src/commands/publish.rs | 49 ++++++++++++--- crates/uv/tests/it/publish.rs | 67 +++++++++++++++++++-- 4 files changed, 136 insertions(+), 26 deletions(-) diff --git a/crates/uv-publish/src/lib.rs b/crates/uv-publish/src/lib.rs index 5d180a9ef0bc..4820974a5176 100644 --- a/crates/uv-publish/src/lib.rs +++ b/crates/uv-publish/src/lib.rs @@ -54,6 +54,8 @@ pub enum PublishError { PublishSend(PathBuf, Url, #[source] PublishSendError), #[error("Failed to obtain token for trusted publishing")] TrustedPublishing(#[from] TrustedPublishingError), + #[error("{0} are not allowed when using trusted publishing")] + MixedCredentials(String), } /// Failure to get the metadata for a specific file. @@ -239,6 +241,15 @@ pub fn files_for_publishing( Ok(files) } +pub enum TrustedPublishResult { + /// We didn't check for trusted publishing. + Skipped, + /// We checked for trusted publishing and found a token. + Configured(TrustedPublishingToken), + /// We checked for optional trusted publishing, but it didn't succeed. + Ignored(TrustedPublishingError), +} + /// If applicable, attempt obtaining a token for trusted publishing. pub async fn check_trusted_publishing( username: Option<&str>, @@ -247,7 +258,7 @@ pub async fn check_trusted_publishing( trusted_publishing: TrustedPublishing, registry: &Url, client: &BaseClient, -) -> Result, PublishError> { +) -> Result { match trusted_publishing { TrustedPublishing::Automatic => { // If the user provided credentials, use those. @@ -255,28 +266,43 @@ pub async fn check_trusted_publishing( || password.is_some() || keyring_provider != KeyringProviderType::Disabled { - return Ok(None); + return Ok(TrustedPublishResult::Skipped); } // If we aren't in GitHub Actions, we can't use trusted publishing. if env::var(EnvVars::GITHUB_ACTIONS) != Ok("true".to_string()) { - return Ok(None); + return Ok(TrustedPublishResult::Skipped); } // We could check for credentials from the keyring or netrc the auth middleware first, but // given that we are in GitHub Actions we check for trusted publishing first. debug!("Running on GitHub Actions without explicit credentials, checking for trusted publishing"); match trusted_publishing::get_token(registry, client.for_host(registry)).await { - Ok(token) => Ok(Some(token)), + Ok(token) => Ok(TrustedPublishResult::Configured(token)), Err(err) => { // TODO(konsti): It would be useful if we could differentiate between actual errors // such as connection errors and warn for them while ignoring errors from trusted // publishing not being configured. debug!("Could not obtain trusted publishing credentials, skipping: {err}"); - Ok(None) + Ok(TrustedPublishResult::Ignored(err)) } } } TrustedPublishing::Always => { debug!("Using trusted publishing for GitHub Actions"); + + let mut conflicts = Vec::new(); + if username.is_some() { + conflicts.push("a username"); + } + if password.is_some() { + conflicts.push("a password"); + } + if keyring_provider != KeyringProviderType::Disabled { + conflicts.push("the keyring"); + } + if !conflicts.is_empty() { + return Err(PublishError::MixedCredentials(conflicts.join(" and "))); + } + if env::var(EnvVars::GITHUB_ACTIONS) != Ok("true".to_string()) { warn_user_once!( "Trusted publishing was requested, but you're not in GitHub Actions." @@ -284,9 +310,9 @@ pub async fn check_trusted_publishing( } let token = trusted_publishing::get_token(registry, client.for_host(registry)).await?; - Ok(Some(token)) + Ok(TrustedPublishResult::Configured(token)) } - TrustedPublishing::Never => Ok(None), + TrustedPublishing::Never => Ok(TrustedPublishResult::Skipped), } } diff --git a/crates/uv-publish/src/trusted_publishing.rs b/crates/uv-publish/src/trusted_publishing.rs index 18f59b0cb795..6e47f97e0ff0 100644 --- a/crates/uv-publish/src/trusted_publishing.rs +++ b/crates/uv-publish/src/trusted_publishing.rs @@ -45,12 +45,6 @@ impl TrustedPublishingError { #[serde(transparent)] pub struct TrustedPublishingToken(String); -impl From for String { - fn from(token: TrustedPublishingToken) -> Self { - token.0 - } -} - impl Display for TrustedPublishingToken { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) diff --git a/crates/uv/src/commands/publish.rs b/crates/uv/src/commands/publish.rs index 315add475644..6f8b69e257b9 100644 --- a/crates/uv/src/commands/publish.rs +++ b/crates/uv/src/commands/publish.rs @@ -5,13 +5,14 @@ use anyhow::{bail, Context, Result}; use console::Term; use owo_colors::OwoColorize; use std::fmt::Write; +use std::iter; use std::sync::Arc; use std::time::Duration; use tracing::info; use url::Url; use uv_client::{AuthIntegration, BaseClientBuilder, Connectivity, DEFAULT_RETRIES}; use uv_configuration::{KeyringProviderType, TrustedHost, TrustedPublishing}; -use uv_publish::{check_trusted_publishing, files_for_publishing, upload}; +use uv_publish::{check_trusted_publishing, files_for_publishing, upload, TrustedPublishResult}; pub(crate) async fn publish( paths: Vec, @@ -71,15 +72,16 @@ pub(crate) async fn publish( ) .await?; - let (username, password) = if let Some(password) = trusted_publishing_token { - (Some("__token__".to_string()), Some(password.into())) - } else { - if username.is_none() && password.is_none() { - prompt_username_and_password()? + let (username, password) = + if let TrustedPublishResult::Configured(password) = &trusted_publishing_token { + (Some("__token__".to_string()), Some(password.to_string())) } else { - (username, password) - } - }; + if username.is_none() && password.is_none() { + prompt_username_and_password()? + } else { + (username, password) + } + }; if password.is_some() && username.is_none() { bail!( @@ -89,6 +91,35 @@ pub(crate) async fn publish( ); } + if username.is_none() && password.is_none() && keyring_provider == KeyringProviderType::Disabled + { + if let TrustedPublishResult::Ignored(err) = trusted_publishing_token { + // The user has configured something incorrectly: + // * The user forgot to configure credentials. + // * The user forgot to forward the secrets as env vars (or used the wrong ones). + // * The trusted publishing configuration is wrong. + writeln!( + printer.stderr(), + "Note: Neither credentials nor keyring are configured, and there was an error \ + fetching the trusted publishing token. If you don't want to use trusted \ + publishing, you can ignore this error, but you need to provide credentials." + )?; + writeln!( + printer.stderr(), + "{}: {err}", + "Trusted publishing error".red().bold() + )?; + for source in iter::successors(std::error::Error::source(&err), |&err| err.source()) { + writeln!( + printer.stderr(), + " {}: {}", + "Caused by".red().bold(), + source.to_string().trim() + )?; + } + } + } + for (file, raw_filename, filename) in files { let size = fs_err::metadata(&file)?.len(); let (bytes, unit) = human_readable_bytes(size); diff --git a/crates/uv/tests/it/publish.rs b/crates/uv/tests/it/publish.rs index 5cf993871d48..2d62f6a336b9 100644 --- a/crates/uv/tests/it/publish.rs +++ b/crates/uv/tests/it/publish.rs @@ -53,15 +53,43 @@ fn invalid_token() { ); } +/// Emulate a missing `permission` `id-token: write` situation. +#[test] +fn mixed_credentials() { + let context = TestContext::new("3.12"); + + uv_snapshot!(context.filters(), context.publish() + .arg("--username") + .arg("ferris") + .arg("--password") + .arg("ZmVycmlz") + .arg("--publish-url") + .arg("https://test.pypi.org/legacy/") + .arg("--trusted-publishing") + .arg("always") + .arg("../../scripts/links/ok-1.0.0-py3-none-any.whl") + // Emulate CI + .env(EnvVars::GITHUB_ACTIONS, "true") + // Just to make sure + .env_remove(EnvVars::ACTIONS_ID_TOKEN_REQUEST_TOKEN), @r###" + success: false + exit_code: 2 + ----- stdout ----- + + ----- stderr ----- + warning: `uv publish` is experimental and may change without warning + Publishing 1 file to https://test.pypi.org/legacy/ + error: a username and a password are not allowed when using trusted publishing + "### + ); +} + +/// Emulate a missing `permission` `id-token: write` situation. #[test] fn missing_trusted_publishing_permission() { let context = TestContext::new("3.12"); uv_snapshot!(context.filters(), context.publish() - .arg("-u") - .arg("__token__") - .arg("-p") - .arg("dummy") .arg("--publish-url") .arg("https://test.pypi.org/legacy/") .arg("--trusted-publishing") @@ -83,3 +111,34 @@ fn missing_trusted_publishing_permission() { "### ); } + +/// Check the error when there are no credentials provided on GitHub Actions. Is it an incorrect +/// trusted publishing configuration? +#[test] +fn no_credentials() { + let context = TestContext::new("3.12"); + + uv_snapshot!(context.filters(), context.publish() + .arg("--publish-url") + .arg("https://test.pypi.org/legacy/") + .arg("../../scripts/links/ok-1.0.0-py3-none-any.whl") + // Emulate CI + .env(EnvVars::GITHUB_ACTIONS, "true") + // Just to make sure + .env_remove(EnvVars::ACTIONS_ID_TOKEN_REQUEST_TOKEN), @r###" + success: false + exit_code: 2 + ----- stdout ----- + + ----- stderr ----- + warning: `uv publish` is experimental and may change without warning + Publishing 1 file to https://test.pypi.org/legacy/ + Note: Neither credentials nor keyring are configured, and there was an error fetching the trusted publishing token. If you don't want to use trusted publishing, you can ignore this error, but you need to provide credentials. + Trusted publishing error: Environment variable ACTIONS_ID_TOKEN_REQUEST_TOKEN not set, is the `id-token: write` permission missing? + Uploading ok-1.0.0-py3-none-any.whl ([SIZE]) + error: Failed to publish `../../scripts/links/ok-1.0.0-py3-none-any.whl` to https://test.pypi.org/legacy/ + Caused by: Failed to send POST request + Caused by: Missing credentials for https://test.pypi.org/legacy/ + "### + ); +}