Skip to main content

security/async_api/
mod.rs

1//! Executor-agnostic async wrappers for callback-based `Security.framework` APIs.
2//!
3//! Enabled with the `async` Cargo feature.
4//!
5//! ## Wrapped APIs
6//!
7//! - [`AsyncTrust::evaluate`] wraps `SecTrustEvaluateAsyncWithError`.
8//! - [`AsyncAuthorization::copy_rights`] wraps `AuthorizationCopyRightsAsync`.
9
10#![cfg(feature = "async")]
11
12use core::ffi::c_void;
13use core::marker::PhantomData;
14use core::pin::Pin;
15use core::task::{Context, Poll};
16use std::future::Future;
17use std::panic::{catch_unwind, AssertUnwindSafe};
18use std::ptr;
19
20use crate::Value;
21
22use crate::authorization::{rights_value, Authorization, AuthorizationOptions};
23use crate::bridge;
24use crate::error::{status, Result, SecurityError};
25use crate::trust::Trust;
26
27mod completion;
28use completion::Completion;
29
30fn flatten_async_result<T>(result: std::result::Result<Result<T>, String>) -> Result<T> {
31    result
32        .map_err(SecurityError::Serialization)
33        .and_then(|result| result)
34}
35
36fn bridge_status_error(
37    operation: &'static str,
38    status: i32,
39    error_raw: *mut c_void,
40) -> SecurityError {
41    match bridge::status_error(operation, status, error_raw) {
42        Ok(error) | Err(error) => error,
43    }
44}
45
46fn trust_failure(error_raw: *mut c_void) -> SecurityError {
47    match bridge::optional_string(error_raw) {
48        Ok(Some(message)) => SecurityError::TrustEvaluationFailed(message),
49        Ok(None) => SecurityError::TrustEvaluationFailed("trust evaluation failed".to_owned()),
50        Err(error) => error,
51    }
52}
53
54unsafe extern "C" fn trust_evaluate_async_cb(
55    refcon: *mut c_void,
56    trusted: bool,
57    error_raw: *mut c_void,
58) {
59    let _ = catch_unwind(AssertUnwindSafe(|| {
60        let result = if trusted {
61            Ok(())
62        } else {
63            Err(trust_failure(error_raw))
64        };
65        unsafe {
66            Completion::<Result<()>>::complete(refcon, Ok(result));
67        };
68    }));
69}
70
71unsafe extern "C" fn authorization_copy_rights_async_cb(
72    refcon: *mut c_void,
73    value_raw: *mut c_void,
74    status_raw: i32,
75    error_raw: *mut c_void,
76) {
77    let _ = catch_unwind(AssertUnwindSafe(|| {
78        let result = if status_raw == status::SUCCESS {
79            match bridge::optional_value(value_raw) {
80                Ok(Some(value)) => Ok(value),
81                Ok(None) => Err(SecurityError::InvalidArgument(
82                    "security_authorization_copy_rights_async_start returned no authorization rights"
83                        .to_owned(),
84                )),
85                Err(error) => Err(error),
86            }
87        } else {
88            Err(bridge_status_error(
89                "security_authorization_copy_rights_async_start",
90                status_raw,
91                error_raw,
92            ))
93        };
94        unsafe {
95            Completion::<Result<Value>>::complete(refcon, Ok(result));
96        };
97    }));
98}
99
100/// Future returned by [`AsyncTrust::evaluate`].
101pub struct TrustEvaluateFuture<'a> {
102    inner: Completion<Result<()>>,
103    _owner: PhantomData<&'a Trust>,
104}
105
106impl core::fmt::Debug for TrustEvaluateFuture<'_> {
107    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
108        f.debug_struct("TrustEvaluateFuture")
109            .finish_non_exhaustive()
110    }
111}
112
113impl Future for TrustEvaluateFuture<'_> {
114    type Output = Result<()>;
115
116    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
117        Pin::new(&mut self.inner).poll(cx).map(flatten_async_result)
118    }
119}
120
121/// Future returned by [`AsyncAuthorization::copy_rights`].
122pub struct AuthorizationRightsFuture<'a> {
123    inner: Completion<Result<Value>>,
124    _owner: PhantomData<&'a Authorization>,
125}
126
127impl core::fmt::Debug for AuthorizationRightsFuture<'_> {
128    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
129        f.debug_struct("AuthorizationRightsFuture")
130            .finish_non_exhaustive()
131    }
132}
133
134impl Future for AuthorizationRightsFuture<'_> {
135    type Output = Result<Value>;
136
137    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
138        Pin::new(&mut self.inner).poll(cx).map(flatten_async_result)
139    }
140}
141
142/// Borrowed async wrapper for `SecTrustRef` evaluation.
143#[derive(Debug, Clone, Copy)]
144pub struct AsyncTrust<'a> {
145    trust: &'a Trust,
146}
147
148impl<'a> AsyncTrust<'a> {
149    /// Create a borrowed async wrapper around a trust object.
150    #[must_use]
151    pub const fn new(trust: &'a Trust) -> Self {
152        Self { trust }
153    }
154
155    /// Start `SecTrustEvaluateAsyncWithError` and await its callback.
156    pub fn evaluate(&self) -> Result<TrustEvaluateFuture<'a>> {
157        let (inner, refcon) = Completion::<Result<()>>::new();
158        let mut error_raw = ptr::null_mut();
159        let status = unsafe {
160            bridge::security_trust_evaluate_async_start(
161                self.trust.as_ptr(),
162                refcon,
163                Some(trust_evaluate_async_cb),
164                &raw mut error_raw,
165            )
166        };
167        if status != status::SUCCESS {
168            let error =
169                bridge_status_error("security_trust_evaluate_async_start", status, error_raw);
170            unsafe {
171                Completion::<Result<()>>::complete(refcon, Err(error.to_string()));
172            };
173            drop(inner);
174            return Err(error);
175        }
176
177        Ok(TrustEvaluateFuture {
178            inner,
179            _owner: PhantomData,
180        })
181    }
182}
183
184/// Borrowed async wrapper for `AuthorizationRef` rights requests.
185#[derive(Debug, Clone, Copy)]
186pub struct AsyncAuthorization<'a> {
187    authorization: &'a Authorization,
188}
189
190impl<'a> AsyncAuthorization<'a> {
191    /// Create a borrowed async wrapper around an authorization handle.
192    #[must_use]
193    pub const fn new(authorization: &'a Authorization) -> Self {
194        Self { authorization }
195    }
196
197    /// Start `AuthorizationCopyRightsAsync` and await the authorized-rights payload.
198    pub fn copy_rights(
199        &self,
200        rights: &[&str],
201        options: AuthorizationOptions,
202    ) -> Result<AuthorizationRightsFuture<'a>> {
203        let rights_value = rights_value(rights)?;
204        let (inner, refcon) = Completion::<Result<Value>>::new();
205        let mut error_raw = ptr::null_mut();
206        let status = unsafe {
207            bridge::security_authorization_copy_rights_async_start(
208                self.authorization.as_ptr(),
209                rights_value.as_ptr(),
210                options.bits(),
211                refcon,
212                Some(authorization_copy_rights_async_cb),
213                &raw mut error_raw,
214            )
215        };
216        if status != status::SUCCESS {
217            let error = bridge_status_error(
218                "security_authorization_copy_rights_async_start",
219                status,
220                error_raw,
221            );
222            unsafe {
223                Completion::<Result<Value>>::complete(refcon, Err(error.to_string()));
224            };
225            drop(inner);
226            return Err(error);
227        }
228
229        Ok(AuthorizationRightsFuture {
230            inner,
231            _owner: PhantomData,
232        })
233    }
234}