Skip to main content

security/keychain/
mod.rs

1use std::ffi::{c_void, CString};
2
3use bitflags::bitflags;
4use serde_json::json;
5
6use apple_cf::cf::CFType;
7
8use crate::bridge::{self, Handle};
9use crate::error::{Result, SecurityError};
10use crate::secret::SecretBytes;
11
12mod internet_password;
13pub use internet_password::{InternetCredential, InternetPassword};
14
15bitflags! {
16    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17    /// Mirrors `SecAccessControlCreateFlags`.
18    pub struct AccessControlFlags: u64 {
19        /// Mirrors a `SecAccessControlCreateFlags` bit.
20        const DEFAULTS = 0;
21        /// Mirrors a `SecAccessControlCreateFlags` bit.
22        const USER_PRESENCE = 1 << 0;
23        /// Mirrors a `SecAccessControlCreateFlags` bit.
24        const BIOMETRY_ANY = 1 << 1;
25        /// Mirrors a `SecAccessControlCreateFlags` bit.
26        const BIOMETRY_CURRENT_SET = 1 << 3;
27        /// Mirrors a `SecAccessControlCreateFlags` bit.
28        const DEVICE_PASSCODE = 1 << 4;
29        /// Mirrors a `SecAccessControlCreateFlags` bit.
30        const COMPANION = 1 << 5;
31        /// Mirrors a `SecAccessControlCreateFlags` bit.
32        const OR = 1 << 14;
33        /// Mirrors a `SecAccessControlCreateFlags` bit.
34        const AND = 1 << 15;
35        /// Mirrors a `SecAccessControlCreateFlags` bit.
36        const PRIVATE_KEY_USAGE = 1 << 30;
37        /// Mirrors a `SecAccessControlCreateFlags` bit.
38        const APPLICATION_PASSWORD = 1 << 31;
39    }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
43/// Mirrors protection classes used by `SecAccessControlCreateWithFlags`.
44pub enum AccessControlProtection {
45    /// Mirrors a `SecAccessControl` protection-class constant.
46    #[default]
47    WhenUnlocked,
48    /// Mirrors a `SecAccessControl` protection-class constant.
49    AfterFirstUnlock,
50    /// Mirrors a `SecAccessControl` protection-class constant.
51    WhenPasscodeSetThisDeviceOnly,
52    /// Mirrors a `SecAccessControl` protection-class constant.
53    WhenUnlockedThisDeviceOnly,
54    /// Mirrors a `SecAccessControl` protection-class constant.
55    AfterFirstUnlockThisDeviceOnly,
56}
57
58impl AccessControlProtection {
59    const fn as_bridge_name(self) -> &'static str {
60        match self {
61            Self::WhenUnlocked => "when_unlocked",
62            Self::AfterFirstUnlock => "after_first_unlock",
63            Self::WhenPasscodeSetThisDeviceOnly => "when_passcode_set_this_device_only",
64            Self::WhenUnlockedThisDeviceOnly => "when_unlocked_this_device_only",
65            Self::AfterFirstUnlockThisDeviceOnly => "after_first_unlock_this_device_only",
66        }
67    }
68}
69
70#[derive(Debug, Clone)]
71/// Wraps `SecAccessControlRef`.
72pub struct AccessControl {
73    object: CFType,
74    protection: AccessControlProtection,
75    flags: AccessControlFlags,
76}
77
78impl AccessControl {
79    /// Wraps the corresponding `SecAccessControlRef` operation.
80    pub fn type_id() -> usize {
81        unsafe { bridge::security_access_control_get_type_id() }
82    }
83
84    /// Wraps the corresponding `SecAccessControlRef` operation.
85    pub fn create(protection: AccessControlProtection, flags: AccessControlFlags) -> Result<Self> {
86        let protection_name = bridge::cstring(protection.as_bridge_name())?;
87        let mut status = 0;
88        let mut error = std::ptr::null_mut();
89        let raw = unsafe {
90            bridge::security_access_control_create(
91                protection_name.as_ptr(),
92                flags.bits(),
93                &raw mut status,
94                &raw mut error,
95            )
96        };
97        let Some(object) = (unsafe { CFType::from_raw(raw) }) else {
98            return Err(bridge::status_error(
99                "security_access_control_create",
100                status,
101                error,
102            )?);
103        };
104        Ok(Self {
105            object,
106            protection,
107            flags,
108        })
109    }
110
111    /// Wraps the corresponding `SecAccessControlRef` operation.
112    pub fn is_valid(&self) -> bool {
113        !self.object.as_ptr().is_null()
114    }
115
116    pub const fn protection(&self) -> AccessControlProtection {
117        self.protection
118    }
119
120    pub const fn flags(&self) -> AccessControlFlags {
121        self.flags
122    }
123
124    pub const fn as_ptr(&self) -> *mut c_void {
125        self.object.as_ptr()
126    }
127}
128
129#[derive(Debug, Default)]
130pub struct KeychainOptions {
131    accessibility: AccessControlProtection,
132    access_control: Option<AccessControl>,
133    access_group: Option<String>,
134    synchronizable: bool,
135    data_protection_keychain: bool,
136    authentication_context: Option<Handle>,
137}
138
139impl KeychainOptions {
140    #[must_use]
141    pub fn accessibility(mut self, accessibility: AccessControlProtection) -> Self {
142        self.accessibility = accessibility;
143        self
144    }
145
146    #[must_use]
147    pub fn access_control(mut self, access_control: AccessControl) -> Self {
148        self.access_control = Some(access_control);
149        self
150    }
151
152    #[must_use]
153    pub fn access_group(mut self, access_group: impl Into<String>) -> Self {
154        self.access_group = Some(access_group.into());
155        self
156    }
157
158    #[must_use]
159    pub fn synchronizable(mut self, synchronizable: bool) -> Self {
160        self.synchronizable = synchronizable;
161        self
162    }
163
164    #[must_use]
165    pub fn data_protection_keychain(mut self, data_protection_keychain: bool) -> Self {
166        self.data_protection_keychain = data_protection_keychain;
167        self
168    }
169
170    #[allow(clippy::missing_safety_doc)]
171    pub unsafe fn authentication_context(mut self, la_context: *mut c_void) -> Result<Self> {
172        let raw = unsafe { bridge::security_authentication_context_retain(la_context) };
173        let handle = Handle::from_raw(raw).ok_or_else(|| {
174            SecurityError::InvalidArgument("authentication context must be an LAContext".to_owned())
175        })?;
176        self.authentication_context = Some(handle);
177        Ok(self)
178    }
179
180    fn bridge_json(&self) -> Result<CString> {
181        let mut options = json!({
182            "accessibility": self.accessibility.as_bridge_name(),
183            "synchronizable": self.synchronizable,
184            "data_protection_keychain": self.data_protection_keychain,
185        });
186        if let Some(access_group) = &self.access_group {
187            options["access_group"] = json!(access_group);
188        }
189        bridge::json_cstring(&options)
190    }
191
192    fn access_control_ptr(&self) -> *mut c_void {
193        self.access_control
194            .as_ref()
195            .map_or(std::ptr::null_mut(), AccessControl::as_ptr)
196    }
197
198    fn authentication_context_ptr(&self) -> *mut c_void {
199        self.authentication_context
200            .as_ref()
201            .map_or(std::ptr::null_mut(), Handle::as_ptr)
202    }
203}
204
205#[derive(Debug, Clone, PartialEq, Eq, Hash)]
206/// Wraps a generic-password identity used with `SecItem` queries.
207pub struct KeychainEntry {
208    account: String,
209    service: String,
210}
211
212impl KeychainEntry {
213    /// Wraps the corresponding generic-password operation built on `SecItem`.
214    pub fn new(account: impl Into<String>, service: impl Into<String>) -> Self {
215        Self {
216            account: account.into(),
217            service: service.into(),
218        }
219    }
220
221    /// Wraps the corresponding generic-password operation built on `SecItem`.
222    pub fn account(&self) -> &str {
223        &self.account
224    }
225
226    /// Wraps the corresponding generic-password operation built on `SecItem`.
227    pub fn service(&self) -> &str {
228        &self.service
229    }
230
231    /// Wraps the corresponding generic-password operation built on `SecItem`.
232    pub fn set(&self, secret: impl AsRef<[u8]>) -> Result<()> {
233        Keychain::set(&self.account, &self.service, secret)
234    }
235
236    /// Wraps the corresponding generic-password operation built on `SecItem`.
237    pub fn get(&self) -> Result<SecretBytes> {
238        Keychain::get(&self.account, &self.service)
239    }
240
241    /// Wraps the corresponding generic-password operation built on `SecItem`.
242    pub fn delete(&self) -> Result<()> {
243        Keychain::delete(&self.account, &self.service)
244    }
245}
246
247/// Wraps generic-password operations built on `SecItem` APIs.
248pub struct Keychain;
249
250impl Keychain {
251    /// Wraps the corresponding generic-password `SecItem` operation.
252    pub fn entry(account: impl Into<String>, service: impl Into<String>) -> KeychainEntry {
253        KeychainEntry::new(account, service)
254    }
255
256    /// Wraps the corresponding generic-password `SecItem` operation.
257    pub fn set(account: &str, service: &str, secret: impl AsRef<[u8]>) -> Result<()> {
258        Self::set_with_options(account, service, secret, &KeychainOptions::default())
259    }
260
261    /// Wraps the corresponding generic-password `SecItem` operation.
262    pub fn get(account: &str, service: &str) -> Result<SecretBytes> {
263        Self::get_with_options(account, service, &KeychainOptions::default())
264    }
265
266    /// Wraps the corresponding generic-password `SecItem` operation.
267    pub fn delete(account: &str, service: &str) -> Result<()> {
268        Self::delete_with_options(account, service, &KeychainOptions::default())
269    }
270
271    /// Wraps the corresponding generic-password `SecItem` operation.
272    pub fn list_accounts(service: &str) -> Result<Vec<String>> {
273        Self::list_accounts_with_options(service, &KeychainOptions::default())
274    }
275
276    pub fn set_with_options(
277        account: &str,
278        service: &str,
279        secret: impl AsRef<[u8]>,
280        options: &KeychainOptions,
281    ) -> Result<()> {
282        let secret = secret.as_ref();
283        let account = bridge::cstring(account)?;
284        let service = bridge::cstring(service)?;
285        let options_json = options.bridge_json()?;
286        let mut error = std::ptr::null_mut();
287        let status = unsafe {
288            bridge::security_keychain_set_item(
289                account.as_ptr(),
290                service.as_ptr(),
291                secret.as_ptr().cast(),
292                bridge::len_to_isize(secret.len())?,
293                options_json.as_ptr(),
294                options.access_control_ptr(),
295                options.authentication_context_ptr(),
296                &raw mut error,
297            )
298        };
299        bridge::status_result("security_keychain_set_item", status, error)
300    }
301
302    pub fn get_with_options(
303        account: &str,
304        service: &str,
305        options: &KeychainOptions,
306    ) -> Result<SecretBytes> {
307        let account = bridge::cstring(account)?;
308        let service = bridge::cstring(service)?;
309        let options_json = options.bridge_json()?;
310        let mut status = 0;
311        let mut error = std::ptr::null_mut();
312        let raw = unsafe {
313            bridge::security_keychain_copy_item(
314                account.as_ptr(),
315                service.as_ptr(),
316                options_json.as_ptr(),
317                options.authentication_context_ptr(),
318                &raw mut status,
319                &raw mut error,
320            )
321        };
322        bridge::required_secret("security_keychain_copy_item", raw, status, error)
323    }
324
325    pub fn delete_with_options(
326        account: &str,
327        service: &str,
328        options: &KeychainOptions,
329    ) -> Result<()> {
330        let account = bridge::cstring(account)?;
331        let service = bridge::cstring(service)?;
332        let options_json = options.bridge_json()?;
333        let mut error = std::ptr::null_mut();
334        let status = unsafe {
335            bridge::security_keychain_delete_item(
336                account.as_ptr(),
337                service.as_ptr(),
338                options_json.as_ptr(),
339                options.authentication_context_ptr(),
340                &raw mut error,
341            )
342        };
343        bridge::status_result("security_keychain_delete_item", status, error)
344    }
345
346    pub fn list_accounts_with_options(
347        service: &str,
348        options: &KeychainOptions,
349    ) -> Result<Vec<String>> {
350        let service = bridge::cstring(service)?;
351        let options_json = options.bridge_json()?;
352        let mut status = 0;
353        let mut error = std::ptr::null_mut();
354        let raw = unsafe {
355            bridge::security_keychain_list_accounts(
356                service.as_ptr(),
357                options_json.as_ptr(),
358                options.authentication_context_ptr(),
359                &raw mut status,
360                &raw mut error,
361            )
362        };
363        bridge::required_json("security_keychain_list_accounts", raw, status, error)
364    }
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn access_control_protection_base_bridge_names_are_stable() {
373        assert_eq!(
374            AccessControlProtection::WhenUnlocked.as_bridge_name(),
375            "when_unlocked"
376        );
377        assert_eq!(
378            AccessControlProtection::AfterFirstUnlock.as_bridge_name(),
379            "after_first_unlock"
380        );
381    }
382
383    #[test]
384    fn access_control_protection_device_only_bridge_names_are_stable() {
385        assert_eq!(
386            AccessControlProtection::WhenPasscodeSetThisDeviceOnly.as_bridge_name(),
387            "when_passcode_set_this_device_only"
388        );
389        assert_eq!(
390            AccessControlProtection::WhenUnlockedThisDeviceOnly.as_bridge_name(),
391            "when_unlocked_this_device_only"
392        );
393        assert_eq!(
394            AccessControlProtection::AfterFirstUnlockThisDeviceOnly.as_bridge_name(),
395            "after_first_unlock_this_device_only"
396        );
397    }
398
399    #[test]
400    fn access_control_flags_round_trip_through_bits() {
401        let flags = AccessControlFlags::USER_PRESENCE
402            | AccessControlFlags::PRIVATE_KEY_USAGE
403            | AccessControlFlags::APPLICATION_PASSWORD;
404
405        assert_eq!(AccessControlFlags::from_bits(flags.bits()), Some(flags));
406    }
407
408    #[test]
409    fn default_options_protect_items_when_unlocked() {
410        let json = KeychainOptions::default().bridge_json().unwrap();
411        let value: serde_json::Value = serde_json::from_str(json.to_str().unwrap()).unwrap();
412        assert_eq!(value["accessibility"], "when_unlocked");
413        assert_eq!(value["synchronizable"], false);
414        assert_eq!(value["data_protection_keychain"], false);
415        assert!(value.get("access_group").is_none());
416        assert_eq!(
417            AccessControlProtection::default(),
418            AccessControlProtection::WhenUnlocked
419        );
420    }
421
422    #[test]
423    fn options_serialize_every_selected_control() {
424        let options = KeychainOptions::default()
425            .accessibility(AccessControlProtection::WhenUnlockedThisDeviceOnly)
426            .access_group("TEAMID.group")
427            .synchronizable(true)
428            .data_protection_keychain(true);
429        let json = options.bridge_json().unwrap();
430        let value: serde_json::Value = serde_json::from_str(json.to_str().unwrap()).unwrap();
431        assert_eq!(value["accessibility"], "when_unlocked_this_device_only");
432        assert_eq!(value["access_group"], "TEAMID.group");
433        assert_eq!(value["synchronizable"], true);
434        assert_eq!(value["data_protection_keychain"], true);
435        assert!(options.access_control_ptr().is_null());
436        assert!(options.authentication_context_ptr().is_null());
437    }
438
439    #[test]
440    fn keychain_entry_new_preserves_account_and_service() {
441        let entry = KeychainEntry::new("alice", "security-rs.tests");
442
443        assert_eq!(entry.account(), "alice");
444        assert_eq!(entry.service(), "security-rs.tests");
445    }
446
447    #[test]
448    fn keychain_entry_convenience_constructor_matches_new() {
449        let entry = Keychain::entry("alice", "security-rs.tests");
450
451        assert_eq!(entry, KeychainEntry::new("alice", "security-rs.tests"));
452    }
453}