diff --git a/codex-rs/keyring-store/src/lib.rs b/codex-rs/keyring-store/src/lib.rs index 9c404729a8..a27b5a26da 100644 --- a/codex-rs/keyring-store/src/lib.rs +++ b/codex-rs/keyring-store/src/lib.rs @@ -10,17 +10,10 @@ mod macos; #[cfg(not(target_os = "macos"))] use keyring::Entry; -#[cfg(not(target_os = "macos"))] pub fn migrate_existing_codex_items_to_access_group() -> Result<(), CredentialStoreError> { Ok(()) } -#[cfg(target_os = "macos")] -pub fn migrate_existing_codex_items_to_access_group() -> Result<(), CredentialStoreError> { - macos::migrate_existing_codex_items_to_access_group() - .map_err(|error| CredentialStoreError::new(KeyringError::PlatformFailure(Box::new(error)))) -} - #[derive(Debug)] pub enum CredentialStoreError { Other(KeyringError), diff --git a/codex-rs/keyring-store/src/macos.rs b/codex-rs/keyring-store/src/macos.rs index 1ea2ecb17e..c5174c7f9f 100644 --- a/codex-rs/keyring-store/src/macos.rs +++ b/codex-rs/keyring-store/src/macos.rs @@ -1,23 +1,13 @@ -use core_foundation::base::TCFType; -use core_foundation::dictionary::CFDictionary; -use core_foundation::string::CFString; use security_framework::base::Error as SecurityError; -use security_framework::item::ItemClass; -use security_framework::item::ItemSearchOptions; -use security_framework::item::ItemUpdateOptions; -use security_framework::item::Limit; -use security_framework::item::Location; -use security_framework::item::SearchResult; -use security_framework::item::update_item; use security_framework::passwords::PasswordOptions; use security_framework::passwords::delete_generic_password_options; use security_framework::passwords::generic_password; use security_framework::passwords::set_generic_password_options; use security_framework_sys::base::errSecItemNotFound; -use security_framework_sys::item::kSecAttrAccount; use std::fmt; +use tracing::warn; -#[derive(Debug)] +#[derive(Debug, Clone)] pub(crate) struct MacOsAccessGroupError { details: String, } @@ -43,25 +33,12 @@ impl fmt::Display for MacOsAccessGroupError { impl std::error::Error for MacOsAccessGroupError {} const SHARED_ACCESS_GROUP: &str = "2DC432GLL2.com.openai.codex.shared"; -const CODEX_KEYCHAIN_SERVICES: [&str; 3] = ["Codex Auth", "Codex MCP Credentials", "codex"]; pub(crate) fn load_password( service: &str, account: &str, ) -> Result, MacOsAccessGroupError> { - if let Some(password) = load_shared_password_bytes(service, account)? { - return decode_password(password, service, account).map(Some); - } - - if migrate_password_to_access_group(service, account)? - && let Some(password) = load_shared_password_bytes(service, account)? - { - return decode_password(password, service, account).map(Some); - } - - load_legacy_password_bytes(service, account)? - .map(|password| decode_password(password, service, account)) - .transpose() + load_password_with_store(&NativePasswordStore, service, account) } pub(crate) fn save_password( @@ -69,95 +46,147 @@ pub(crate) fn save_password( account: &str, value: &str, ) -> Result<(), MacOsAccessGroupError> { - if load_shared_password_bytes(service, account)?.is_none() { - let _ = migrate_password_to_access_group(service, account)?; - } - - save_shared_password_bytes(service, account, value.as_bytes()) + save_password_with_store(&NativePasswordStore, service, account, value) } pub(crate) fn delete_password(service: &str, account: &str) -> Result { - let shared_removed = delete_shared_password(service, account)?; - let legacy_removed = delete_legacy_password(service, account)?; - Ok(shared_removed || legacy_removed) + delete_password_with_store(&NativePasswordStore, service, account) } -pub(crate) fn migrate_existing_codex_items_to_access_group() -> Result<(), MacOsAccessGroupError> { - for service in CODEX_KEYCHAIN_SERVICES { - for account in legacy_accounts_for_service(service)? { - let _ = migrate_password_to_access_group(service, &account)?; - } +trait PasswordStore { + fn load_shared_password_bytes( + &self, + service: &str, + account: &str, + ) -> Result>, MacOsAccessGroupError>; + + fn load_legacy_password_bytes( + &self, + service: &str, + account: &str, + ) -> Result>, MacOsAccessGroupError>; + + fn save_shared_password_bytes( + &self, + service: &str, + account: &str, + value: &[u8], + ) -> Result<(), MacOsAccessGroupError>; + + fn delete_shared_password( + &self, + service: &str, + account: &str, + ) -> Result; + + fn delete_legacy_password( + &self, + service: &str, + account: &str, + ) -> Result; +} + +#[derive(Debug)] +struct NativePasswordStore; + +impl PasswordStore for NativePasswordStore { + fn load_shared_password_bytes( + &self, + service: &str, + account: &str, + ) -> Result>, MacOsAccessGroupError> { + load_password_bytes( + shared_password_options(service, account), + "read shared generic password", + ) } - Ok(()) + fn load_legacy_password_bytes( + &self, + service: &str, + account: &str, + ) -> Result>, MacOsAccessGroupError> { + load_password_bytes( + legacy_password_options(service, account), + "read legacy generic password", + ) + } + + fn save_shared_password_bytes( + &self, + service: &str, + account: &str, + value: &[u8], + ) -> Result<(), MacOsAccessGroupError> { + set_generic_password_options(value, shared_password_options(service, account)) + .map_err(|error| wrap_security_error("write shared generic password", error)) + } + + fn delete_shared_password( + &self, + service: &str, + account: &str, + ) -> Result { + delete_password_options( + shared_password_options(service, account), + "delete shared generic password", + ) + } + + fn delete_legacy_password( + &self, + service: &str, + account: &str, + ) -> Result { + delete_password_options( + legacy_password_options(service, account), + "delete legacy generic password", + ) + } } -fn migrate_password_to_access_group( +fn load_password_with_store( + store: &impl PasswordStore, + service: &str, + account: &str, +) -> Result, MacOsAccessGroupError> { + if let Some(password) = store.load_shared_password_bytes(service, account)? { + return decode_password(password, service, account).map(Some); + } + + let Some(password) = store.load_legacy_password_bytes(service, account)? else { + return Ok(None); + }; + + if let Err(error) = store.save_shared_password_bytes(service, account, &password) { + warn!( + error = %error, + service, + account, + "failed to backfill legacy macOS keychain item into the shared access group" + ); + } + + decode_password(password, service, account).map(Some) +} + +fn save_password_with_store( + store: &impl PasswordStore, + service: &str, + account: &str, + value: &str, +) -> Result<(), MacOsAccessGroupError> { + store.save_shared_password_bytes(service, account, value.as_bytes()) +} + +fn delete_password_with_store( + store: &impl PasswordStore, service: &str, account: &str, ) -> Result { - let mut search = ItemSearchOptions::new(); - search - .class(ItemClass::generic_password()) - .service(service) - .account(account); - - let mut update = ItemUpdateOptions::new(); - update - .set_access_group(SHARED_ACCESS_GROUP) - .set_location(Location::DataProtectionKeychain); - - match update_item(&search, &update) { - Ok(()) => Ok(true), - Err(error) if error.code() == errSecItemNotFound => Ok(false), - Err(error) => Err(wrap_security_error( - "move existing generic password into the shared access group", - error, - )), - } -} - -fn legacy_accounts_for_service(service: &str) -> Result, MacOsAccessGroupError> { - let mut search = ItemSearchOptions::new(); - search - .class(ItemClass::generic_password()) - .service(service) - .load_attributes(true) - .limit(Limit::All); - - let results = match search.search() { - Ok(results) => results, - Err(error) if error.code() == errSecItemNotFound => return Ok(Vec::new()), - Err(error) => { - return Err(wrap_security_error( - "search existing generic passwords for Codex service", - error, - )); - } - }; - - let mut accounts = Vec::with_capacity(results.len()); - for result in results { - match result { - SearchResult::Dict(attributes) => accounts.push(account_from_attributes(&attributes)?), - SearchResult::Ref(_) | SearchResult::Data(_) | SearchResult::Other => { - return Err(MacOsAccessGroupError::new( - "search existing generic passwords for Codex service returned an unexpected result", - )); - } - } - } - - Ok(accounts) -} - -fn account_from_attributes(attributes: &CFDictionary) -> Result { - let Some(account_value) = attributes.find(unsafe { kSecAttrAccount }.cast()) else { - return Err(MacOsAccessGroupError::new( - "generic password attributes did not include an account name", - )); - }; - Ok(unsafe { CFString::wrap_under_get_rule((*account_value).cast()) }.to_string()) + let shared_removed = store.delete_shared_password(service, account)?; + let legacy_removed = store.delete_legacy_password(service, account)?; + Ok(shared_removed || legacy_removed) } fn decode_password( @@ -172,26 +201,6 @@ fn decode_password( }) } -fn load_shared_password_bytes( - service: &str, - account: &str, -) -> Result>, MacOsAccessGroupError> { - load_password_bytes( - shared_password_options(service, account), - "read shared generic password", - ) -} - -fn load_legacy_password_bytes( - service: &str, - account: &str, -) -> Result>, MacOsAccessGroupError> { - load_password_bytes( - legacy_password_options(service, account), - "read legacy generic password", - ) -} - fn load_password_bytes( options: PasswordOptions, action: &str, @@ -203,29 +212,6 @@ fn load_password_bytes( } } -fn save_shared_password_bytes( - service: &str, - account: &str, - value: &[u8], -) -> Result<(), MacOsAccessGroupError> { - set_generic_password_options(value, shared_password_options(service, account)) - .map_err(|error| wrap_security_error("write shared generic password", error)) -} - -fn delete_shared_password(service: &str, account: &str) -> Result { - delete_password_options( - shared_password_options(service, account), - "delete shared generic password", - ) -} - -fn delete_legacy_password(service: &str, account: &str) -> Result { - delete_password_options( - legacy_password_options(service, account), - "delete legacy generic password", - ) -} - fn delete_password_options( options: PasswordOptions, action: &str, @@ -255,13 +241,173 @@ fn wrap_security_error(action: &str, error: SecurityError) -> MacOsAccessGroupEr #[cfg(test)] mod tests { use super::*; + use std::cell::Cell; + use std::cell::RefCell; + + #[derive(Default)] + struct MockPasswordStore { + shared: RefCell>>, + legacy: RefCell>>, + save_shared_error: RefCell>, + shared_writes: Cell, + } + + impl MockPasswordStore { + fn with_shared_password(self, value: &str) -> Self { + self.shared.replace(Some(value.as_bytes().to_vec())); + self + } + + fn with_legacy_password(self, value: &str) -> Self { + self.legacy.replace(Some(value.as_bytes().to_vec())); + self + } + + fn with_save_shared_error(self, details: &str) -> Self { + self.save_shared_error + .replace(Some(MacOsAccessGroupError::new(details))); + self + } + } + + impl PasswordStore for MockPasswordStore { + fn load_shared_password_bytes( + &self, + _service: &str, + _account: &str, + ) -> Result>, MacOsAccessGroupError> { + Ok(self.shared.borrow().clone()) + } + + fn load_legacy_password_bytes( + &self, + _service: &str, + _account: &str, + ) -> Result>, MacOsAccessGroupError> { + Ok(self.legacy.borrow().clone()) + } + + fn save_shared_password_bytes( + &self, + _service: &str, + _account: &str, + value: &[u8], + ) -> Result<(), MacOsAccessGroupError> { + if let Some(error) = self.save_shared_error.borrow().clone() { + return Err(error); + } + + self.shared.replace(Some(value.to_vec())); + self.shared_writes.set(self.shared_writes.get() + 1); + Ok(()) + } + + fn delete_shared_password( + &self, + _service: &str, + _account: &str, + ) -> Result { + Ok(self.shared.borrow_mut().take().is_some()) + } + + fn delete_legacy_password( + &self, + _service: &str, + _account: &str, + ) -> Result { + Ok(self.legacy.borrow_mut().take().is_some()) + } + } #[test] - fn codex_keychain_services_match_stored_secret_services() { + fn load_prefers_shared_password_when_present() { + let store = MockPasswordStore::default() + .with_shared_password("shared-value") + .with_legacy_password("legacy-value"); + + let password = load_password_with_store(&store, "Codex Auth", "greg") + .unwrap() + .expect("expected password"); + + assert_eq!(password, "shared-value"); assert_eq!( - CODEX_KEYCHAIN_SERVICES, - ["Codex Auth", "Codex MCP Credentials", "codex"] + store.shared.borrow().clone(), + Some(b"shared-value".to_vec()) ); + assert_eq!( + store.legacy.borrow().clone(), + Some(b"legacy-value".to_vec()) + ); + assert_eq!(store.shared_writes.get(), 0); + } + + #[test] + fn load_backfills_shared_password_from_legacy_without_deleting_legacy() { + let store = MockPasswordStore::default().with_legacy_password("legacy-value"); + + let password = load_password_with_store(&store, "Codex Auth", "greg") + .unwrap() + .expect("expected password"); + + assert_eq!(password, "legacy-value"); + assert_eq!( + store.shared.borrow().clone(), + Some(b"legacy-value".to_vec()) + ); + assert_eq!( + store.legacy.borrow().clone(), + Some(b"legacy-value".to_vec()) + ); + assert_eq!(store.shared_writes.get(), 1); + } + + #[test] + fn load_returns_legacy_password_when_shared_backfill_fails() { + let store = MockPasswordStore::default() + .with_legacy_password("legacy-value") + .with_save_shared_error("shared write failed"); + + let password = load_password_with_store(&store, "Codex Auth", "greg") + .unwrap() + .expect("expected password"); + + assert_eq!(password, "legacy-value"); + assert_eq!(store.shared.borrow().clone(), None); + assert_eq!( + store.legacy.borrow().clone(), + Some(b"legacy-value".to_vec()) + ); + assert_eq!(store.shared_writes.get(), 0); + } + + #[test] + fn save_writes_only_to_shared_password() { + let store = MockPasswordStore::default().with_legacy_password("legacy-value"); + + save_password_with_store(&store, "Codex Auth", "greg", "shared-value").unwrap(); + + assert_eq!( + store.shared.borrow().clone(), + Some(b"shared-value".to_vec()) + ); + assert_eq!( + store.legacy.borrow().clone(), + Some(b"legacy-value".to_vec()) + ); + assert_eq!(store.shared_writes.get(), 1); + } + + #[test] + fn delete_removes_both_shared_and_legacy_passwords() { + let store = MockPasswordStore::default() + .with_shared_password("shared-value") + .with_legacy_password("legacy-value"); + + let deleted = delete_password_with_store(&store, "Codex Auth", "greg").unwrap(); + + assert!(deleted); + assert_eq!(store.shared.borrow().clone(), None); + assert_eq!(store.legacy.borrow().clone(), None); } #[test]