Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Add a way to write credentials only if none exist (#66062)
Oleksiy Syvokon79fe6a645f68
diff --git a/crates/credentials_provider/src/credentials_provider.rs b/crates/credentials_provider/src/credentials_provider.rsindex 38dd769166a..b5144cf292a 100644--- a/crates/credentials_provider/src/credentials_provider.rs+++ b/crates/credentials_provider/src/credentials_provider.rs@@ -28,6 +28,32 @@ pub trait CredentialsProvider: Send + Sync {cx: &'a AsyncApp,) -> Pin<Box<dyn Future<Output = Result<()>> + 'a>>;+ /// Writes credentials only if none exist for the URL.+ ///+ /// Returns `true` if written, or `false` if credentials already exist and+ /// were left unchanged. The default reads and then writes, so a concurrent+ /// writer can still be overwritten. Providers override this when their+ /// storage can create atomically.+ ///+ /// # Errors+ ///+ /// Returns an error if the read or write fails. A failed read never writes.+ fn write_credentials_if_not_exists<'a>(+ &'a self,+ url: &'a str,+ username: &'a str,+ password: &'a [u8],+ cx: &'a AsyncApp,+ ) -> Pin<Box<dyn Future<Output = Result<bool>> + 'a>> {+ Box::pin(async move {+ if self.read_credentials(url, cx).await?.is_some() {+ return Ok(false);+ }+ self.write_credentials(url, username, password, cx).await?;+ Ok(true)+ })+ }+/// Deletes the credentials from the provider.fn delete_credentials<'a>(&'a self,diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rsindex 2fc922724f2..0f1d59b4f6b 100644--- a/crates/gpui/src/app.rs+++ b/crates/gpui/src/app.rs@@ -1896,6 +1896,24 @@ impl App {self.platform.write_credentials(url, username, password)}+ /// Atomically writes credentials unless an item with this URL and username exists.+ ///+ /// Returns `true` if written, or `false` if the existing item was left unchanged.+ ///+ /// # Errors+ ///+ /// Returns an error if Keychain access fails or the platform lacks support.+ #[cfg(target_os = "macos")]+ pub fn write_credentials_if_not_exists(+ &self,+ url: &str,+ username: &str,+ password: &[u8],+ ) -> Task<Result<bool>> {+ self.platform+ .write_credentials_if_not_exists(url, username, password)+ }+/// Reads credentials from the platform keychain.pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {self.platform.read_credentials(url)diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rsindex a875ee0f378..90b3bc39e3a 100644--- a/crates/gpui/src/platform.rs+++ b/crates/gpui/src/platform.rs@@ -601,6 +601,22 @@ pub trait Platform: 'static {fn write_to_find_pasteboard(&self, item: ClipboardItem);fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>>;++ /// Atomically writes credentials unless an item with this URL and username exists.+ ///+ /// Returns `true` if written, or `false` if the existing item was left unchanged.+ #[cfg(target_os = "macos")]+ fn write_credentials_if_not_exists(+ &self,+ _url: &str,+ _username: &str,+ _password: &[u8],+ ) -> Task<Result<bool>> {+ Task::ready(Err(anyhow::anyhow!(+ "this platform does not support atomic credential writes"+ )))+ }+fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>>;fn delete_credentials(&self, url: &str) -> Task<Result<()>>;diff --git a/crates/gpui_apple/src/keychain.rs b/crates/gpui_apple/src/keychain.rsindex 339ed864209..a40eafcf203 100644--- a/crates/gpui_apple/src/keychain.rs+++ b/crates/gpui_apple/src/keychain.rs@@ -1,8 +1,8 @@use objc2_core_foundation::{CFData, CFDictionary, CFRetained, CFString, CFType, kCFBooleanTrue};use objc2_security::{- SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate, errSecItemNotFound,- errSecSuccess, errSecUserCanceled, kSecAttrAccount, kSecAttrServer, kSecClass,- kSecClassInternetPassword, kSecReturnAttributes, kSecReturnData, kSecValueData,+ SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate, errSecDuplicateItem,+ errSecItemNotFound, errSecSuccess, errSecUserCanceled, kSecAttrAccount, kSecAttrServer,+ kSecClass, kSecClassInternetPassword, kSecReturnAttributes, kSecReturnData, kSecValueData,};use std::ptr;@@ -58,17 +58,46 @@ pub fn write_credentials(let mut status = unsafe { SecItemUpdate(query.as_opaque(), attributes.as_opaque()) };if status == errSecItemNotFound {operation = KeychainOperation::Create;- let attributes = CFDictionary::<CFString, CFType>::from_slices(- &[class_key, server_key, account_key, data_key],- &[internet_password, &server, &account, &password],- );- // SAFETY: The dictionary maps Security attribute keys to CF values, and a- // null result pointer asks Security not to return the new item.- status = unsafe { SecItemAdd(attributes.as_opaque(), ptr::null_mut()) };+ status = add_credentials(&server, &account, &password);}check_status(operation, status)}+/// Atomically adds a Keychain item unless one with this server and account exists.+///+/// Returns `false` if the item exists, leaving its secret unchanged. Items for the+/// same server under a different account are not conflicts.+pub fn write_credentials_if_not_exists(+ server: &str,+ account: &str,+ password: &[u8],+) -> Result<bool, KeychainError> {+ let server = CFString::from_str(server);+ let account = CFString::from_str(account);+ let password = CFData::from_bytes(password);+ create_status(add_credentials(&server, &account, &password))+}++fn add_credentials(server: &CFString, account: &CFString, password: &CFData) -> i32 {+ // SAFETY: Reading immutable constants exported by the Security framework.+ let (class_key, server_key, account_key, data_key, internet_password) = unsafe {+ (+ kSecClass,+ kSecAttrServer,+ kSecAttrAccount,+ kSecValueData,+ kSecClassInternetPassword,+ )+ };+ let attributes = CFDictionary::<CFString, CFType>::from_slices(+ &[class_key, server_key, account_key, data_key],+ &[internet_password, server, account, password],+ );+ // SAFETY: The dictionary maps Security attribute keys to CF values, and a+ // null result pointer asks Security not to return the new item.+ unsafe { SecItemAdd(attributes.as_opaque(), ptr::null_mut()) }+}+/// Reads credentials by server, returning `None` when no item exists.pub fn read_credentials(server: &str) -> Result<Option<(String, Vec<u8>)>, KeychainError> {let server = CFString::from_str(server);@@ -159,6 +188,15 @@ fn read_status(status: i32) -> Result<bool, KeychainError> {}}+fn create_status(status: i32) -> Result<bool, KeychainError> {+ if status == errSecDuplicateItem {+ Ok(false)+ } else {+ check_status(KeychainOperation::Create, status)?;+ Ok(true)+ }+}+fn check_status(operation: KeychainOperation, status: i32) -> Result<(), KeychainError> {if status == errSecSuccess {Ok(())@@ -229,4 +267,17 @@ mod tests {}));}++ #[test]+ fn create_reports_existing_items_without_error() {+ assert_eq!(create_status(errSecSuccess), Ok(true));+ assert_eq!(create_status(errSecDuplicateItem), Ok(false));+ assert_eq!(+ create_status(errSecItemNotFound),+ Err(KeychainError::Security {+ operation: KeychainOperation::Create,+ status: errSecItemNotFound,+ })+ );+ }}diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rsindex 5d31ca46d73..8fd20666b09 100644--- a/crates/gpui_macos/src/platform.rs+++ b/crates/gpui_macos/src/platform.rs@@ -1219,6 +1219,22 @@ impl Platform for MacPlatform {.spawn(async move { Ok(keychain::write_credentials(&url, &username, &password)?) })}+ fn write_credentials_if_not_exists(+ &self,+ url: &str,+ username: &str,+ password: &[u8],+ ) -> Task<Result<bool>> {+ let url = url.to_string();+ let username = username.to_string();+ let password = password.to_vec();+ self.background_executor().spawn(async move {+ Ok(keychain::write_credentials_if_not_exists(+ &url, &username, &password,+ )?)+ })+ }+fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {let url = url.to_string();self.background_executor()diff --git a/crates/zed_credentials_provider/src/zed_credentials_provider.rs b/crates/zed_credentials_provider/src/zed_credentials_provider.rsindex 6705e58d400..7d71dff9a31 100644--- a/crates/zed_credentials_provider/src/zed_credentials_provider.rs+++ b/crates/zed_credentials_provider/src/zed_credentials_provider.rs@@ -91,6 +91,21 @@ impl CredentialsProvider for KeychainCredentialsProvider {.boxed_local()}+ #[cfg(target_os = "macos")]+ fn write_credentials_if_not_exists<'a>(+ &'a self,+ url: &'a str,+ username: &'a str,+ password: &'a [u8],+ cx: &'a AsyncApp,+ ) -> Pin<Box<dyn Future<Output = Result<bool>> + 'a>> {+ async move {+ cx.update(move |cx| cx.write_credentials_if_not_exists(url, username, password))+ .await+ }+ .boxed_local()+ }+fn delete_credentials<'a>(&'a self,url: &'a str,