1use std::ffi::c_void;
2
3use crate::bridge::{self, CoreFoundationHandle, Handle};
4use crate::error::{Result, SecurityError};
5use crate::secret::SecretBytes;
6use crate::Value;
7
8mod internet_password;
9pub use internet_password::{InternetCredential, InternetPassword};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[repr(transparent)]
13#[must_use]
14pub struct AccessControlFlags(u64);
16
17impl AccessControlFlags {
18 pub const DEFAULTS: Self = Self(0);
20 pub const USER_PRESENCE: Self = Self(1 << 0);
22 pub const BIOMETRY_ANY: Self = Self(1 << 1);
24 pub const BIOMETRY_CURRENT_SET: Self = Self(1 << 3);
26 pub const DEVICE_PASSCODE: Self = Self(1 << 4);
28 pub const COMPANION: Self = Self(1 << 5);
30 pub const OR: Self = Self(1 << 14);
32 pub const AND: Self = Self(1 << 15);
34 pub const PRIVATE_KEY_USAGE: Self = Self(1 << 30);
36 pub const APPLICATION_PASSWORD: Self = Self(1 << 31);
38
39 pub const fn empty() -> Self {
40 Self(0)
41 }
42 pub const fn all() -> Self {
43 Self(0xc000_c03b)
44 }
45 pub const fn bits(self) -> u64 {
46 self.0
47 }
48 pub const fn from_bits(bits: u64) -> Option<Self> {
49 if bits & !Self::all().0 == 0 {
50 Some(Self(bits))
51 } else {
52 None
53 }
54 }
55 pub const fn from_bits_retain(bits: u64) -> Self {
56 Self(bits)
57 }
58 pub const fn from_bits_truncate(bits: u64) -> Self {
59 Self(bits & Self::all().0)
60 }
61 pub const fn is_empty(self) -> bool {
62 self.0 == 0
63 }
64 pub const fn is_all(self) -> bool {
65 self.0 & Self::all().0 == Self::all().0
66 }
67 pub const fn contains(self, other: Self) -> bool {
68 self.0 & other.0 == other.0
69 }
70 pub const fn intersects(self, other: Self) -> bool {
71 self.0 & other.0 != 0
72 }
73 pub const fn union(self, other: Self) -> Self {
74 Self(self.0 | other.0)
75 }
76 pub const fn intersection(self, other: Self) -> Self {
77 Self(self.0 & other.0)
78 }
79 pub const fn difference(self, other: Self) -> Self {
80 Self(self.0 & !other.0)
81 }
82 pub const fn symmetric_difference(self, other: Self) -> Self {
83 Self(self.0 ^ other.0)
84 }
85 pub const fn complement(self) -> Self {
86 Self(!self.0 & Self::all().0)
87 }
88 pub fn insert(&mut self, other: Self) {
89 self.0 |= other.0;
90 }
91 pub fn remove(&mut self, other: Self) {
92 self.0 &= !other.0;
93 }
94 pub fn toggle(&mut self, other: Self) {
95 self.0 ^= other.0;
96 }
97 pub fn set(&mut self, other: Self, value: bool) {
98 if value {
99 self.0 |= other.0;
100 } else {
101 self.0 &= !other.0;
102 }
103 }
104}
105
106impl std::ops::BitOr for AccessControlFlags {
107 type Output = Self;
108 fn bitor(self, rhs: Self) -> Self {
109 Self(self.0 | rhs.0)
110 }
111}
112impl std::ops::BitAnd for AccessControlFlags {
113 type Output = Self;
114 fn bitand(self, rhs: Self) -> Self {
115 Self(self.0 & rhs.0)
116 }
117}
118impl std::ops::BitXor for AccessControlFlags {
119 type Output = Self;
120 fn bitxor(self, rhs: Self) -> Self {
121 Self(self.0 ^ rhs.0)
122 }
123}
124impl std::ops::Sub for AccessControlFlags {
125 type Output = Self;
126 fn sub(self, rhs: Self) -> Self {
127 Self(self.0 & !rhs.0)
128 }
129}
130impl std::ops::Not for AccessControlFlags {
131 type Output = Self;
132 fn not(self) -> Self {
133 Self(!self.0 & Self::all().0)
134 }
135}
136impl std::ops::BitOrAssign for AccessControlFlags {
137 fn bitor_assign(&mut self, rhs: Self) {
138 self.0 |= rhs.0;
139 }
140}
141impl std::ops::BitAndAssign for AccessControlFlags {
142 fn bitand_assign(&mut self, rhs: Self) {
143 self.0 &= rhs.0;
144 }
145}
146impl std::ops::BitXorAssign for AccessControlFlags {
147 fn bitxor_assign(&mut self, rhs: Self) {
148 self.0 ^= rhs.0;
149 }
150}
151impl std::ops::SubAssign for AccessControlFlags {
152 fn sub_assign(&mut self, rhs: Self) {
153 self.0 &= !rhs.0;
154 }
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
158pub enum AccessControlProtection {
160 #[default]
162 WhenUnlocked,
163 AfterFirstUnlock,
165 WhenPasscodeSetThisDeviceOnly,
167 WhenUnlockedThisDeviceOnly,
169 AfterFirstUnlockThisDeviceOnly,
171}
172
173impl AccessControlProtection {
174 const fn as_bridge_name(self) -> &'static str {
175 match self {
176 Self::WhenUnlocked => "when_unlocked",
177 Self::AfterFirstUnlock => "after_first_unlock",
178 Self::WhenPasscodeSetThisDeviceOnly => "when_passcode_set_this_device_only",
179 Self::WhenUnlockedThisDeviceOnly => "when_unlocked_this_device_only",
180 Self::AfterFirstUnlockThisDeviceOnly => "after_first_unlock_this_device_only",
181 }
182 }
183}
184
185#[derive(Debug, Clone)]
186pub struct AccessControl {
188 object: CoreFoundationHandle,
189 protection: AccessControlProtection,
190 flags: AccessControlFlags,
191}
192
193impl AccessControl {
194 pub fn type_id() -> usize {
196 unsafe { bridge::security_access_control_get_type_id() }
197 }
198
199 pub fn create(protection: AccessControlProtection, flags: AccessControlFlags) -> Result<Self> {
201 let protection_name = bridge::cstring(protection.as_bridge_name())?;
202 let mut status = 0;
203 let mut error = std::ptr::null_mut();
204 let raw = unsafe {
205 bridge::security_access_control_create(
206 protection_name.as_ptr(),
207 flags.bits(),
208 &raw mut status,
209 &raw mut error,
210 )
211 };
212 let Some(object) = CoreFoundationHandle::from_raw(raw) else {
213 return Err(bridge::status_error(
214 "security_access_control_create",
215 status,
216 error,
217 )?);
218 };
219 Ok(Self {
220 object,
221 protection,
222 flags,
223 })
224 }
225
226 pub fn is_valid(&self) -> bool {
228 !self.object.as_ptr().is_null()
229 }
230
231 pub const fn protection(&self) -> AccessControlProtection {
232 self.protection
233 }
234
235 pub const fn flags(&self) -> AccessControlFlags {
236 self.flags
237 }
238
239 pub const fn as_ptr(&self) -> *mut c_void {
240 self.object.as_ptr()
241 }
242}
243
244#[derive(Debug, Default)]
245pub struct KeychainOptions {
246 accessibility: AccessControlProtection,
247 access_control: Option<AccessControl>,
248 access_group: Option<String>,
249 synchronizable: bool,
250 data_protection_keychain: bool,
251 authentication_context: Option<Handle>,
252}
253
254impl KeychainOptions {
255 #[must_use]
256 pub fn accessibility(mut self, accessibility: AccessControlProtection) -> Self {
257 self.accessibility = accessibility;
258 self
259 }
260
261 #[must_use]
262 pub fn access_control(mut self, access_control: AccessControl) -> Self {
263 self.access_control = Some(access_control);
264 self
265 }
266
267 #[must_use]
268 pub fn access_group(mut self, access_group: impl Into<String>) -> Self {
269 self.access_group = Some(access_group.into());
270 self
271 }
272
273 #[must_use]
274 pub fn synchronizable(mut self, synchronizable: bool) -> Self {
275 self.synchronizable = synchronizable;
276 self
277 }
278
279 #[must_use]
280 pub fn data_protection_keychain(mut self, data_protection_keychain: bool) -> Self {
281 self.data_protection_keychain = data_protection_keychain;
282 self
283 }
284
285 #[allow(clippy::missing_safety_doc)]
286 pub unsafe fn authentication_context(mut self, la_context: *mut c_void) -> Result<Self> {
287 let raw = unsafe { bridge::security_authentication_context_retain(la_context) };
288 let handle = Handle::from_raw(raw).ok_or_else(|| {
289 SecurityError::InvalidArgument("authentication context must be an LAContext".to_owned())
290 })?;
291 self.authentication_context = Some(handle);
292 Ok(self)
293 }
294
295 fn bridge_value(&self) -> Value {
296 let mut options = std::collections::BTreeMap::from([
297 (
298 "accessibility".to_owned(),
299 Value::String(self.accessibility.as_bridge_name().to_owned()),
300 ),
301 (
302 "synchronizable".to_owned(),
303 Value::Bool(self.synchronizable),
304 ),
305 (
306 "data_protection_keychain".to_owned(),
307 Value::Bool(self.data_protection_keychain),
308 ),
309 ]);
310 if let Some(access_group) = &self.access_group {
311 options.insert(
312 "access_group".to_owned(),
313 Value::String(access_group.clone()),
314 );
315 }
316 Value::Object(options)
317 }
318
319 fn access_control_ptr(&self) -> *mut c_void {
320 self.access_control
321 .as_ref()
322 .map_or(std::ptr::null_mut(), AccessControl::as_ptr)
323 }
324
325 fn authentication_context_ptr(&self) -> *mut c_void {
326 self.authentication_context
327 .as_ref()
328 .map_or(std::ptr::null_mut(), Handle::as_ptr)
329 }
330}
331
332#[derive(Debug, Clone, PartialEq, Eq, Hash)]
333pub struct KeychainEntry {
335 account: String,
336 service: String,
337}
338
339impl KeychainEntry {
340 pub fn new(account: impl Into<String>, service: impl Into<String>) -> Self {
342 Self {
343 account: account.into(),
344 service: service.into(),
345 }
346 }
347
348 pub fn account(&self) -> &str {
350 &self.account
351 }
352
353 pub fn service(&self) -> &str {
355 &self.service
356 }
357
358 pub fn set(&self, secret: impl AsRef<[u8]>) -> Result<()> {
360 Keychain::set(&self.account, &self.service, secret)
361 }
362
363 pub fn get(&self) -> Result<SecretBytes> {
365 Keychain::get(&self.account, &self.service)
366 }
367
368 pub fn delete(&self) -> Result<()> {
370 Keychain::delete(&self.account, &self.service)
371 }
372}
373
374pub struct Keychain;
376
377impl Keychain {
378 pub fn entry(account: impl Into<String>, service: impl Into<String>) -> KeychainEntry {
380 KeychainEntry::new(account, service)
381 }
382
383 pub fn set(account: &str, service: &str, secret: impl AsRef<[u8]>) -> Result<()> {
385 Self::set_with_options(account, service, secret, &KeychainOptions::default())
386 }
387
388 pub fn get(account: &str, service: &str) -> Result<SecretBytes> {
390 Self::get_with_options(account, service, &KeychainOptions::default())
391 }
392
393 pub fn delete(account: &str, service: &str) -> Result<()> {
395 Self::delete_with_options(account, service, &KeychainOptions::default())
396 }
397
398 pub fn list_accounts(service: &str) -> Result<Vec<String>> {
400 Self::list_accounts_with_options(service, &KeychainOptions::default())
401 }
402
403 pub fn set_with_options(
404 account: &str,
405 service: &str,
406 secret: impl AsRef<[u8]>,
407 options: &KeychainOptions,
408 ) -> Result<()> {
409 let secret = secret.as_ref();
410 let account = bridge::cstring(account)?;
411 let service = bridge::cstring(service)?;
412 let options_value = bridge::InputValue::new(&options.bridge_value())?;
413 let mut error = std::ptr::null_mut();
414 let status = unsafe {
415 bridge::security_keychain_set_item(
416 account.as_ptr(),
417 service.as_ptr(),
418 secret.as_ptr().cast(),
419 bridge::len_to_isize(secret.len())?,
420 options_value.as_ptr(),
421 options.access_control_ptr(),
422 options.authentication_context_ptr(),
423 &raw mut error,
424 )
425 };
426 bridge::status_result("security_keychain_set_item", status, error)
427 }
428
429 pub fn get_with_options(
430 account: &str,
431 service: &str,
432 options: &KeychainOptions,
433 ) -> Result<SecretBytes> {
434 let account = bridge::cstring(account)?;
435 let service = bridge::cstring(service)?;
436 let options_value = bridge::InputValue::new(&options.bridge_value())?;
437 let mut status = 0;
438 let mut error = std::ptr::null_mut();
439 let raw = unsafe {
440 bridge::security_keychain_copy_item(
441 account.as_ptr(),
442 service.as_ptr(),
443 options_value.as_ptr(),
444 options.authentication_context_ptr(),
445 &raw mut status,
446 &raw mut error,
447 )
448 };
449 bridge::required_secret("security_keychain_copy_item", raw, status, error)
450 }
451
452 pub fn delete_with_options(
453 account: &str,
454 service: &str,
455 options: &KeychainOptions,
456 ) -> Result<()> {
457 let account = bridge::cstring(account)?;
458 let service = bridge::cstring(service)?;
459 let options_value = bridge::InputValue::new(&options.bridge_value())?;
460 let mut error = std::ptr::null_mut();
461 let status = unsafe {
462 bridge::security_keychain_delete_item(
463 account.as_ptr(),
464 service.as_ptr(),
465 options_value.as_ptr(),
466 options.authentication_context_ptr(),
467 &raw mut error,
468 )
469 };
470 bridge::status_result("security_keychain_delete_item", status, error)
471 }
472
473 pub fn list_accounts_with_options(
474 service: &str,
475 options: &KeychainOptions,
476 ) -> Result<Vec<String>> {
477 let service = bridge::cstring(service)?;
478 let options_value = bridge::InputValue::new(&options.bridge_value())?;
479 let mut status = 0;
480 let mut error = std::ptr::null_mut();
481 let raw = unsafe {
482 bridge::security_keychain_list_accounts(
483 service.as_ptr(),
484 options_value.as_ptr(),
485 options.authentication_context_ptr(),
486 &raw mut status,
487 &raw mut error,
488 )
489 };
490 bridge::required_value("security_keychain_list_accounts", raw, status, error)?
491 .into_strings("security_keychain_list_accounts")
492 }
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn access_control_protection_base_bridge_names_are_stable() {
501 assert_eq!(
502 AccessControlProtection::WhenUnlocked.as_bridge_name(),
503 "when_unlocked"
504 );
505 assert_eq!(
506 AccessControlProtection::AfterFirstUnlock.as_bridge_name(),
507 "after_first_unlock"
508 );
509 }
510
511 #[test]
512 fn access_control_protection_device_only_bridge_names_are_stable() {
513 assert_eq!(
514 AccessControlProtection::WhenPasscodeSetThisDeviceOnly.as_bridge_name(),
515 "when_passcode_set_this_device_only"
516 );
517 assert_eq!(
518 AccessControlProtection::WhenUnlockedThisDeviceOnly.as_bridge_name(),
519 "when_unlocked_this_device_only"
520 );
521 assert_eq!(
522 AccessControlProtection::AfterFirstUnlockThisDeviceOnly.as_bridge_name(),
523 "after_first_unlock_this_device_only"
524 );
525 }
526
527 #[test]
528 fn access_control_flags_round_trip_through_bits() {
529 let flags = AccessControlFlags::USER_PRESENCE
530 | AccessControlFlags::PRIVATE_KEY_USAGE
531 | AccessControlFlags::APPLICATION_PASSWORD;
532
533 assert_eq!(AccessControlFlags::from_bits(flags.bits()), Some(flags));
534 }
535
536 #[test]
537 fn default_options_protect_items_when_unlocked() {
538 let value = KeychainOptions::default().bridge_value();
539 assert_eq!(
540 value.get("accessibility").and_then(Value::as_str),
541 Some("when_unlocked")
542 );
543 assert_eq!(
544 value.get("synchronizable").and_then(Value::as_bool),
545 Some(false)
546 );
547 assert_eq!(
548 value
549 .get("data_protection_keychain")
550 .and_then(Value::as_bool),
551 Some(false)
552 );
553 assert!(value.get("access_group").is_none());
554 assert_eq!(
555 AccessControlProtection::default(),
556 AccessControlProtection::WhenUnlocked
557 );
558 }
559
560 #[test]
561 fn options_serialize_every_selected_control() {
562 let options = KeychainOptions::default()
563 .accessibility(AccessControlProtection::WhenUnlockedThisDeviceOnly)
564 .access_group("TEAMID.group")
565 .synchronizable(true)
566 .data_protection_keychain(true);
567 let value = options.bridge_value();
568 assert_eq!(
569 value.get("accessibility").and_then(Value::as_str),
570 Some("when_unlocked_this_device_only")
571 );
572 assert_eq!(
573 value.get("access_group").and_then(Value::as_str),
574 Some("TEAMID.group")
575 );
576 assert_eq!(
577 value.get("synchronizable").and_then(Value::as_bool),
578 Some(true)
579 );
580 assert_eq!(
581 value
582 .get("data_protection_keychain")
583 .and_then(Value::as_bool),
584 Some(true)
585 );
586 assert!(options.access_control_ptr().is_null());
587 assert!(options.authentication_context_ptr().is_null());
588 }
589
590 #[test]
591 fn keychain_entry_new_preserves_account_and_service() {
592 let entry = KeychainEntry::new("alice", "security-rs.tests");
593
594 assert_eq!(entry.account(), "alice");
595 assert_eq!(entry.service(), "security-rs.tests");
596 }
597
598 #[test]
599 fn keychain_entry_convenience_constructor_matches_new() {
600 let entry = Keychain::entry("alice", "security-rs.tests");
601
602 assert_eq!(entry, KeychainEntry::new("alice", "security-rs.tests"));
603 }
604}