From ccf01fff663fe82d9bd8062f48c742b3498c8b3c Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Wed, 10 Sep 2025 15:07:29 -0400 Subject: [PATCH] Avoid initiating login flow for invalid API keys (#15773) ## Summary If the login flow fails, and the user provided an API key, it's unintuitive to initiate the login flow. --- crates/uv-auth/src/pyx.rs | 19 ++++++++++++++++--- crates/uv/src/commands/auth/token.rs | 7 +++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/uv-auth/src/pyx.rs b/crates/uv-auth/src/pyx.rs index 67c1f1d4f..00a5d6b3a 100644 --- a/crates/uv-auth/src/pyx.rs +++ b/crates/uv-auth/src/pyx.rs @@ -261,11 +261,24 @@ impl PyxTokenStore { Ok(()) } + /// Returns `true` if the user appears to have an authentication token set. + pub fn has_auth_token(&self) -> bool { + read_pyx_auth_token().is_some() + } + + /// Returns `true` if the user appears to have an API key set. + pub fn has_api_key(&self) -> bool { + read_pyx_api_key().is_some() + } + + /// Returns `true` if the user appears to have OAuth tokens stored on disk. + pub fn has_oauth_tokens(&self) -> bool { + self.subdirectory.join("tokens.json").is_file() + } + /// Returns `true` if the user appears to have credentials (which may be invalid). pub fn has_credentials(&self) -> bool { - read_pyx_auth_token().is_some() - || read_pyx_api_key().is_some() - || self.subdirectory.join("tokens.json").is_file() + self.has_auth_token() || self.has_api_key() || self.has_oauth_tokens() } /// Read the tokens from the store. diff --git a/crates/uv/src/commands/auth/token.rs b/crates/uv/src/commands/auth/token.rs index 9853919d8..04d2aca01 100644 --- a/crates/uv/src/commands/auth/token.rs +++ b/crates/uv/src/commands/auth/token.rs @@ -110,6 +110,13 @@ async fn pyx_refresh(store: &PyxTokenStore, client: &BaseClient, printer: Printe // Similarly, if the refresh token expired, prompt for login. Err(err) if err.is_unauthorized() => { + if store.has_auth_token() { + return Err( + anyhow::Error::from(err).context("Failed to authenticate with access token") + ); + } else if store.has_api_key() { + return Err(anyhow::Error::from(err).context("Failed to authenticate with API key")); + } debug!( "Received 401 (Unauthorized) response from refresh endpoint; prompting for login..." );