Skip to main content

localauthentication/
la_context.rs

1//! `LAContext` and related `LocalAuthentication` value types.
2
3use core::ffi::c_void;
4use std::collections::BTreeMap;
5use std::ptr;
6
7use security::AccessControl;
8
9use crate::ffi;
10use crate::la_credential::{LACredential, LACredentialType};
11use crate::la_error::{from_status, LAError, Result};
12use crate::la_policy::LAPolicy;
13use crate::private::{
14    bridge_bool, bridge_f64, bridge_i32, bridge_i32_vec, bridge_opt_bytes, bridge_opt_string,
15    bridge_ptr, bridge_string, bridge_unit, cstring, framework_bool_result, OwnedHandle,
16};
17
18/// Biometry kinds reported by `LAContext`.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20#[non_exhaustive]
21pub enum BiometryType {
22    None,
23    TouchId,
24    FaceId,
25    OpticId,
26    Unknown(i32),
27}
28
29impl BiometryType {
30    #[must_use]
31    pub const fn from_ffi(value: i32) -> Self {
32        match value {
33            ffi::biometry::NONE => Self::None,
34            ffi::biometry::TOUCH_ID => Self::TouchId,
35            ffi::biometry::FACE_ID => Self::FaceId,
36            ffi::biometry::OPTIC_ID => Self::OpticId,
37            other => Self::Unknown(other),
38        }
39    }
40}
41
42/// Companion kinds reported by `LADomainState`.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44#[non_exhaustive]
45pub enum LACompanionType {
46    Watch,
47    Mac,
48    Vision,
49    Unknown(i32),
50}
51
52impl LACompanionType {
53    #[must_use]
54    pub const fn from_ffi(value: i32) -> Self {
55        match value {
56            ffi::companion::WATCH => Self::Watch,
57            ffi::companion::MAC => Self::Mac,
58            ffi::companion::VISION => Self::Vision,
59            other => Self::Unknown(other),
60        }
61    }
62
63    #[must_use]
64    pub const fn raw_value(self) -> i32 {
65        match self {
66            Self::Watch => ffi::companion::WATCH,
67            Self::Mac => ffi::companion::MAC,
68            Self::Vision => ffi::companion::VISION,
69            Self::Unknown(value) => value,
70        }
71    }
72}
73
74/// Access-control operations supported by `LAContext::evaluate_access_control`.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum LAAccessControlOperation {
78    CreateItem,
79    UseItem,
80    CreateKey,
81    UseKeySign,
82    UseKeyDecrypt,
83    UseKeyKeyExchange,
84}
85
86impl LAAccessControlOperation {
87    #[must_use]
88    pub const fn raw_value(self) -> i32 {
89        match self {
90            Self::CreateItem => ffi::la_context::ACCESS_CONTROL_OPERATION_CREATE_ITEM,
91            Self::UseItem => ffi::la_context::ACCESS_CONTROL_OPERATION_USE_ITEM,
92            Self::CreateKey => ffi::la_context::ACCESS_CONTROL_OPERATION_CREATE_KEY,
93            Self::UseKeySign => ffi::la_context::ACCESS_CONTROL_OPERATION_USE_KEY_SIGN,
94            Self::UseKeyDecrypt => ffi::la_context::ACCESS_CONTROL_OPERATION_USE_KEY_DECRYPT,
95            Self::UseKeyKeyExchange => {
96                ffi::la_context::ACCESS_CONTROL_OPERATION_USE_KEY_KEY_EXCHANGE
97            }
98        }
99    }
100}
101
102/// A snapshot of `LAContext.domainState.biometry`.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct LADomainStateBiometry {
105    biometry_type: BiometryType,
106    state_hash: Option<Vec<u8>>,
107}
108
109impl LADomainStateBiometry {
110    #[must_use]
111    pub const fn biometry_type(&self) -> BiometryType {
112        self.biometry_type
113    }
114
115    #[must_use]
116    pub fn state_hash(&self) -> Option<&[u8]> {
117        self.state_hash.as_deref()
118    }
119}
120
121/// A snapshot of `LAContext.domainState.companion`.
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct LADomainStateCompanion {
124    available_companion_types: Vec<LACompanionType>,
125    state_hash: Option<Vec<u8>>,
126    per_type_state_hashes: BTreeMap<LACompanionType, Vec<u8>>,
127}
128
129impl LADomainStateCompanion {
130    #[must_use]
131    pub fn available_companion_types(&self) -> &[LACompanionType] {
132        &self.available_companion_types
133    }
134
135    #[must_use]
136    pub fn state_hash(&self) -> Option<&[u8]> {
137        self.state_hash.as_deref()
138    }
139
140    #[must_use]
141    pub fn state_hash_for(&self, companion_type: LACompanionType) -> Option<&[u8]> {
142        self.per_type_state_hashes
143            .get(&companion_type)
144            .map(std::vec::Vec::as_slice)
145    }
146}
147
148/// A snapshot of `LAContext.domainState`.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct LADomainState {
151    state_hash: Option<Vec<u8>>,
152    biometry: LADomainStateBiometry,
153    companion: Option<LADomainStateCompanion>,
154}
155
156impl LADomainState {
157    #[must_use]
158    pub fn state_hash(&self) -> Option<&[u8]> {
159        self.state_hash.as_deref()
160    }
161
162    #[must_use]
163    pub const fn biometry(&self) -> &LADomainStateBiometry {
164        &self.biometry
165    }
166
167    #[must_use]
168    pub const fn companion(&self) -> Option<&LADomainStateCompanion> {
169        self.companion.as_ref()
170    }
171}
172
173/// Managed wrapper around Apple's `LAContext`.
174#[derive(Debug)]
175pub struct LAContext {
176    handle: OwnedHandle,
177}
178
179impl LAContext {
180    /// Create a new authentication context.
181    ///
182    /// # Errors
183    ///
184    /// Returns an error if the Swift bridge fails to allocate the underlying `LAContext`.
185    pub fn new() -> Result<Self> {
186        let raw = bridge_ptr(|out, error_out| unsafe {
187            ffi::la_context::la_context_new(out, error_out)
188        })?;
189        Ok(Self {
190            handle: OwnedHandle::new(raw, ffi::la_context::la_context_release),
191        })
192    }
193
194    /// Invalidate this context.
195    ///
196    /// # Errors
197    ///
198    /// Returns an error if the Swift bridge rejects the request.
199    pub fn invalidate(&self) -> Result<()> {
200        bridge_unit(|error_out| unsafe {
201            ffi::la_context::la_context_invalidate(self.handle.as_ptr(), error_out)
202        })
203    }
204
205    /// Check whether a policy can be evaluated without prompting the user.
206    ///
207    /// # Errors
208    ///
209    /// Returns a mapped framework error when the policy is unavailable, or a bridge error if the request itself fails.
210    pub fn can_evaluate_policy(&self, policy: LAPolicy) -> Result<bool> {
211        let mut out_can_evaluate = 0_u8;
212        let mut framework_error_code = 0_i32;
213        let mut framework_error_message = ptr::null_mut();
214        let mut bridge_error = ptr::null_mut();
215
216        let status = unsafe {
217            ffi::la_context::la_context_can_evaluate_policy(
218                self.handle.as_ptr(),
219                policy.as_ffi(),
220                &raw mut out_can_evaluate,
221                &raw mut framework_error_code,
222                &raw mut framework_error_message,
223                &raw mut bridge_error,
224            )
225        };
226        if status != ffi::status::OK {
227            return Err(from_status(status, bridge_error));
228        }
229
230        framework_bool_result(
231            out_can_evaluate != 0,
232            framework_error_code,
233            framework_error_message,
234        )
235    }
236
237    /// Evaluate a policy with the supplied localized reason string.
238    ///
239    /// # Errors
240    ///
241    /// Returns a mapped framework or bridge error when evaluation fails.
242    pub fn evaluate_policy(&self, policy: LAPolicy, localized_reason: &str) -> Result<bool> {
243        if localized_reason.is_empty() {
244            return Err(LAError::InvalidArgument(
245                "localized reason must not be empty".to_owned(),
246            ));
247        }
248
249        let localized_reason = cstring(localized_reason)?;
250        bridge_bool(|out, error_out| unsafe {
251            ffi::la_context::la_context_evaluate_policy(
252                self.handle.as_ptr(),
253                policy.as_ffi(),
254                localized_reason.as_ptr(),
255                out,
256                error_out,
257            )
258        })
259    }
260
261    /// Evaluate a `SecAccessControlRef` for the given operation.
262    ///
263    /// # Errors
264    ///
265    /// Returns a mapped framework or bridge error when evaluation fails.
266    pub fn evaluate_access_control(
267        &self,
268        access_control: &AccessControl,
269        operation: LAAccessControlOperation,
270        localized_reason: &str,
271    ) -> Result<bool> {
272        if localized_reason.is_empty() {
273            return Err(LAError::InvalidArgument(
274                "localized reason must not be empty".to_owned(),
275            ));
276        }
277
278        let localized_reason = cstring(localized_reason)?;
279        bridge_bool(|out, error_out| unsafe {
280            ffi::la_context::la_context_evaluate_access_control(
281                self.handle.as_ptr(),
282                access_control.as_ptr().cast_const(),
283                operation.raw_value(),
284                localized_reason.as_ptr(),
285                out,
286                error_out,
287            )
288        })
289    }
290
291    /// Read the localized fallback title.
292    ///
293    /// # Errors
294    ///
295    /// Returns an error if the Swift bridge rejects the request.
296    pub fn localized_fallback_title(&self) -> Result<Option<String>> {
297        bridge_opt_string(|out, error_out| unsafe {
298            ffi::la_context::la_context_get_localized_fallback_title(
299                self.handle.as_ptr(),
300                out,
301                error_out,
302            )
303        })
304    }
305
306    /// Update the localized fallback title. Pass `None` to restore the default title.
307    ///
308    /// # Errors
309    ///
310    /// Returns an error if the title contains an interior NUL byte or the Swift bridge rejects the request.
311    pub fn set_localized_fallback_title(&self, title: Option<&str>) -> Result<()> {
312        let title = title.map(cstring).transpose()?;
313        bridge_unit(|error_out| unsafe {
314            ffi::la_context::la_context_set_localized_fallback_title(
315                self.handle.as_ptr(),
316                title.as_ref().map_or(ptr::null(), |value| value.as_ptr()),
317                error_out,
318            )
319        })
320    }
321
322    /// Read the localized cancel title.
323    ///
324    /// # Errors
325    ///
326    /// Returns an error if the Swift bridge rejects the request.
327    pub fn localized_cancel_title(&self) -> Result<Option<String>> {
328        bridge_opt_string(|out, error_out| unsafe {
329            ffi::la_context::la_context_get_localized_cancel_title(
330                self.handle.as_ptr(),
331                out,
332                error_out,
333            )
334        })
335    }
336
337    /// Update the localized cancel title. Pass `None` to restore the default title.
338    ///
339    /// # Errors
340    ///
341    /// Returns an error if the title contains an interior NUL byte or the Swift bridge rejects the request.
342    pub fn set_localized_cancel_title(&self, title: Option<&str>) -> Result<()> {
343        let title = title.map(cstring).transpose()?;
344        bridge_unit(|error_out| unsafe {
345            ffi::la_context::la_context_set_localized_cancel_title(
346                self.handle.as_ptr(),
347                title.as_ref().map_or(ptr::null(), |value| value.as_ptr()),
348                error_out,
349            )
350        })
351    }
352
353    /// Read the default localized reason used for authentication requests.
354    ///
355    /// # Errors
356    ///
357    /// Returns an error if the Swift bridge rejects the request.
358    pub fn localized_reason(&self) -> Result<String> {
359        bridge_string(|out, error_out| unsafe {
360            ffi::la_context::la_context_get_localized_reason(self.handle.as_ptr(), out, error_out)
361        })
362    }
363
364    /// Update the default localized reason used for authentication requests.
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if the string contains an interior NUL byte or the Swift bridge rejects the request.
369    pub fn set_localized_reason(&self, localized_reason: &str) -> Result<()> {
370        let localized_reason = cstring(localized_reason)?;
371        bridge_unit(|error_out| unsafe {
372            ffi::la_context::la_context_set_localized_reason(
373                self.handle.as_ptr(),
374                localized_reason.as_ptr(),
375                error_out,
376            )
377        })
378    }
379
380    /// Read the allowable biometric reuse duration, in seconds.
381    ///
382    /// # Errors
383    ///
384    /// Returns an error if the Swift bridge rejects the request.
385    pub fn touch_id_authentication_allowable_reuse_duration(&self) -> Result<f64> {
386        bridge_f64(|out, error_out| unsafe {
387            ffi::la_context::la_context_get_touch_id_authentication_allowable_reuse_duration(
388                self.handle.as_ptr(),
389                out,
390                error_out,
391            )
392        })
393    }
394
395    /// Backward-compatible alias for `touch_id_authentication_allowable_reuse_duration`.
396    ///
397    /// # Errors
398    ///
399    /// Propagates any error returned by `touch_id_authentication_allowable_reuse_duration`.
400    pub fn allowable_reuse_duration(&self) -> Result<f64> {
401        self.touch_id_authentication_allowable_reuse_duration()
402    }
403
404    /// Update the allowable biometric reuse duration, in seconds.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if the value is negative, non-finite, or the Swift bridge rejects the request.
409    pub fn set_touch_id_authentication_allowable_reuse_duration(
410        &self,
411        duration: f64,
412    ) -> Result<()> {
413        if !duration.is_finite() || duration < 0.0 {
414            return Err(LAError::InvalidArgument(
415                "allowable reuse duration must be a finite, non-negative number".to_owned(),
416            ));
417        }
418
419        bridge_unit(|error_out| unsafe {
420            ffi::la_context::la_context_set_touch_id_authentication_allowable_reuse_duration(
421                self.handle.as_ptr(),
422                duration,
423                error_out,
424            )
425        })
426    }
427
428    /// Backward-compatible alias for `set_touch_id_authentication_allowable_reuse_duration`.
429    ///
430    /// # Errors
431    ///
432    /// Propagates any error returned by `set_touch_id_authentication_allowable_reuse_duration`.
433    pub fn set_allowable_reuse_duration(&self, duration: f64) -> Result<()> {
434        self.set_touch_id_authentication_allowable_reuse_duration(duration)
435    }
436
437    /// The framework-defined maximum reuse duration, in seconds.
438    #[must_use]
439    pub fn touch_id_authentication_maximum_allowable_reuse_duration() -> f64 {
440        unsafe {
441            ffi::la_context::la_context_get_touch_id_authentication_maximum_allowable_reuse_duration(
442            )
443        }
444    }
445
446    /// Read whether interactive authentication UI is disabled.
447    ///
448    /// # Errors
449    ///
450    /// Returns an error if the Swift bridge rejects the request.
451    pub fn interaction_not_allowed(&self) -> Result<bool> {
452        bridge_bool(|out, error_out| unsafe {
453            ffi::la_context::la_context_get_interaction_not_allowed(
454                self.handle.as_ptr(),
455                out,
456                error_out,
457            )
458        })
459    }
460
461    /// Enable or disable interactive authentication UI.
462    ///
463    /// # Errors
464    ///
465    /// Returns an error if the Swift bridge rejects the request.
466    pub fn set_interaction_not_allowed(&self, value: bool) -> Result<()> {
467        bridge_unit(|error_out| unsafe {
468            ffi::la_context::la_context_set_interaction_not_allowed(
469                self.handle.as_ptr(),
470                u8::from(value),
471                error_out,
472            )
473        })
474    }
475
476    /// Read the currently reported biometry type.
477    ///
478    /// # Errors
479    ///
480    /// Returns an error if the Swift bridge rejects the request.
481    pub fn biometry_type(&self) -> Result<BiometryType> {
482        let raw = bridge_i32(|out, error_out| unsafe {
483            ffi::la_context::la_context_get_biometry_type(self.handle.as_ptr(), out, error_out)
484        })?;
485        Ok(BiometryType::from_ffi(raw))
486    }
487
488    /// Read the evaluated policy domain state bytes, if any are available.
489    ///
490    /// # Errors
491    ///
492    /// Returns an error if the Swift bridge rejects the request.
493    pub fn evaluated_policy_domain_state(&self) -> Result<Option<Vec<u8>>> {
494        bridge_opt_bytes(|out, out_len, error_out| unsafe {
495            ffi::la_context::la_context_get_evaluated_policy_domain_state(
496                self.handle.as_ptr(),
497                out,
498                out_len,
499                error_out,
500            )
501        })
502    }
503
504    /// Set an application-provided credential for subsequent authentication operations.
505    ///
506    /// # Errors
507    ///
508    /// Returns an error if the Swift bridge rejects the request.
509    pub fn set_credential(&self, credential: &LACredential) -> Result<bool> {
510        let bytes = credential.bytes();
511        bridge_bool(|out, error_out| unsafe {
512            ffi::la_context::la_context_set_credential(
513                self.handle.as_ptr(),
514                bytes.as_ptr(),
515                bytes.len(),
516                credential.credential_type().as_ffi(),
517                1,
518                out,
519                error_out,
520            )
521        })
522    }
523
524    /// Remove any previously-supplied credential of the given type.
525    ///
526    /// # Errors
527    ///
528    /// Returns an error if the Swift bridge rejects the request.
529    pub fn clear_credential(&self, credential_type: LACredentialType) -> Result<bool> {
530        bridge_bool(|out, error_out| unsafe {
531            ffi::la_context::la_context_set_credential(
532                self.handle.as_ptr(),
533                ptr::null(),
534                0,
535                credential_type.as_ffi(),
536                0,
537                out,
538                error_out,
539            )
540        })
541    }
542
543    /// Check whether a credential of the given type is currently stored on this context.
544    ///
545    /// # Errors
546    ///
547    /// Returns an error if the Swift bridge rejects the request.
548    pub fn is_credential_set(&self, credential_type: LACredentialType) -> Result<bool> {
549        bridge_bool(|out, error_out| unsafe {
550            ffi::la_context::la_context_is_credential_set(
551                self.handle.as_ptr(),
552                credential_type.as_ffi(),
553                out,
554                error_out,
555            )
556        })
557    }
558
559    /// Read the richer `domainState` snapshot available on macOS 15 and newer.
560    ///
561    /// # Errors
562    ///
563    /// Returns an error if the property is unavailable or the Swift bridge rejects the request.
564    pub fn domain_state(&self) -> Result<LADomainState> {
565        let state_hash = bridge_opt_bytes(|out, out_len, error_out| unsafe {
566            ffi::la_context::la_context_get_domain_state_hash(
567                self.handle.as_ptr(),
568                out,
569                out_len,
570                error_out,
571            )
572        })?;
573        let biometry_type = BiometryType::from_ffi(bridge_i32(|out, error_out| unsafe {
574            ffi::la_context::la_context_get_domain_state_biometry_type(
575                self.handle.as_ptr(),
576                out,
577                error_out,
578            )
579        })?);
580        let biometry_state_hash = bridge_opt_bytes(|out, out_len, error_out| unsafe {
581            ffi::la_context::la_context_get_domain_state_biometry_hash(
582                self.handle.as_ptr(),
583                out,
584                out_len,
585                error_out,
586            )
587        })?;
588        let companion_types_raw = bridge_i32_vec(|out, out_len, error_out| unsafe {
589            ffi::la_context::la_context_get_domain_state_companion_types(
590                self.handle.as_ptr(),
591                out,
592                out_len,
593                error_out,
594            )
595        })?;
596        let companion_types: Vec<LACompanionType> = companion_types_raw
597            .into_iter()
598            .map(LACompanionType::from_ffi)
599            .collect();
600        let companion_state_hash = bridge_opt_bytes(|out, out_len, error_out| unsafe {
601            ffi::la_context::la_context_get_domain_state_companion_hash(
602                self.handle.as_ptr(),
603                out,
604                out_len,
605                error_out,
606            )
607        })?;
608
609        let mut per_type_state_hashes = BTreeMap::new();
610        for companion_type in &companion_types {
611            if let Some(hash) = bridge_opt_bytes(|out, out_len, error_out| unsafe {
612                ffi::la_context::la_context_get_domain_state_companion_hash_for_type(
613                    self.handle.as_ptr(),
614                    companion_type.raw_value(),
615                    out,
616                    out_len,
617                    error_out,
618                )
619            })? {
620                per_type_state_hashes.insert(*companion_type, hash);
621            }
622        }
623
624        Ok(LADomainState {
625            state_hash,
626            biometry: LADomainStateBiometry {
627                biometry_type,
628                state_hash: biometry_state_hash,
629            },
630            companion: Some(LADomainStateCompanion {
631                available_companion_types: companion_types,
632                state_hash: companion_state_hash,
633                per_type_state_hashes,
634            }),
635        })
636    }
637
638    #[must_use]
639    pub fn as_raw_la_context(&self) -> *mut c_void {
640        unsafe { ffi::la_context::la_context_raw_la_context(self.handle.as_ptr()) }
641    }
642
643    /// Internal helper to get the raw pointer for FFI calls.
644    ///
645    /// Used by the async API module. This is intentionally non-public.
646    #[cfg(feature = "async")]
647    pub(crate) const fn as_ptr(&self) -> *mut c_void {
648        self.handle.as_ptr()
649    }
650}
651
652impl Drop for LAContext {
653    fn drop(&mut self) {
654        let _ = self.invalidate();
655    }
656}
657
658#[cfg(test)]
659mod tests {
660    use core::ffi::{c_char, c_void};
661    use std::ffi::CStr;
662    use std::ptr::{self, NonNull};
663
664    use super::{LAAccessControlOperation, LACompanionType, LAContext, Result};
665    use crate::ffi;
666    use crate::private::OwnedHandle;
667    use crate::{LACredential, LACredentialType, LAError, LAPolicy};
668
669    unsafe extern "C" {
670        fn objc_retain(object: *mut c_void) -> *mut c_void;
671        fn object_getClassName(object: *mut c_void) -> *const c_char;
672    }
673
674    #[link(name = "CoreFoundation", kind = "framework")]
675    unsafe extern "C" {
676        fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: isize) -> *mut c_void;
677        fn CFRelease(cf: *const c_void);
678    }
679
680    #[test]
681    fn dropping_a_context_invalidates_it() -> Result<()> {
682        let context = LAContext::new()?;
683        context.set_interaction_not_allowed(true)?;
684        let raw = context.handle.as_ptr();
685        unsafe { objc_retain(raw) };
686        let shared = LAContext {
687            handle: OwnedHandle::new(
688                NonNull::new(raw).expect("handle"),
689                ffi::la_context::la_context_release,
690            ),
691        };
692        let before = shared.can_evaluate_policy(LAPolicy::DeviceOwnerAuthentication);
693        assert!(
694            !matches!(before, Err(LAError::InvalidContext(_))),
695            "{before:?}"
696        );
697
698        drop(context);
699
700        let after = shared.can_evaluate_policy(LAPolicy::DeviceOwnerAuthentication);
701        assert!(
702            matches!(after, Err(LAError::InvalidContext(_))),
703            "{after:?}"
704        );
705        Ok(())
706    }
707
708    #[test]
709    fn handles_of_another_type_are_rejected() -> Result<()> {
710        let right = crate::LARight::new()?;
711        let mut error = std::ptr::null_mut();
712        let status =
713            unsafe { ffi::la_context::la_context_invalidate(right.as_ptr(), &raw mut error) };
714        let error = crate::la_error::from_status(status, error);
715        assert!(
716            matches!(&error, LAError::InvalidArgument(message) if message.contains("LAContext")),
717            "{error:?}"
718        );
719        assert!(right.check_can_authorize().is_ok() || right.state().is_ok());
720        Ok(())
721    }
722
723    #[test]
724    fn the_bridge_rejects_objects_that_are_not_access_controls() -> Result<()> {
725        let context = LAContext::new()?;
726        context.set_interaction_not_allowed(true)?;
727        let bytes = [0_u8; 4];
728        let data = unsafe { CFDataCreate(ptr::null(), bytes.as_ptr(), 4) };
729        assert!(!data.is_null());
730        let mut success = 0_u8;
731        let mut error = ptr::null_mut();
732        let status = unsafe {
733            ffi::la_context::la_context_evaluate_access_control(
734                context.handle.as_ptr(),
735                data.cast_const(),
736                LAAccessControlOperation::UseItem.raw_value(),
737                c"Authenticate".as_ptr(),
738                &raw mut success,
739                &raw mut error,
740            )
741        };
742        unsafe { CFRelease(data) };
743        let error = crate::la_error::from_status(status, error);
744        assert!(
745            matches!(&error, LAError::InvalidArgument(message) if message.contains("SecAccessControl")),
746            "{error:?}"
747        );
748        assert_eq!(success, 0);
749        Ok(())
750    }
751
752    #[test]
753    fn the_raw_context_is_the_objective_c_la_context() -> Result<()> {
754        let context = LAContext::new()?;
755        let raw = context.as_raw_la_context();
756        assert!(!raw.is_null());
757        assert_ne!(raw, context.handle.as_ptr());
758        let class_name = unsafe { CStr::from_ptr(object_getClassName(raw)) };
759        assert_eq!(class_name.to_str(), Ok("LAContext"));
760        assert_eq!(context.as_raw_la_context(), raw);
761        Ok(())
762    }
763
764    #[test]
765    fn property_round_trip_without_prompt() -> Result<()> {
766        let context = LAContext::new()?;
767        context.set_interaction_not_allowed(true)?;
768        context.set_localized_fallback_title(Some("Use Password"))?;
769        context.set_localized_cancel_title(Some("Cancel"))?;
770        context.set_localized_reason("Test local authentication")?;
771        context.set_allowable_reuse_duration(30.0)?;
772        let credential = LACredential::application_password(b"secret".to_vec());
773
774        assert!(context.set_credential(&credential)?);
775        assert!(context.is_credential_set(LACredentialType::ApplicationPassword)?);
776        assert!(context.clear_credential(LACredentialType::ApplicationPassword)?);
777        assert!(!context.is_credential_set(LACredentialType::ApplicationPassword)?);
778        assert!(context.interaction_not_allowed()?);
779        assert_eq!(
780            context.localized_fallback_title()?.as_deref(),
781            Some("Use Password")
782        );
783        assert_eq!(context.localized_cancel_title()?.as_deref(), Some("Cancel"));
784        assert_eq!(context.localized_reason()?, "Test local authentication");
785        assert!((context.allowable_reuse_duration()? - 30.0).abs() < f64::EPSILON);
786        assert!(LAContext::touch_id_authentication_maximum_allowable_reuse_duration() >= 300.0);
787
788        let _ = context.can_evaluate_policy(LAPolicy::DeviceOwnerAuthenticationWithBiometrics);
789        let domain_state = context.domain_state()?;
790        let _ = domain_state.biometry().biometry_type();
791        if let Some(companion) = domain_state.companion() {
792            for companion_type in companion.available_companion_types() {
793                let _ = companion.state_hash_for(*companion_type);
794            }
795            let _ = companion.state_hash_for(LACompanionType::Watch);
796        }
797        Ok(())
798    }
799}