Skip to main content

localauthentication/
la_persisted_right.rs

1//! `LAPersistedRight`, `LAPrivateKey`, and `LASecret` wrappers.
2
3use zeroize::Zeroizing;
4
5use crate::ffi;
6use crate::la_error::{LAError, Result};
7use crate::la_public_key::{LAPublicKey, SecKeyAlgorithm, SecKeyExchangeParameters};
8use crate::la_right::LARightState;
9use crate::private::{
10    bridge_bool, bridge_bytes, bridge_i32, bridge_i64, bridge_ptr, bridge_secret_bytes,
11    bridge_unit, cstring, OwnedHandle,
12};
13
14/// Managed wrapper around Apple's `LAPersistedRight`.
15#[derive(Debug)]
16pub struct LAPersistedRight {
17    handle: OwnedHandle,
18}
19
20impl LAPersistedRight {
21    pub(crate) fn from_raw(raw: std::ptr::NonNull<core::ffi::c_void>) -> Self {
22        Self {
23            handle: OwnedHandle::new(raw, ffi::la_persisted_right::la_persisted_right_release),
24        }
25    }
26
27    pub(crate) const fn as_ptr(&self) -> *mut core::ffi::c_void {
28        self.handle.as_ptr()
29    }
30
31    /// The current authorization state.
32    ///
33    /// # Errors
34    ///
35    /// Returns an error if the Swift bridge rejects the request.
36    pub fn state(&self) -> Result<LARightState> {
37        let raw = bridge_i32(|out, error_out| unsafe {
38            ffi::la_persisted_right::la_persisted_right_get_state(
39                self.handle.as_ptr(),
40                out,
41                error_out,
42            )
43        })?;
44        Ok(LARightState::from_ffi(raw))
45    }
46
47    /// Application-controlled integer tag.
48    ///
49    /// # Errors
50    ///
51    /// Returns an error if the Swift bridge rejects the request.
52    pub fn tag(&self) -> Result<i64> {
53        bridge_i64(|out, error_out| unsafe {
54            ffi::la_persisted_right::la_persisted_right_get_tag(
55                self.handle.as_ptr(),
56                out,
57                error_out,
58            )
59        })
60    }
61
62    /// Update the application-controlled integer tag.
63    ///
64    /// # Errors
65    ///
66    /// Returns an error if the Swift bridge rejects the request.
67    pub fn set_tag(&self, tag: i64) -> Result<()> {
68        bridge_unit(|error_out| unsafe {
69            ffi::la_persisted_right::la_persisted_right_set_tag(
70                self.handle.as_ptr(),
71                tag,
72                error_out,
73            )
74        })
75    }
76
77    /// Attempt to authorize the persisted right.
78    ///
79    /// # Errors
80    ///
81    /// Returns a mapped framework or bridge error when authorization fails.
82    pub fn authorize(&self, localized_reason: &str) -> Result<()> {
83        if localized_reason.is_empty() {
84            return Err(LAError::InvalidArgument(
85                "localized reason must not be empty".to_owned(),
86            ));
87        }
88        let localized_reason = cstring(localized_reason)?;
89        bridge_unit(|error_out| unsafe {
90            ffi::la_persisted_right::la_persisted_right_authorize(
91                self.handle.as_ptr(),
92                localized_reason.as_ptr(),
93                error_out,
94            )
95        })
96    }
97
98    /// Preflight whether the persisted right can eventually be authorized.
99    ///
100    /// # Errors
101    ///
102    /// Returns a mapped framework or bridge error when authorization is not possible.
103    pub fn check_can_authorize(&self) -> Result<()> {
104        bridge_unit(|error_out| unsafe {
105            ffi::la_persisted_right::la_persisted_right_check_can_authorize(
106                self.handle.as_ptr(),
107                error_out,
108            )
109        })
110    }
111
112    /// Deauthorize the persisted right.
113    ///
114    /// # Errors
115    ///
116    /// Returns an error if the Swift bridge rejects the request.
117    pub fn deauthorize(&self) -> Result<()> {
118        bridge_unit(|error_out| unsafe {
119            ffi::la_persisted_right::la_persisted_right_deauthorize(self.handle.as_ptr(), error_out)
120        })
121    }
122
123    /// Borrow the managed private key associated with this persisted right.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error if the Swift bridge rejects the request.
128    pub fn key(&self) -> Result<LAPrivateKey> {
129        Ok(LAPrivateKey::from_raw(bridge_ptr(
130            |out, error_out| unsafe {
131                ffi::la_persisted_right::la_persisted_right_get_key(
132                    self.handle.as_ptr(),
133                    out,
134                    error_out,
135                )
136            },
137        )?))
138    }
139
140    /// Borrow the generic secret associated with this persisted right.
141    ///
142    /// # Errors
143    ///
144    /// Returns an error if the Swift bridge rejects the request.
145    pub fn secret(&self) -> Result<LASecret> {
146        Ok(LASecret::from_raw(bridge_ptr(|out, error_out| unsafe {
147            ffi::la_persisted_right::la_persisted_right_get_secret(
148                self.handle.as_ptr(),
149                out,
150                error_out,
151            )
152        })?))
153    }
154
155    /// Convenience helper returning `self.key()?.public_key()`.
156    ///
157    /// # Errors
158    ///
159    /// Returns an error if the Swift bridge rejects the request.
160    pub fn public_key(&self) -> Result<LAPublicKey> {
161        self.key()?.public_key()
162    }
163}
164
165/// Managed wrapper around Apple's `LASecret`.
166#[derive(Debug)]
167pub struct LASecret {
168    handle: OwnedHandle,
169}
170
171impl LASecret {
172    pub(crate) fn from_raw(raw: std::ptr::NonNull<core::ffi::c_void>) -> Self {
173        Self {
174            handle: OwnedHandle::new(raw, ffi::la_persisted_right::la_secret_release),
175        }
176    }
177
178    /// Load the secret bytes.
179    ///
180    /// # Errors
181    ///
182    /// Returns a mapped framework or bridge error if loading fails.
183    pub fn load_data(&self) -> Result<Zeroizing<Vec<u8>>> {
184        bridge_secret_bytes(|out, out_len, error_out| unsafe {
185            ffi::la_persisted_right::la_secret_load_data(
186                self.handle.as_ptr(),
187                out,
188                out_len,
189                error_out,
190            )
191        })
192    }
193}
194
195/// Managed wrapper around Apple's `LAPrivateKey`.
196#[derive(Debug)]
197pub struct LAPrivateKey {
198    handle: OwnedHandle,
199}
200
201impl LAPrivateKey {
202    pub(crate) fn from_raw(raw: std::ptr::NonNull<core::ffi::c_void>) -> Self {
203        Self {
204            handle: OwnedHandle::new(raw, ffi::la_persisted_right::la_private_key_release),
205        }
206    }
207
208    /// Borrow the public-key counterpart of this private key.
209    ///
210    /// # Errors
211    ///
212    /// Returns an error if the Swift bridge rejects the request.
213    pub fn public_key(&self) -> Result<LAPublicKey> {
214        Ok(LAPublicKey::from_raw(bridge_ptr(
215            |out, error_out| unsafe {
216                ffi::la_persisted_right::la_private_key_get_public_key(
217                    self.handle.as_ptr(),
218                    out,
219                    error_out,
220                )
221            },
222        )?))
223    }
224
225    /// Check whether an algorithm can sign with this key.
226    ///
227    /// # Errors
228    ///
229    /// Returns an error if the Swift bridge rejects the request.
230    pub fn can_sign_using(&self, algorithm: &SecKeyAlgorithm) -> Result<bool> {
231        let algorithm = cstring(algorithm.raw_name())?;
232        bridge_bool(|out, error_out| unsafe {
233            ffi::la_persisted_right::la_private_key_can_sign_using_algorithm(
234                self.handle.as_ptr(),
235                algorithm.as_ptr(),
236                out,
237                error_out,
238            )
239        })
240    }
241
242    /// Sign data with this key.
243    ///
244    /// # Errors
245    ///
246    /// Returns a mapped framework or bridge error if signing fails.
247    pub fn sign(&self, data: &[u8], algorithm: &SecKeyAlgorithm) -> Result<Vec<u8>> {
248        let algorithm = cstring(algorithm.raw_name())?;
249        bridge_bytes(|out, out_len, error_out| unsafe {
250            ffi::la_persisted_right::la_private_key_sign_data(
251                self.handle.as_ptr(),
252                data.as_ptr(),
253                data.len(),
254                algorithm.as_ptr(),
255                out,
256                out_len,
257                error_out,
258            )
259        })
260    }
261
262    /// Check whether an algorithm can decrypt with this key.
263    ///
264    /// # Errors
265    ///
266    /// Returns an error if the Swift bridge rejects the request.
267    pub fn can_decrypt_using(&self, algorithm: &SecKeyAlgorithm) -> Result<bool> {
268        let algorithm = cstring(algorithm.raw_name())?;
269        bridge_bool(|out, error_out| unsafe {
270            ffi::la_persisted_right::la_private_key_can_decrypt_using_algorithm(
271                self.handle.as_ptr(),
272                algorithm.as_ptr(),
273                out,
274                error_out,
275            )
276        })
277    }
278
279    /// Decrypt data with this key.
280    ///
281    /// # Errors
282    ///
283    /// Returns a mapped framework or bridge error if decryption fails.
284    pub fn decrypt(&self, data: &[u8], algorithm: &SecKeyAlgorithm) -> Result<Zeroizing<Vec<u8>>> {
285        let algorithm = cstring(algorithm.raw_name())?;
286        bridge_secret_bytes(|out, out_len, error_out| unsafe {
287            ffi::la_persisted_right::la_private_key_decrypt_data(
288                self.handle.as_ptr(),
289                data.as_ptr(),
290                data.len(),
291                algorithm.as_ptr(),
292                out,
293                out_len,
294                error_out,
295            )
296        })
297    }
298
299    /// Check whether an algorithm can be used for key exchange.
300    ///
301    /// # Errors
302    ///
303    /// Returns an error if the Swift bridge rejects the request.
304    pub fn can_exchange_keys_using(&self, algorithm: &SecKeyAlgorithm) -> Result<bool> {
305        let algorithm = cstring(algorithm.raw_name())?;
306        bridge_bool(|out, error_out| unsafe {
307            ffi::la_persisted_right::la_private_key_can_exchange_keys_using_algorithm(
308                self.handle.as_ptr(),
309                algorithm.as_ptr(),
310                out,
311                error_out,
312            )
313        })
314    }
315
316    /// Perform a Diffie-Hellman-style key exchange with a remote public key.
317    ///
318    /// # Errors
319    ///
320    /// Returns a mapped framework or bridge error if key exchange fails.
321    pub fn exchange_keys_with_public_key(
322        &self,
323        public_key: &[u8],
324        algorithm: &SecKeyAlgorithm,
325        parameters: &SecKeyExchangeParameters,
326    ) -> Result<Zeroizing<Vec<u8>>> {
327        let algorithm = cstring(algorithm.raw_name())?;
328        let requested_size = parameters
329            .requested_size_value()
330            .map(i64::try_from)
331            .transpose()
332            .map_err(|_| {
333                LAError::InvalidArgument(
334                    "requested key-exchange size must fit in a signed 64-bit integer".to_owned(),
335                )
336            })?
337            .unwrap_or(-1);
338        let shared_info = parameters.shared_info_value();
339        let shared_info_ptr = shared_info.map_or(std::ptr::null(), <[u8]>::as_ptr);
340        let shared_info_len = shared_info.map_or(0, <[u8]>::len);
341        let has_shared_info = u8::from(shared_info.is_some());
342
343        bridge_secret_bytes(|out, out_len, error_out| unsafe {
344            ffi::la_persisted_right::la_private_key_exchange_keys_with_public_key(
345                self.handle.as_ptr(),
346                public_key.as_ptr(),
347                public_key.len(),
348                algorithm.as_ptr(),
349                requested_size,
350                shared_info_ptr,
351                shared_info_len,
352                has_shared_info,
353                out,
354                out_len,
355                error_out,
356            )
357        })
358    }
359}