Skip to main content

security/trust/
mod.rs

1use std::time::{Duration, SystemTime, UNIX_EPOCH};
2
3use bitflags::bitflags;
4use serde_json::Value;
5
6use crate::bridge;
7use crate::certificate::{Certificate, PublicKey};
8use crate::error::{Result, SecurityError};
9pub use crate::policy::Policy;
10
11bitflags! {
12    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13    /// Mirrors `SecTrustOptionFlags`.
14    pub struct TrustOptions: u32 {
15        /// Mirrors a `SecTrustOptionFlags` bit.
16        const ALLOW_EXPIRED = 0x0000_0001;
17        /// Mirrors a `SecTrustOptionFlags` bit.
18        const LEAF_IS_CA = 0x0000_0002;
19        /// Mirrors a `SecTrustOptionFlags` bit.
20        const FETCH_ISSUER_FROM_NET = 0x0000_0004;
21        /// Mirrors a `SecTrustOptionFlags` bit.
22        const ALLOW_EXPIRED_ROOT = 0x0000_0008;
23        /// Mirrors a `SecTrustOptionFlags` bit.
24        const REQUIRE_REVOCATION_PER_CERT = 0x0000_0010;
25        /// Mirrors a `SecTrustOptionFlags` bit.
26        const USE_TRUST_SETTINGS = 0x0000_0020;
27        /// Mirrors a `SecTrustOptionFlags` bit.
28        const IMPLICIT_ANCHORS = 0x0000_0040;
29    }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33#[repr(u32)]
34/// Mirrors `SecTrustResultType`.
35pub enum TrustResultType {
36    /// Mirrors a `SecTrustResultType` constant.
37    Invalid = 0,
38    /// Mirrors a `SecTrustResultType` constant.
39    Proceed = 1,
40    /// Mirrors a `SecTrustResultType` constant.
41    Confirm = 2,
42    /// Mirrors a `SecTrustResultType` constant.
43    Deny = 3,
44    /// Mirrors a `SecTrustResultType` constant.
45    Unspecified = 4,
46    /// Mirrors a `SecTrustResultType` constant.
47    RecoverableTrustFailure = 5,
48    /// Mirrors a `SecTrustResultType` constant.
49    FatalTrustFailure = 6,
50    /// Mirrors a `SecTrustResultType` constant.
51    OtherError = 7,
52}
53
54impl TrustResultType {
55    fn from_raw(raw: u32) -> Result<Self> {
56        match raw {
57            0 => Ok(Self::Invalid),
58            1 => Ok(Self::Proceed),
59            2 => Ok(Self::Confirm),
60            3 => Ok(Self::Deny),
61            4 => Ok(Self::Unspecified),
62            5 => Ok(Self::RecoverableTrustFailure),
63            6 => Ok(Self::FatalTrustFailure),
64            7 => Ok(Self::OtherError),
65            _ => Err(SecurityError::InvalidArgument(format!(
66                "unexpected trust result type: {raw}"
67            ))),
68        }
69    }
70}
71
72#[derive(Debug)]
73/// Wraps `SecTrustRef`.
74pub struct Trust {
75    handle: bridge::Handle,
76}
77
78impl Trust {
79    #[cfg(feature = "async")]
80    pub(crate) fn as_ptr(&self) -> *mut std::ffi::c_void {
81        self.handle.as_ptr()
82    }
83
84    pub(crate) fn from_handle(handle: bridge::Handle) -> Self {
85        Self { handle }
86    }
87
88    /// Wraps the corresponding `SecTrustRef` operation.
89    pub fn type_id() -> usize {
90        unsafe { bridge::security_trust_get_type_id() }
91    }
92
93    /// Wraps the corresponding `SecTrustRef` operation.
94    pub fn new(certificate: &Certificate, policies: &[Policy]) -> Result<Self> {
95        Self::from_certificates(std::slice::from_ref(certificate), policies)
96    }
97
98    /// Wraps the corresponding `SecTrustRef` operation.
99    pub fn from_certificates(certificates: &[Certificate], policies: &[Policy]) -> Result<Self> {
100        let certificate_handles = certificates
101            .iter()
102            .map(Certificate::handle)
103            .collect::<Vec<_>>();
104        let policy_handles = policies.iter().map(Policy::handle).collect::<Vec<_>>();
105        let certificate_pointers = bridge::handle_pointer_array(&certificate_handles);
106        let policy_pointers = bridge::handle_pointer_array(&policy_handles);
107        let mut status = 0;
108        let mut error = std::ptr::null_mut();
109        let raw = unsafe {
110            bridge::security_trust_create(
111                certificate_pointers.as_ptr(),
112                bridge::len_to_isize(certificate_pointers.len())?,
113                policy_pointers.as_ptr(),
114                bridge::len_to_isize(policy_pointers.len())?,
115                &raw mut status,
116                &raw mut error,
117            )
118        };
119        bridge::required_handle("security_trust_create", raw, status, error)
120            .map(|handle| Self { handle })
121    }
122
123    /// Wraps the corresponding `SecTrustRef` operation.
124    pub fn set_policies(&mut self, policies: &[Policy]) -> Result<()> {
125        let policy_handles = policies.iter().map(Policy::handle).collect::<Vec<_>>();
126        let pointers = bridge::handle_pointer_array(&policy_handles);
127        let mut error = std::ptr::null_mut();
128        let status = unsafe {
129            bridge::security_trust_set_policies(
130                self.handle.as_ptr(),
131                pointers.as_ptr(),
132                bridge::len_to_isize(pointers.len())?,
133                &raw mut error,
134            )
135        };
136        bridge::status_result("security_trust_set_policies", status, error)
137    }
138
139    /// Wraps the corresponding `SecTrustRef` operation.
140    pub fn policies(&self) -> Result<Value> {
141        let mut status = 0;
142        let mut error = std::ptr::null_mut();
143        let raw = unsafe {
144            bridge::security_trust_copy_policies(
145                self.handle.as_ptr(),
146                &raw mut status,
147                &raw mut error,
148            )
149        };
150        bridge::required_json("security_trust_copy_policies", raw, status, error)
151    }
152
153    /// Wraps the corresponding `SecTrustRef` operation.
154    pub fn set_anchor_certificates(&mut self, certificates: &[Certificate]) -> Result<()> {
155        let certificate_handles = certificates
156            .iter()
157            .map(Certificate::handle)
158            .collect::<Vec<_>>();
159        let pointers = bridge::handle_pointer_array(&certificate_handles);
160        let mut error = std::ptr::null_mut();
161        let status = unsafe {
162            bridge::security_trust_set_anchor_certificates(
163                self.handle.as_ptr(),
164                pointers.as_ptr(),
165                bridge::len_to_isize(pointers.len())?,
166                &raw mut error,
167            )
168        };
169        bridge::status_result("security_trust_set_anchor_certificates", status, error)
170    }
171
172    /// Wraps the corresponding `SecTrustRef` operation.
173    pub fn custom_anchor_certificates(&self) -> Result<Value> {
174        let mut status = 0;
175        let mut error = std::ptr::null_mut();
176        let raw = unsafe {
177            bridge::security_trust_copy_custom_anchor_certificates(
178                self.handle.as_ptr(),
179                &raw mut status,
180                &raw mut error,
181            )
182        };
183        bridge::required_json(
184            "security_trust_copy_custom_anchor_certificates",
185            raw,
186            status,
187            error,
188        )
189    }
190
191    /// Wraps the corresponding `SecTrustRef` operation.
192    pub fn set_anchor_certificates_only(&mut self, only_anchor_certificates: bool) -> Result<()> {
193        let mut error = std::ptr::null_mut();
194        let status = unsafe {
195            bridge::security_trust_set_anchor_certificates_only(
196                self.handle.as_ptr(),
197                only_anchor_certificates,
198                &raw mut error,
199            )
200        };
201        bridge::status_result("security_trust_set_anchor_certificates_only", status, error)
202    }
203
204    /// Wraps the corresponding `SecTrustRef` operation.
205    pub fn set_network_fetch_allowed(&mut self, allowed: bool) -> Result<()> {
206        let mut error = std::ptr::null_mut();
207        let status = unsafe {
208            bridge::security_trust_set_network_fetch_allowed(
209                self.handle.as_ptr(),
210                allowed,
211                &raw mut error,
212            )
213        };
214        bridge::status_result("security_trust_set_network_fetch_allowed", status, error)
215    }
216
217    /// Wraps the corresponding `SecTrustRef` operation.
218    pub fn network_fetch_allowed(&self) -> Result<bool> {
219        let mut status = 0;
220        let mut error = std::ptr::null_mut();
221        let allowed = unsafe {
222            bridge::security_trust_get_network_fetch_allowed(
223                self.handle.as_ptr(),
224                &raw mut status,
225                &raw mut error,
226            )
227        };
228        if status != 0 {
229            return Err(bridge::status_error(
230                "security_trust_get_network_fetch_allowed",
231                status,
232                error,
233            )?);
234        }
235        Ok(allowed)
236    }
237
238    /// Wraps the corresponding `SecTrustRef` operation.
239    pub fn set_verify_date(&mut self, verify_date: SystemTime) -> Result<()> {
240        let mut error = std::ptr::null_mut();
241        let status = unsafe {
242            bridge::security_trust_set_verify_date(
243                self.handle.as_ptr(),
244                system_time_to_unix(verify_date),
245                &raw mut error,
246            )
247        };
248        bridge::status_result("security_trust_set_verify_date", status, error)
249    }
250
251    /// Wraps the corresponding `SecTrustRef` operation.
252    pub fn verify_time(&self) -> Result<Option<SystemTime>> {
253        let mut status = 0;
254        let mut error = std::ptr::null_mut();
255        let raw = unsafe {
256            bridge::security_trust_get_verify_time(
257                self.handle.as_ptr(),
258                &raw mut status,
259                &raw mut error,
260            )
261        };
262        if status != 0 {
263            return Err(bridge::status_error(
264                "security_trust_get_verify_time",
265                status,
266                error,
267            )?);
268        }
269        bridge::optional_json::<Value>(raw)?
270            .map_or(Ok(None), |value| decode_trust_date(value).map(Some))
271    }
272
273    /// Wraps the corresponding `SecTrustRef` operation.
274    pub fn evaluate(&self) -> Result<()> {
275        let mut error = std::ptr::null_mut();
276        let trusted =
277            unsafe { bridge::security_trust_evaluate(self.handle.as_ptr(), &raw mut error) };
278        if trusted {
279            Ok(())
280        } else {
281            let message = bridge::optional_string(error)?
282                .unwrap_or_else(|| "trust evaluation failed".to_owned());
283            Err(SecurityError::TrustEvaluationFailed(message))
284        }
285    }
286
287    /// Wraps the corresponding `SecTrustRef` operation.
288    pub fn evaluate_async(&self) -> Result<()> {
289        let mut status = 0;
290        let mut error = std::ptr::null_mut();
291        let trusted = unsafe {
292            bridge::security_trust_evaluate_async(
293                self.handle.as_ptr(),
294                &raw mut status,
295                &raw mut error,
296            )
297        };
298        if status != 0 {
299            return Err(bridge::status_error(
300                "security_trust_evaluate_async",
301                status,
302                error,
303            )?);
304        }
305        if trusted {
306            Ok(())
307        } else {
308            let message = bridge::optional_string(error)?
309                .unwrap_or_else(|| "trust evaluation failed".to_owned());
310            Err(SecurityError::TrustEvaluationFailed(message))
311        }
312    }
313
314    /// Wraps the corresponding `SecTrustRef` operation.
315    pub fn trust_result_type(&self) -> Result<TrustResultType> {
316        let mut status = 0;
317        let mut error = std::ptr::null_mut();
318        let raw = unsafe {
319            bridge::security_trust_get_trust_result(
320                self.handle.as_ptr(),
321                &raw mut status,
322                &raw mut error,
323            )
324        };
325        if status != 0 {
326            return Err(bridge::status_error(
327                "security_trust_get_trust_result",
328                status,
329                error,
330            )?);
331        }
332        TrustResultType::from_raw(raw)
333    }
334
335    /// Wraps the corresponding `SecTrustRef` operation.
336    pub fn result(&self) -> Result<Value> {
337        let mut status = 0;
338        let mut error = std::ptr::null_mut();
339        let raw = unsafe {
340            bridge::security_trust_copy_result(
341                self.handle.as_ptr(),
342                &raw mut status,
343                &raw mut error,
344            )
345        };
346        bridge::required_json("security_trust_copy_result", raw, status, error)
347    }
348
349    /// Wraps the corresponding `SecTrustRef` operation.
350    pub fn key(&self) -> Result<Option<PublicKey>> {
351        let mut status = 0;
352        let mut error = std::ptr::null_mut();
353        let raw = unsafe {
354            bridge::security_trust_copy_key(self.handle.as_ptr(), &raw mut status, &raw mut error)
355        };
356        if status != 0 {
357            return Err(bridge::status_error(
358                "security_trust_copy_key",
359                status,
360                error,
361            )?);
362        }
363        Ok(bridge::Handle::from_raw(raw).map(PublicKey::from_handle))
364    }
365
366    /// Wraps the corresponding `SecTrustRef` operation.
367    pub fn certificate_count(&self) -> usize {
368        usize::try_from(unsafe {
369            bridge::security_trust_get_certificate_count(self.handle.as_ptr())
370        })
371        .unwrap_or_default()
372    }
373
374    /// Wraps the corresponding `SecTrustRef` operation.
375    pub fn certificate_chain(&self) -> Result<Vec<Certificate>> {
376        let mut status = 0;
377        let mut error = std::ptr::null_mut();
378        let raw = unsafe {
379            bridge::security_trust_copy_certificate_chain(
380                self.handle.as_ptr(),
381                &raw mut status,
382                &raw mut error,
383            )
384        };
385        let array_handle =
386            bridge::required_handle("security_trust_copy_certificate_chain", raw, status, error)?;
387        Certificate::from_array_handle(&array_handle)
388    }
389
390    /// Wraps the corresponding `SecTrustRef` operation.
391    pub fn exceptions(&self) -> Result<Option<Vec<u8>>> {
392        let mut status = 0;
393        let mut error = std::ptr::null_mut();
394        let raw = unsafe {
395            bridge::security_trust_copy_exceptions(
396                self.handle.as_ptr(),
397                &raw mut status,
398                &raw mut error,
399            )
400        };
401        if status != 0 {
402            return Err(bridge::status_error(
403                "security_trust_copy_exceptions",
404                status,
405                error,
406            )?);
407        }
408        bridge::optional_data(raw)
409    }
410
411    /// Wraps the corresponding `SecTrustRef` operation.
412    pub fn set_exceptions(&mut self, exceptions: Option<&[u8]>) -> Result<bool> {
413        let mut error = std::ptr::null_mut();
414        let accepted = unsafe {
415            bridge::security_trust_set_exceptions(
416                self.handle.as_ptr(),
417                exceptions.map_or(std::ptr::null(), |value| value.as_ptr().cast()),
418                exceptions.map_or(Ok(0), |value| bridge::len_to_isize(value.len()))?,
419                &raw mut error,
420            )
421        };
422        if !error.is_null() {
423            return Err(bridge::status_error(
424                "security_trust_set_exceptions",
425                -1,
426                error,
427            )?);
428        }
429        Ok(accepted)
430    }
431
432    /// Wraps the corresponding `SecTrustRef` operation.
433    pub fn set_ocsp_responses(&mut self, responses: &[Vec<u8>]) -> Result<()> {
434        let responses = bridge::json_cstring(&responses)?;
435        let mut error = std::ptr::null_mut();
436        let status = unsafe {
437            bridge::security_trust_set_ocsp_response(
438                self.handle.as_ptr(),
439                responses.as_ptr(),
440                &raw mut error,
441            )
442        };
443        bridge::status_result("security_trust_set_ocsp_response", status, error)
444    }
445
446    /// Wraps the corresponding `SecTrustRef` operation.
447    pub fn set_signed_certificate_timestamps(&mut self, timestamps: &[Vec<u8>]) -> Result<()> {
448        let timestamps = bridge::json_cstring(&timestamps)?;
449        let mut error = std::ptr::null_mut();
450        let status = unsafe {
451            bridge::security_trust_set_signed_certificate_timestamps(
452                self.handle.as_ptr(),
453                timestamps.as_ptr(),
454                &raw mut error,
455            )
456        };
457        bridge::status_result(
458            "security_trust_set_signed_certificate_timestamps",
459            status,
460            error,
461        )
462    }
463
464    /// Wraps the corresponding `SecTrustRef` operation.
465    pub fn set_options(&mut self, options: TrustOptions) -> Result<()> {
466        let mut error = std::ptr::null_mut();
467        let status = unsafe {
468            bridge::security_trust_set_options(self.handle.as_ptr(), options.bits(), &raw mut error)
469        };
470        bridge::status_result("security_trust_set_options", status, error)
471    }
472
473    /// Wraps the corresponding `SecTrustRef` operation.
474    pub fn system_anchor_certificates() -> Result<Value> {
475        let mut status = 0;
476        let mut error = std::ptr::null_mut();
477        let raw = unsafe {
478            bridge::security_trust_copy_anchor_certificates(&raw mut status, &raw mut error)
479        };
480        bridge::required_json(
481            "security_trust_copy_anchor_certificates",
482            raw,
483            status,
484            error,
485        )
486    }
487}
488
489fn decode_trust_date(value: Value) -> Result<SystemTime> {
490    let unix =
491        value
492            .get("unix")
493            .and_then(Value::as_f64)
494            .ok_or_else(|| SecurityError::UnexpectedType {
495                operation: "security_trust_get_verify_time",
496                expected: "date JSON object",
497            })?;
498    let out_of_range =
499        || SecurityError::InvalidArgument("trust verify time is out of range".to_owned());
500    let duration = Duration::try_from_secs_f64(unix.abs()).map_err(|_| out_of_range())?;
501    if unix >= 0.0 {
502        UNIX_EPOCH.checked_add(duration).ok_or_else(out_of_range)
503    } else {
504        UNIX_EPOCH.checked_sub(duration).ok_or_else(out_of_range)
505    }
506}
507
508fn system_time_to_unix(time: SystemTime) -> f64 {
509    match time.duration_since(UNIX_EPOCH) {
510        Ok(duration) => duration.as_secs_f64(),
511        Err(error) => -error.duration().as_secs_f64(),
512    }
513}
514
515#[cfg(test)]
516mod tests {
517    use serde_json::json;
518
519    use super::*;
520
521    #[test]
522    fn trust_result_type_from_raw_maps_known_values() {
523        assert_eq!(
524            TrustResultType::from_raw(0).unwrap(),
525            TrustResultType::Invalid
526        );
527        assert_eq!(
528            TrustResultType::from_raw(7).unwrap(),
529            TrustResultType::OtherError
530        );
531    }
532
533    #[test]
534    fn trust_result_type_from_raw_rejects_unknown_values() {
535        assert_eq!(
536            TrustResultType::from_raw(99).unwrap_err(),
537            SecurityError::InvalidArgument("unexpected trust result type: 99".to_owned())
538        );
539    }
540
541    #[test]
542    fn system_time_to_unix_preserves_times_after_epoch() {
543        let time = UNIX_EPOCH + Duration::from_secs_f64(42.5);
544
545        assert!((system_time_to_unix(time) - 42.5).abs() < f64::EPSILON);
546    }
547
548    #[test]
549    fn system_time_to_unix_preserves_times_before_epoch() {
550        let time = UNIX_EPOCH - Duration::from_secs_f64(12.5);
551
552        assert!((system_time_to_unix(time) + 12.5).abs() < f64::EPSILON);
553    }
554
555    #[test]
556    fn decode_trust_date_parses_positive_unix_seconds() {
557        let time = decode_trust_date(json!({ "unix": 42.5 })).unwrap();
558
559        assert_eq!(time, UNIX_EPOCH + Duration::from_secs_f64(42.5));
560    }
561
562    #[test]
563    fn decode_trust_date_parses_negative_unix_seconds() {
564        let time = decode_trust_date(json!({ "unix": -12.5 })).unwrap();
565
566        assert_eq!(time, UNIX_EPOCH - Duration::from_secs_f64(12.5));
567    }
568
569    #[test]
570    fn decode_trust_date_requires_unix_field() {
571        assert!(matches!(
572            decode_trust_date(json!({ "seconds": 1 })).unwrap_err(),
573            SecurityError::UnexpectedType {
574                operation: "security_trust_get_verify_time",
575                expected: "date JSON object",
576            }
577        ));
578    }
579}