Skip to main content

localauthentication/
async_api.rs

1//! Async API for `LocalAuthentication`
2//!
3//! This module provides async versions of authentication operations when the `async` feature is enabled.
4//! The async API is **executor-agnostic** and works with any async runtime (Tokio, async-std, smol, etc.).
5
6use crate::la_context::LAContext;
7use crate::la_error::{LAError, Result};
8use crate::la_policy::LAPolicy;
9use doom_fish_utils::completion::{error_from_cstr, AsyncCompletion, AsyncCompletionFuture};
10use doom_fish_utils::panic_safe::catch_user_panic;
11use security::AccessControl;
12use std::ffi::{c_char, c_void};
13use std::future::Future;
14use std::pin::Pin;
15use std::task::{Context, Poll};
16
17// ============================================================================
18// Callbacks for async operations
19// ============================================================================
20
21type EvaluationResult = Result<bool>;
22
23extern "C" fn evaluation_callback(
24    success: u8,
25    status: i32,
26    error: *const c_char,
27    user_data: *mut c_void,
28) {
29    catch_user_panic("evaluation_callback", || {
30        let result = if status == crate::ffi::status::OK {
31            Ok(success != 0)
32        } else {
33            let message = if error.is_null() {
34                String::new()
35            } else {
36                // SAFETY: error is a valid C string from Swift bridge
37                unsafe { error_from_cstr(error) }
38            };
39            Err(LAError::from_code_message(status, message))
40        };
41        // SAFETY: user_data points to a valid AsyncCompletion<EvaluationResult> created by AsyncCompletion::create()
42        unsafe { AsyncCompletion::<EvaluationResult>::complete_ok(user_data, result) };
43    });
44}
45
46// ============================================================================
47// Future types
48// ============================================================================
49
50/// Future for async policy evaluation
51pub struct AsyncPolicyEvaluation {
52    inner: AsyncCompletionFuture<EvaluationResult>,
53}
54
55impl std::fmt::Debug for AsyncPolicyEvaluation {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        f.debug_struct("AsyncPolicyEvaluation")
58            .finish_non_exhaustive()
59    }
60}
61
62impl Future for AsyncPolicyEvaluation {
63    type Output = Result<bool>;
64
65    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
66        Pin::new(&mut self.inner).poll(cx).map(|result| {
67            result
68                .map_err(LAError::BridgeFailed)
69                .and_then(|result| result)
70        })
71    }
72}
73
74/// Future for async access control evaluation
75pub struct AsyncAccessControlEvaluation {
76    inner: AsyncCompletionFuture<EvaluationResult>,
77}
78
79impl std::fmt::Debug for AsyncAccessControlEvaluation {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.debug_struct("AsyncAccessControlEvaluation")
82            .finish_non_exhaustive()
83    }
84}
85
86impl Future for AsyncAccessControlEvaluation {
87    type Output = Result<bool>;
88
89    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
90        Pin::new(&mut self.inner).poll(cx).map(|result| {
91            result
92                .map_err(LAError::BridgeFailed)
93                .and_then(|result| result)
94        })
95    }
96}
97
98// ============================================================================
99// Async operations extension trait
100// ============================================================================
101
102/// Extension trait adding async methods to `LAContext`
103pub trait AsyncContextExt {
104    /// Asynchronously evaluate a policy
105    ///
106    /// # Errors
107    ///
108    /// Returns an error if the localized reason is empty or contains a null byte.
109    fn evaluate_policy_async(
110        &self,
111        policy: LAPolicy,
112        localized_reason: &str,
113    ) -> Result<AsyncPolicyEvaluation>;
114
115    /// Asynchronously evaluate an access control
116    ///
117    /// # Errors
118    ///
119    /// Returns an error if the localized reason is empty or contains a null byte.
120    fn evaluate_access_control_async(
121        &self,
122        access_control: &AccessControl,
123        operation: crate::la_context::LAAccessControlOperation,
124        localized_reason: &str,
125    ) -> Result<AsyncAccessControlEvaluation>;
126}
127
128impl AsyncContextExt for LAContext {
129    /// Asynchronously evaluate a policy
130    ///
131    /// Uses callback-based Swift FFI for true async operation.
132    ///
133    /// # Arguments
134    ///
135    /// * `policy` - The authentication policy to evaluate
136    /// * `localized_reason` - A localized reason shown to the user
137    fn evaluate_policy_async(
138        &self,
139        policy: LAPolicy,
140        localized_reason: &str,
141    ) -> Result<AsyncPolicyEvaluation> {
142        if localized_reason.is_empty() {
143            return Err(crate::la_error::LAError::InvalidArgument(
144                "localized reason must not be empty".to_owned(),
145            ));
146        }
147
148        let reason_cstring = std::ffi::CString::new(localized_reason).map_err(|_| {
149            LAError::InvalidArgument("localized reason contains null byte".to_owned())
150        })?;
151        let (future, ctx) = AsyncCompletion::create();
152
153        let context_ptr = self.as_ptr();
154
155        unsafe {
156            crate::ffi::la_context::la_context_evaluate_policy_async(
157                context_ptr,
158                policy.as_ffi(),
159                reason_cstring.as_ptr(),
160                evaluation_callback,
161                ctx,
162            );
163        }
164
165        Ok(AsyncPolicyEvaluation { inner: future })
166    }
167
168    /// Asynchronously evaluate an access control
169    ///
170    /// Uses callback-based Swift FFI for true async operation.
171    ///
172    /// # Arguments
173    ///
174    /// * `access_control` - The `SecAccessControl` to evaluate
175    /// * `operation` - The access control operation to evaluate
176    /// * `localized_reason` - A localized reason shown to the user
177    fn evaluate_access_control_async(
178        &self,
179        access_control: &AccessControl,
180        operation: crate::la_context::LAAccessControlOperation,
181        localized_reason: &str,
182    ) -> Result<AsyncAccessControlEvaluation> {
183        if localized_reason.is_empty() {
184            return Err(crate::la_error::LAError::InvalidArgument(
185                "localized reason must not be empty".to_owned(),
186            ));
187        }
188
189        let reason_cstring = std::ffi::CString::new(localized_reason).map_err(|_| {
190            LAError::InvalidArgument("localized reason contains null byte".to_owned())
191        })?;
192        let (future, ctx) = AsyncCompletion::create();
193
194        let context_ptr = self.as_ptr();
195
196        unsafe {
197            crate::ffi::la_context::la_context_evaluate_access_control_async(
198                context_ptr,
199                access_control.as_ptr().cast_const(),
200                operation.raw_value(),
201                reason_cstring.as_ptr(),
202                evaluation_callback,
203                ctx,
204            );
205        }
206
207        Ok(AsyncAccessControlEvaluation { inner: future })
208    }
209}