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
This commit is contained in:
Oleksiy Syvokon
2026-10-23 21:59:20 +00:00
committed by GitHub
parent abd9b3cbd2
commit 79fe6a645f
6 changed files with 152 additions and 10 deletions
@@ -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,
+18
View File
@@ -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)
+16
View File
@@ -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<()>>;
+61 -10
View File
@@ -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,
})
);
}
}
+16
View File
@@ -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()
@@ -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,