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