Skip to content

Commit

Permalink
Better trusted publishing error story (#8633)
Browse files Browse the repository at this point in the history
  • Loading branch information
konstin authored Oct 28, 2024
1 parent e86c52d commit 0044000
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 26 deletions.
40 changes: 33 additions & 7 deletions crates/uv-publish/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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>,
Expand All @@ -247,46 +258,61 @@ pub async fn check_trusted_publishing(
trusted_publishing: TrustedPublishing,
registry: &Url,
client: &BaseClient,
) -> Result<Option<TrustedPublishingToken>, PublishError> {
) -> Result<TrustedPublishResult, PublishError> {
match trusted_publishing {
TrustedPublishing::Automatic => {
// If the user provided credentials, use those.
if username.is_some()
|| 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."
);
}

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),
}
}

Expand Down
6 changes: 0 additions & 6 deletions crates/uv-publish/src/trusted_publishing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,6 @@ impl TrustedPublishingError {
#[serde(transparent)]
pub struct TrustedPublishingToken(String);

impl From<TrustedPublishingToken> 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)
Expand Down
49 changes: 40 additions & 9 deletions crates/uv/src/commands/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
Expand Down Expand Up @@ -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!(
Expand All @@ -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);
Expand Down
67 changes: 63 additions & 4 deletions crates/uv/tests/it/publish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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/
"###
);
}

0 comments on commit 0044000

Please sign in to comment.