From 79fe6a645f68f8c9230578f154bf99852d9f716f Mon Sep 17 00:00:00 2001 From: Oleksiy Syvokon Date: Fri, 23 Oct 2026 21:59:20 +0000 Subject: [PATCH] gpui: Add a way to write credentials only if none exist (#66062) Apps that keep a shared secret in the system keychain, such as an encryption key, create it on first use. With only `read_credentials` and `write_credentials`, two processes can both find no secret, and the second write then replaces the first. Data encrypted with the replaced secret can no longer be read. Add `write_credentials_if_not_exists`, which returns `true` if it wrote the credentials and `false` if they already existed. It never replaces an existing secret. On macOS this is a single atomic `SecItemAdd`: an existing item with the same URL and username makes it return `false`. Other platforms and providers get a default that reads and then writes. That default never overwrites credentials it can see, but two concurrent callers can still race. A failed read, including a cancelled Keychain prompt, never writes. `write_credentials` keeps its update behavior. Release Notes: - [GPUI] Added `write_credentials_if_not_exists`, which never replaces existing credentials and is atomic on macOS --- .../src/credentials_provider.rs | 26 +++++++ crates/gpui/src/app.rs | 18 +++++ crates/gpui/src/platform.rs | 16 +++++ crates/gpui_apple/src/keychain.rs | 71 ++++++++++++++++--- crates/gpui_macos/src/platform.rs | 16 +++++ .../src/zed_credentials_provider.rs | 15 ++++ 6 files changed, 152 insertions(+), 10 deletions(-) diff --git a/crates/credentials_provider/src/credentials_provider.rs b/crates/credentials_provider/src/credentials_provider.rs index 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> + '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> + '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.rs index 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> { + self.platform + .write_credentials_if_not_exists(url, username, password) + } + /// Reads credentials from the platform keychain. pub fn read_credentials(&self, url: &str) -> Task)>>> { self.platform.read_credentials(url) diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 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>; + + /// 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> { + Task::ready(Err(anyhow::anyhow!( + "this platform does not support atomic credential writes" + ))) + } + fn read_credentials(&self, url: &str) -> Task)>>>; fn delete_credentials(&self, url: &str) -> Task>; diff --git a/crates/gpui_apple/src/keychain.rs b/crates/gpui_apple/src/keychain.rs index 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::::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 { + 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::::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)>, KeychainError> { let server = CFString::from_str(server); @@ -159,6 +188,15 @@ fn read_status(status: i32) -> Result { } } +fn create_status(status: i32) -> Result { + 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.rs index 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> { + 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)>>> { 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.rs index 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> + '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,