Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions crates/uv-auth/src/keyring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,19 +357,32 @@ impl KeyringProvider {
username: Option<&str>,
) -> Option<(String, String)> {
let prefixed_service = format!("{UV_SERVICE_PREFIX}{service}");
let username = username?;
let Ok(entry) = uv_keyring::Entry::new(&prefixed_service, username) else {
return None;
};
match entry.get_password().await {
Ok(password) => return Some((username.to_string(), password)),
Err(uv_keyring::Error::NoEntry) => {
debug!("No entry found in system keyring for {service}");
if let Some(username) = username {
let Ok(entry) = uv_keyring::Entry::new(&prefixed_service, username) else {
return None;
};
match entry.get_password().await {
Ok(password) => return Some((username.to_string(), password)),
Err(uv_keyring::Error::NoEntry) => {
debug!("No entry found in system keyring for {service}");
}
Err(err) => {
warn_user_once!(
"Unable to fetch credentials for {service} from system keyring: {err}"
);
}
}
Err(err) => {
warn_user_once!(
"Unable to fetch credentials for {service} from system keyring: {err}"
);
} else {
match uv_keyring::find_credential_by_service(&prefixed_service).await {
Ok(Some(credentials)) => return Some(credentials),
Ok(None) => {
debug!("No entry found in system keyring for {service}");
}
Err(err) => {
warn_user_once!(
"Unable to search credentials for {service} in system keyring: {err}"
);
}
}
}
None
Expand Down
23 changes: 23 additions & 0 deletions crates/uv-keyring/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,29 @@ pub fn default_credential_builder() -> Box<CredentialBuilder> {
credential::nop_credential_builder()
}

/// Search for a credential by service name only (without knowing the account/username).
///
/// Uses platform-specific search APIs to find a matching credential, returning
/// the first match as an `(account, password)` pair.
///
/// Returns `Ok(None)` if no matching credential is found or the platform does not
/// support username-less search.
#[cfg_attr(
not(all(target_os = "macos", feature = "apple-native")),
expect(clippy::unused_async, reason = "async is used on macOS")
)]
pub async fn find_credential_by_service(service: &str) -> Result<Option<(String, String)>> {
#[cfg(all(target_os = "macos", feature = "apple-native"))]
{
macos::find_credential_by_service(service).await
}
#[cfg(not(all(target_os = "macos", feature = "apple-native")))]
{
let _ = service;
Ok(None)
}
}

fn build_default_credential(target: Option<&str>, service: &str, user: &str) -> Result<Entry> {
static DEFAULT: std::sync::LazyLock<Box<CredentialBuilder>> =
std::sync::LazyLock::new(default_credential_builder);
Expand Down
87 changes: 87 additions & 0 deletions crates/uv-keyring/src/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ ignores all the others. so clients can't use it to access or update any attribut
use crate::credential::{Credential, CredentialApi, CredentialBuilder, CredentialBuilderApi};
use crate::error::{Error as ErrorCode, Result, decode_password};
use security_framework::base::Error;
use security_framework::item::{ItemClass, ItemSearchOptions, SearchResult};
use security_framework::os::macos::keychain::{SecKeychain, SecPreferencesDomain};
use security_framework::os::macos::passwords::find_generic_password;

Expand Down Expand Up @@ -331,6 +332,54 @@ pub fn decode_error(err: Error) -> ErrorCode {
}
}

/// Search for a generic password credential by service name only (without account).
///
/// Uses the modern `SecItemCopyMatching` API to search by service attribute,
/// returning the first matching credential's (account, password) pair.
///
/// Returns `Ok(None)` if no matching credential is found.
pub(crate) async fn find_credential_by_service(service: &str) -> Result<Option<(String, String)>> {
let service = service.to_string();
crate::blocking::spawn_blocking(move || {
let keychain = get_keychain(MacKeychainDomain::User)?;
let results = ItemSearchOptions::new()
.keychains(&[keychain])
.class(ItemClass::generic_password())
.service(&service)
.load_attributes(true)
.load_data(true)
.search();

let results = match results {
Ok(results) => results,
Err(err) => {
let decoded = decode_error(err);
if matches!(decoded, ErrorCode::NoEntry) {
return Ok(None);
}
return Err(decoded);
}
};

for result in &results {
if let SearchResult::Dict(_) = result {
if let Some(attrs) = result.simplify_dict() {
if let (Some(account), Some(password)) =
(attrs.get("acct"), attrs.get("v_Data"))
{
if !account.is_empty() {
return Ok(Some((account.clone(), password.clone())));
}
}
}
}
}

Ok(None)
})
.await
}

#[cfg(feature = "native-auth")]
#[cfg(not(miri))]
#[cfg(test)]
Expand Down Expand Up @@ -429,6 +478,44 @@ mod tests {
crate::tests::test_noop_get_update_attributes(entry_new).await;
}

#[tokio::test]
async fn test_find_credential_by_service_without_account() {
let service = generate_random_string();
let user = generate_random_string();
let password = "test-password-for-search";

// Store a credential using the normal Entry API
let entry = entry_new(&service, &user);
entry
.set_password(password)
.await
.expect("Can't set password for search test");

// Search by service name only (no account) — this is the capability
// that was missing, causing native-auth credential lookups to fail
// during `uv sync` when the username is not known upfront.
let result = super::find_credential_by_service(&service)
.await
.expect("Search should not error");
assert_eq!(
result,
Some((user.clone(), password.to_string())),
"Should find credential by service name alone"
);

// Search for a non-existent service returns None
let missing = super::find_credential_by_service("nonexistent-service-name")
.await
.expect("Search for missing service should not error");
assert_eq!(missing, None, "Should return None for missing service");

// Clean up
entry
.delete_credential()
.await
.expect("Couldn't delete after search test");
}

#[test]
fn test_select_keychain() {
for name in ["unknown", "user", "common", "system", "dynamic"] {
Expand Down
Loading