Skip to main content

security/
cms.rs

1use std::time::{Duration, SystemTime, UNIX_EPOCH};
2
3use crate::Value;
4
5use crate::bridge;
6use crate::certificate::Certificate;
7use crate::error::{OsStatus, Result, SecurityError};
8use crate::identity::Identity;
9use crate::policy::Policy;
10use crate::trust::Trust;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(transparent)]
14#[must_use]
15/// Mirrors signed-attribute bits used by the CMS encoder APIs.
16pub struct CmsSignedAttributes(u32);
17
18impl CmsSignedAttributes {
19    /// Mirrors a CMS signed-attribute bit.
20    pub const NONE: Self = Self(0);
21    /// Mirrors a CMS signed-attribute bit.
22    pub const SMIME_CAPABILITIES: Self = Self(0x0001);
23    /// Mirrors a CMS signed-attribute bit.
24    pub const SMIME_ENCRYPTION_KEY_PREFS: Self = Self(0x0002);
25    /// Mirrors a CMS signed-attribute bit.
26    pub const SMIME_MS_ENCRYPTION_KEY_PREFS: Self = Self(0x0004);
27    /// Mirrors a CMS signed-attribute bit.
28    pub const SIGNING_TIME: Self = Self(0x0008);
29    /// Mirrors a CMS signed-attribute bit.
30    pub const APPLE_CODESIGNING_HASH_AGILITY: Self = Self(0x0010);
31    /// Mirrors a CMS signed-attribute bit.
32    pub const APPLE_CODESIGNING_HASH_AGILITY_V2: Self = Self(0x0020);
33    /// Mirrors a CMS signed-attribute bit.
34    pub const APPLE_EXPIRATION_TIME: Self = Self(0x0040);
35
36    pub const fn empty() -> Self {
37        Self(0)
38    }
39    pub const fn all() -> Self {
40        Self(0x7f)
41    }
42    pub const fn bits(self) -> u32 {
43        self.0
44    }
45    pub const fn from_bits(bits: u32) -> Option<Self> {
46        if bits & !Self::all().0 == 0 {
47            Some(Self(bits))
48        } else {
49            None
50        }
51    }
52    pub const fn from_bits_retain(bits: u32) -> Self {
53        Self(bits)
54    }
55    pub const fn from_bits_truncate(bits: u32) -> Self {
56        Self(bits & Self::all().0)
57    }
58    pub const fn is_empty(self) -> bool {
59        self.0 == 0
60    }
61    pub const fn is_all(self) -> bool {
62        self.0 & Self::all().0 == Self::all().0
63    }
64    pub const fn contains(self, other: Self) -> bool {
65        self.0 & other.0 == other.0
66    }
67    pub const fn intersects(self, other: Self) -> bool {
68        self.0 & other.0 != 0
69    }
70    pub const fn union(self, other: Self) -> Self {
71        Self(self.0 | other.0)
72    }
73    pub const fn intersection(self, other: Self) -> Self {
74        Self(self.0 & other.0)
75    }
76    pub const fn difference(self, other: Self) -> Self {
77        Self(self.0 & !other.0)
78    }
79    pub const fn symmetric_difference(self, other: Self) -> Self {
80        Self(self.0 ^ other.0)
81    }
82    pub const fn complement(self) -> Self {
83        Self(!self.0 & Self::all().0)
84    }
85    pub fn insert(&mut self, other: Self) {
86        self.0 |= other.0;
87    }
88    pub fn remove(&mut self, other: Self) {
89        self.0 &= !other.0;
90    }
91    pub fn toggle(&mut self, other: Self) {
92        self.0 ^= other.0;
93    }
94    pub fn set(&mut self, other: Self, value: bool) {
95        if value {
96            self.0 |= other.0;
97        } else {
98            self.0 &= !other.0;
99        }
100    }
101}
102
103impl std::ops::BitOr for CmsSignedAttributes {
104    type Output = Self;
105    fn bitor(self, rhs: Self) -> Self {
106        Self(self.0 | rhs.0)
107    }
108}
109impl std::ops::BitAnd for CmsSignedAttributes {
110    type Output = Self;
111    fn bitand(self, rhs: Self) -> Self {
112        Self(self.0 & rhs.0)
113    }
114}
115impl std::ops::BitXor for CmsSignedAttributes {
116    type Output = Self;
117    fn bitxor(self, rhs: Self) -> Self {
118        Self(self.0 ^ rhs.0)
119    }
120}
121impl std::ops::Sub for CmsSignedAttributes {
122    type Output = Self;
123    fn sub(self, rhs: Self) -> Self {
124        Self(self.0 & !rhs.0)
125    }
126}
127impl std::ops::Not for CmsSignedAttributes {
128    type Output = Self;
129    fn not(self) -> Self {
130        Self(!self.0 & Self::all().0)
131    }
132}
133impl std::ops::BitOrAssign for CmsSignedAttributes {
134    fn bitor_assign(&mut self, rhs: Self) {
135        self.0 |= rhs.0;
136    }
137}
138impl std::ops::BitAndAssign for CmsSignedAttributes {
139    fn bitand_assign(&mut self, rhs: Self) {
140        self.0 &= rhs.0;
141    }
142}
143impl std::ops::BitXorAssign for CmsSignedAttributes {
144    fn bitxor_assign(&mut self, rhs: Self) {
145        self.0 ^= rhs.0;
146    }
147}
148impl std::ops::SubAssign for CmsSignedAttributes {
149    fn sub_assign(&mut self, rhs: Self) {
150        self.0 &= !rhs.0;
151    }
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
155#[repr(u32)]
156/// Mirrors certificate-chain modes used by `CMSEncoder`.
157pub enum CmsCertificateChainMode {
158    /// Mirrors a CMS certificate-chain mode constant.
159    None = 0,
160    /// Mirrors a CMS certificate-chain mode constant.
161    SignerOnly = 1,
162    /// Mirrors a CMS certificate-chain mode constant.
163    Chain = 2,
164    /// Mirrors a CMS certificate-chain mode constant.
165    ChainWithRoot = 3,
166    /// Mirrors a CMS certificate-chain mode constant.
167    ChainWithRootOrFail = 4,
168}
169
170impl CmsCertificateChainMode {
171    fn from_raw(raw: u32) -> Result<Self> {
172        match raw {
173            0 => Ok(Self::None),
174            1 => Ok(Self::SignerOnly),
175            2 => Ok(Self::Chain),
176            3 => Ok(Self::ChainWithRoot),
177            4 => Ok(Self::ChainWithRootOrFail),
178            _ => Err(SecurityError::InvalidArgument(format!(
179                "unexpected CMS certificate chain mode: {raw}"
180            ))),
181        }
182    }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
186/// Mirrors digest selectors used by `CMSEncoderSetSignerAlgorithm`.
187pub enum CmsDigestAlgorithm {
188    /// Mirrors a CMS digest selector.
189    Sha1,
190    /// Mirrors a CMS digest selector.
191    Sha256,
192}
193
194impl CmsDigestAlgorithm {
195    const fn as_bridge_name(self) -> &'static str {
196        match self {
197            Self::Sha1 => "sha1",
198            Self::Sha256 => "sha256",
199        }
200    }
201}
202
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
204pub enum CmsSignerStatus {
205    Unsigned,
206    Valid,
207    NeedsDetachedContent,
208    InvalidSignature,
209    InvalidCertificate,
210    InvalidIndex,
211    Unknown(u32),
212}
213
214impl CmsSignerStatus {
215    const fn from_raw(raw: u32) -> Self {
216        match raw {
217            0 => Self::Unsigned,
218            1 => Self::Valid,
219            2 => Self::NeedsDetachedContent,
220            3 => Self::InvalidSignature,
221            4 => Self::InvalidCertificate,
222            5 => Self::InvalidIndex,
223            other => Self::Unknown(other),
224        }
225    }
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229pub enum CmsCertificateVerification {
230    NotEvaluated,
231    Evaluated(OsStatus),
232}
233
234#[derive(Debug)]
235#[non_exhaustive]
236pub struct CmsSignerStatusReport {
237    pub signer_status: CmsSignerStatus,
238    pub certificate_verification: CmsCertificateVerification,
239    pub trust: Option<Trust>,
240}
241
242impl CmsSignerStatusReport {
243    pub fn is_verified(&self) -> bool {
244        self.signer_status == CmsSignerStatus::Valid
245            && self.certificate_verification == CmsCertificateVerification::Evaluated(0)
246    }
247
248    fn from_value(value: &Value, trust: Option<Trust>) -> Result<Self> {
249        let unexpected = || SecurityError::UnexpectedType {
250            operation: "security_cms_decoder_copy_signer_status",
251            expected: "signer status dictionary",
252        };
253        let signer_status = value
254            .get("signerStatus")
255            .and_then(Value::as_u64)
256            .and_then(|raw| u32::try_from(raw).ok())
257            .map(CmsSignerStatus::from_raw)
258            .ok_or_else(unexpected)?;
259        let evaluated = value
260            .get("trustEvaluated")
261            .and_then(Value::as_bool)
262            .ok_or_else(unexpected)?;
263        let certificate_verification = if evaluated {
264            value
265                .get("certVerifyResultCode")
266                .and_then(Value::as_i64)
267                .and_then(|raw| OsStatus::try_from(raw).ok())
268                .map(CmsCertificateVerification::Evaluated)
269                .ok_or_else(unexpected)?
270        } else {
271            CmsCertificateVerification::NotEvaluated
272        };
273        Ok(Self {
274            signer_status,
275            certificate_verification,
276            trust,
277        })
278    }
279}
280
281#[derive(Debug)]
282/// Wraps Security.framework CMS decoder state.
283pub struct CmsDecoder {
284    handle: bridge::Handle,
285}
286
287impl CmsDecoder {
288    fn from_handle(handle: bridge::Handle) -> Self {
289        Self { handle }
290    }
291
292    /// Wraps the corresponding Security.framework CMS decoder operation.
293    pub fn type_id() -> usize {
294        unsafe { bridge::security_cms_decoder_get_type_id() }
295    }
296
297    /// Wraps the corresponding Security.framework CMS decoder operation.
298    pub fn update_message(&mut self, data: &[u8]) -> Result<()> {
299        let mut error = std::ptr::null_mut();
300        let status = unsafe {
301            bridge::security_cms_decoder_update_message(
302                self.handle.as_ptr(),
303                data.as_ptr().cast(),
304                bridge::len_to_isize(data.len())?,
305                &raw mut error,
306            )
307        };
308        bridge::status_result("security_cms_decoder_update_message", status, error)
309    }
310
311    /// Wraps the corresponding Security.framework CMS decoder operation.
312    pub fn finalize_message(&mut self) -> Result<()> {
313        let mut error = std::ptr::null_mut();
314        let status = unsafe {
315            bridge::security_cms_decoder_finalize_message(self.handle.as_ptr(), &raw mut error)
316        };
317        bridge::status_result("security_cms_decoder_finalize_message", status, error)
318    }
319
320    /// Wraps the corresponding Security.framework CMS decoder operation.
321    pub fn set_detached_content(&mut self, data: &[u8]) -> Result<()> {
322        let mut error = std::ptr::null_mut();
323        let status = unsafe {
324            bridge::security_cms_decoder_set_detached_content(
325                self.handle.as_ptr(),
326                data.as_ptr().cast(),
327                bridge::len_to_isize(data.len())?,
328                &raw mut error,
329            )
330        };
331        bridge::status_result("security_cms_decoder_set_detached_content", status, error)
332    }
333
334    /// Wraps the corresponding Security.framework CMS decoder operation.
335    pub fn detached_content(&self) -> Result<Option<Vec<u8>>> {
336        let mut status = 0;
337        let mut error = std::ptr::null_mut();
338        let raw = unsafe {
339            bridge::security_cms_decoder_copy_detached_content(
340                self.handle.as_ptr(),
341                &raw mut status,
342                &raw mut error,
343            )
344        };
345        if status != 0 {
346            return Err(bridge::status_error(
347                "security_cms_decoder_copy_detached_content",
348                status,
349                error,
350            )?);
351        }
352        bridge::optional_data(raw)
353    }
354
355    /// Wraps the corresponding Security.framework CMS decoder operation.
356    pub fn num_signers(&self) -> Result<usize> {
357        let mut status = 0;
358        let mut error = std::ptr::null_mut();
359        let count = unsafe {
360            bridge::security_cms_decoder_get_num_signers(
361                self.handle.as_ptr(),
362                &raw mut status,
363                &raw mut error,
364            )
365        };
366        if status != 0 {
367            return Err(bridge::status_error(
368                "security_cms_decoder_get_num_signers",
369                status,
370                error,
371            )?);
372        }
373        usize::try_from(count).map_err(|_| {
374            SecurityError::Serialization("negative signer count from bridge".to_owned())
375        })
376    }
377
378    /// Wraps the corresponding Security.framework CMS decoder operation.
379    pub fn signer_status(
380        &self,
381        signer_index: usize,
382        policy: Option<&Policy>,
383        evaluate_sec_trust: bool,
384    ) -> Result<CmsSignerStatusReport> {
385        let mut status = 0;
386        let mut error = std::ptr::null_mut();
387        let mut trust = std::ptr::null_mut();
388        let raw = unsafe {
389            bridge::security_cms_decoder_copy_signer_status(
390                self.handle.as_ptr(),
391                bridge::len_to_isize(signer_index)?,
392                policy.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
393                evaluate_sec_trust,
394                &raw mut trust,
395                &raw mut status,
396                &raw mut error,
397            )
398        };
399        let trust = bridge::Handle::from_raw(trust).map(Trust::from_handle);
400        let value: Value = bridge::required_value(
401            "security_cms_decoder_copy_signer_status",
402            raw,
403            status,
404            error,
405        )?;
406        CmsSignerStatusReport::from_value(&value, trust)
407    }
408
409    /// Wraps the corresponding Security.framework CMS decoder operation.
410    pub fn signer_email_address(&self, signer_index: usize) -> Result<Option<String>> {
411        let mut status = 0;
412        let mut error = std::ptr::null_mut();
413        let raw = unsafe {
414            bridge::security_cms_decoder_copy_signer_email_address(
415                self.handle.as_ptr(),
416                bridge::len_to_isize(signer_index)?,
417                &raw mut status,
418                &raw mut error,
419            )
420        };
421        if raw.is_null() && status == 0 {
422            Ok(None)
423        } else {
424            bridge::required_string(
425                "security_cms_decoder_copy_signer_email_address",
426                raw,
427                status,
428                error,
429            )
430            .map(Some)
431        }
432    }
433
434    /// Wraps the corresponding Security.framework CMS decoder operation.
435    pub fn signer_certificate(&self, signer_index: usize) -> Result<Certificate> {
436        let mut status = 0;
437        let mut error = std::ptr::null_mut();
438        let raw = unsafe {
439            bridge::security_cms_decoder_copy_signer_cert(
440                self.handle.as_ptr(),
441                bridge::len_to_isize(signer_index)?,
442                &raw mut status,
443                &raw mut error,
444            )
445        };
446        bridge::required_handle("security_cms_decoder_copy_signer_cert", raw, status, error)
447            .map(Certificate::from_handle)
448    }
449
450    /// Wraps the corresponding Security.framework CMS decoder operation.
451    pub fn is_content_encrypted(&self) -> Result<bool> {
452        let mut status = 0;
453        let mut error = std::ptr::null_mut();
454        let encrypted = unsafe {
455            bridge::security_cms_decoder_is_content_encrypted(
456                self.handle.as_ptr(),
457                &raw mut status,
458                &raw mut error,
459            )
460        };
461        if status != 0 {
462            return Err(bridge::status_error(
463                "security_cms_decoder_is_content_encrypted",
464                status,
465                error,
466            )?);
467        }
468        Ok(encrypted)
469    }
470
471    /// Wraps the corresponding Security.framework CMS decoder operation.
472    pub fn encapsulated_content_type(&self) -> Result<Option<Vec<u8>>> {
473        let mut status = 0;
474        let mut error = std::ptr::null_mut();
475        let raw = unsafe {
476            bridge::security_cms_decoder_copy_encapsulated_content_type(
477                self.handle.as_ptr(),
478                &raw mut status,
479                &raw mut error,
480            )
481        };
482        if status != 0 {
483            return Err(bridge::status_error(
484                "security_cms_decoder_copy_encapsulated_content_type",
485                status,
486                error,
487            )?);
488        }
489        bridge::optional_data(raw)
490    }
491
492    /// Wraps the corresponding Security.framework CMS decoder operation.
493    pub fn content(&self) -> Result<Option<Vec<u8>>> {
494        let mut status = 0;
495        let mut error = std::ptr::null_mut();
496        let raw = unsafe {
497            bridge::security_cms_decoder_copy_content(
498                self.handle.as_ptr(),
499                &raw mut status,
500                &raw mut error,
501            )
502        };
503        if status != 0 {
504            return Err(bridge::status_error(
505                "security_cms_decoder_copy_content",
506                status,
507                error,
508            )?);
509        }
510        bridge::optional_data(raw)
511    }
512
513    /// Wraps the corresponding Security.framework CMS decoder operation.
514    pub fn signer_signing_time(&self, signer_index: usize) -> Result<Option<SystemTime>> {
515        decode_optional_cms_date("security_cms_decoder_copy_signer_signing_time", unsafe {
516            let mut status = 0;
517            let mut error = std::ptr::null_mut();
518            let raw = bridge::security_cms_decoder_copy_signer_signing_time(
519                self.handle.as_ptr(),
520                bridge::len_to_isize(signer_index)?,
521                &raw mut status,
522                &raw mut error,
523            );
524            (raw, status, error)
525        })
526    }
527
528    /// Wraps the corresponding Security.framework CMS decoder operation.
529    pub fn signer_timestamp(&self, signer_index: usize) -> Result<Option<SystemTime>> {
530        decode_optional_cms_date("security_cms_decoder_copy_signer_timestamp", unsafe {
531            let mut status = 0;
532            let mut error = std::ptr::null_mut();
533            let raw = bridge::security_cms_decoder_copy_signer_timestamp(
534                self.handle.as_ptr(),
535                bridge::len_to_isize(signer_index)?,
536                &raw mut status,
537                &raw mut error,
538            );
539            (raw, status, error)
540        })
541    }
542
543    /// Wraps the corresponding Security.framework CMS decoder operation.
544    pub fn signer_timestamp_with_policy(
545        &self,
546        policy: Option<&Policy>,
547        signer_index: usize,
548    ) -> Result<Option<SystemTime>> {
549        decode_optional_cms_date(
550            "security_cms_decoder_copy_signer_timestamp_with_policy",
551            unsafe {
552                let mut status = 0;
553                let mut error = std::ptr::null_mut();
554                let raw = bridge::security_cms_decoder_copy_signer_timestamp_with_policy(
555                    self.handle.as_ptr(),
556                    policy.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
557                    bridge::len_to_isize(signer_index)?,
558                    &raw mut status,
559                    &raw mut error,
560                );
561                (raw, status, error)
562            },
563        )
564    }
565
566    /// Wraps the corresponding Security.framework CMS decoder operation.
567    pub fn signer_timestamp_certificates(&self, signer_index: usize) -> Result<Value> {
568        let mut status = 0;
569        let mut error = std::ptr::null_mut();
570        let raw = unsafe {
571            bridge::security_cms_decoder_copy_signer_timestamp_certificates(
572                self.handle.as_ptr(),
573                bridge::len_to_isize(signer_index)?,
574                &raw mut status,
575                &raw mut error,
576            )
577        };
578        bridge::required_value(
579            "security_cms_decoder_copy_signer_timestamp_certificates",
580            raw,
581            status,
582            error,
583        )
584    }
585
586    /// Wraps the corresponding Security.framework CMS decoder operation.
587    pub fn all_certificates(&self) -> Result<Vec<Certificate>> {
588        let mut status = 0;
589        let mut error = std::ptr::null_mut();
590        let raw = unsafe {
591            bridge::security_cms_decoder_copy_all_certificates(
592                self.handle.as_ptr(),
593                &raw mut status,
594                &raw mut error,
595            )
596        };
597        let array_handle = bridge::required_handle(
598            "security_cms_decoder_copy_all_certificates",
599            raw,
600            status,
601            error,
602        )?;
603        Certificate::from_array_handle(&array_handle)
604    }
605}
606
607#[derive(Debug)]
608/// Wraps Security.framework CMS encoder state.
609pub struct CmsEncoder {
610    handle: bridge::Handle,
611}
612
613impl CmsEncoder {
614    fn from_handle(handle: bridge::Handle) -> Self {
615        Self { handle }
616    }
617
618    /// Wraps the corresponding Security.framework CMS encoder operation.
619    pub fn type_id() -> usize {
620        unsafe { bridge::security_cms_encoder_get_type_id() }
621    }
622
623    /// Wraps the corresponding Security.framework CMS encoder operation.
624    pub fn set_signer_algorithm(&mut self, algorithm: CmsDigestAlgorithm) -> Result<()> {
625        let algorithm = bridge::cstring(algorithm.as_bridge_name())?;
626        let mut error = std::ptr::null_mut();
627        let status = unsafe {
628            bridge::security_cms_encoder_set_signer_algorithm(
629                self.handle.as_ptr(),
630                algorithm.as_ptr(),
631                &raw mut error,
632            )
633        };
634        bridge::status_result("security_cms_encoder_set_signer_algorithm", status, error)
635    }
636
637    /// Wraps the corresponding Security.framework CMS encoder operation.
638    pub fn add_signers(&mut self, signers: &[Identity]) -> Result<()> {
639        let handles = signers.iter().map(Identity::handle).collect::<Vec<_>>();
640        let pointers = bridge::handle_pointer_array(&handles);
641        let mut error = std::ptr::null_mut();
642        let status = unsafe {
643            bridge::security_cms_encoder_add_signers(
644                self.handle.as_ptr(),
645                pointers.as_ptr(),
646                bridge::len_to_isize(pointers.len())?,
647                &raw mut error,
648            )
649        };
650        bridge::status_result("security_cms_encoder_add_signers", status, error)
651    }
652
653    /// Wraps the corresponding Security.framework CMS encoder operation.
654    pub fn signers(&self) -> Result<Value> {
655        let mut status = 0;
656        let mut error = std::ptr::null_mut();
657        let raw = unsafe {
658            bridge::security_cms_encoder_copy_signers(
659                self.handle.as_ptr(),
660                &raw mut status,
661                &raw mut error,
662            )
663        };
664        bridge::required_value("security_cms_encoder_copy_signers", raw, status, error)
665    }
666
667    /// Wraps the corresponding Security.framework CMS encoder operation.
668    pub fn add_recipients(&mut self, recipients: &[Certificate]) -> Result<()> {
669        let handles = recipients
670            .iter()
671            .map(Certificate::handle)
672            .collect::<Vec<_>>();
673        let pointers = bridge::handle_pointer_array(&handles);
674        let mut error = std::ptr::null_mut();
675        let status = unsafe {
676            bridge::security_cms_encoder_add_recipients(
677                self.handle.as_ptr(),
678                pointers.as_ptr(),
679                bridge::len_to_isize(pointers.len())?,
680                &raw mut error,
681            )
682        };
683        bridge::status_result("security_cms_encoder_add_recipients", status, error)
684    }
685
686    /// Wraps the corresponding Security.framework CMS encoder operation.
687    pub fn recipients(&self) -> Result<Value> {
688        let mut status = 0;
689        let mut error = std::ptr::null_mut();
690        let raw = unsafe {
691            bridge::security_cms_encoder_copy_recipients(
692                self.handle.as_ptr(),
693                &raw mut status,
694                &raw mut error,
695            )
696        };
697        bridge::required_value("security_cms_encoder_copy_recipients", raw, status, error)
698    }
699
700    /// Wraps the corresponding Security.framework CMS encoder operation.
701    pub fn set_has_detached_content(&mut self, detached_content: bool) -> Result<()> {
702        let mut error = std::ptr::null_mut();
703        let status = unsafe {
704            bridge::security_cms_encoder_set_has_detached_content(
705                self.handle.as_ptr(),
706                detached_content,
707                &raw mut error,
708            )
709        };
710        bridge::status_result(
711            "security_cms_encoder_set_has_detached_content",
712            status,
713            error,
714        )
715    }
716
717    /// Wraps the corresponding Security.framework CMS encoder operation.
718    pub fn has_detached_content(&self) -> Result<bool> {
719        let mut status = 0;
720        let mut error = std::ptr::null_mut();
721        let detached = unsafe {
722            bridge::security_cms_encoder_get_has_detached_content(
723                self.handle.as_ptr(),
724                &raw mut status,
725                &raw mut error,
726            )
727        };
728        if status != 0 {
729            return Err(bridge::status_error(
730                "security_cms_encoder_get_has_detached_content",
731                status,
732                error,
733            )?);
734        }
735        Ok(detached)
736    }
737
738    /// Wraps the corresponding Security.framework CMS encoder operation.
739    pub fn set_encapsulated_content_type_oid(&mut self, oid: &str) -> Result<()> {
740        let oid = bridge::cstring(oid)?;
741        let mut error = std::ptr::null_mut();
742        let status = unsafe {
743            bridge::security_cms_encoder_set_encapsulated_content_type_oid(
744                self.handle.as_ptr(),
745                oid.as_ptr(),
746                &raw mut error,
747            )
748        };
749        bridge::status_result(
750            "security_cms_encoder_set_encapsulated_content_type_oid",
751            status,
752            error,
753        )
754    }
755
756    /// Wraps the corresponding Security.framework CMS encoder operation.
757    pub fn encapsulated_content_type(&self) -> Result<Option<Vec<u8>>> {
758        let mut status = 0;
759        let mut error = std::ptr::null_mut();
760        let raw = unsafe {
761            bridge::security_cms_encoder_copy_encapsulated_content_type(
762                self.handle.as_ptr(),
763                &raw mut status,
764                &raw mut error,
765            )
766        };
767        if status != 0 {
768            return Err(bridge::status_error(
769                "security_cms_encoder_copy_encapsulated_content_type",
770                status,
771                error,
772            )?);
773        }
774        bridge::optional_data(raw)
775    }
776
777    /// Wraps the corresponding Security.framework CMS encoder operation.
778    pub fn add_supporting_certificates(&mut self, certificates: &[Certificate]) -> Result<()> {
779        let handles = certificates
780            .iter()
781            .map(Certificate::handle)
782            .collect::<Vec<_>>();
783        let pointers = bridge::handle_pointer_array(&handles);
784        let mut error = std::ptr::null_mut();
785        let status = unsafe {
786            bridge::security_cms_encoder_add_supporting_certs(
787                self.handle.as_ptr(),
788                pointers.as_ptr(),
789                bridge::len_to_isize(pointers.len())?,
790                &raw mut error,
791            )
792        };
793        bridge::status_result("security_cms_encoder_add_supporting_certs", status, error)
794    }
795
796    /// Wraps the corresponding Security.framework CMS encoder operation.
797    pub fn supporting_certificates(&self) -> Result<Value> {
798        let mut status = 0;
799        let mut error = std::ptr::null_mut();
800        let raw = unsafe {
801            bridge::security_cms_encoder_copy_supporting_certs(
802                self.handle.as_ptr(),
803                &raw mut status,
804                &raw mut error,
805            )
806        };
807        bridge::required_value(
808            "security_cms_encoder_copy_supporting_certs",
809            raw,
810            status,
811            error,
812        )
813    }
814
815    /// Wraps the corresponding Security.framework CMS encoder operation.
816    pub fn add_signed_attributes(&mut self, signed_attributes: CmsSignedAttributes) -> Result<()> {
817        let mut error = std::ptr::null_mut();
818        let status = unsafe {
819            bridge::security_cms_encoder_add_signed_attributes(
820                self.handle.as_ptr(),
821                signed_attributes.bits(),
822                &raw mut error,
823            )
824        };
825        bridge::status_result("security_cms_encoder_add_signed_attributes", status, error)
826    }
827
828    /// Wraps the corresponding Security.framework CMS encoder operation.
829    pub fn set_certificate_chain_mode(
830        &mut self,
831        chain_mode: CmsCertificateChainMode,
832    ) -> Result<()> {
833        let mut error = std::ptr::null_mut();
834        let status = unsafe {
835            bridge::security_cms_encoder_set_certificate_chain_mode(
836                self.handle.as_ptr(),
837                chain_mode as u32,
838                &raw mut error,
839            )
840        };
841        bridge::status_result(
842            "security_cms_encoder_set_certificate_chain_mode",
843            status,
844            error,
845        )
846    }
847
848    /// Wraps the corresponding Security.framework CMS encoder operation.
849    pub fn certificate_chain_mode(&self) -> Result<CmsCertificateChainMode> {
850        let mut status = 0;
851        let mut error = std::ptr::null_mut();
852        let mode = unsafe {
853            bridge::security_cms_encoder_get_certificate_chain_mode(
854                self.handle.as_ptr(),
855                &raw mut status,
856                &raw mut error,
857            )
858        };
859        if status != 0 {
860            return Err(bridge::status_error(
861                "security_cms_encoder_get_certificate_chain_mode",
862                status,
863                error,
864            )?);
865        }
866        CmsCertificateChainMode::from_raw(mode)
867    }
868
869    /// Wraps the corresponding Security.framework CMS encoder operation.
870    pub fn update_content(&mut self, data: &[u8]) -> Result<()> {
871        let mut error = std::ptr::null_mut();
872        let status = unsafe {
873            bridge::security_cms_encoder_update_content(
874                self.handle.as_ptr(),
875                data.as_ptr().cast(),
876                bridge::len_to_isize(data.len())?,
877                &raw mut error,
878            )
879        };
880        bridge::status_result("security_cms_encoder_update_content", status, error)
881    }
882
883    /// Wraps the corresponding Security.framework CMS encoder operation.
884    pub fn encoded_content(&self) -> Result<Vec<u8>> {
885        let mut status = 0;
886        let mut error = std::ptr::null_mut();
887        let raw = unsafe {
888            bridge::security_cms_encoder_copy_encoded_content(
889                self.handle.as_ptr(),
890                &raw mut status,
891                &raw mut error,
892            )
893        };
894        bridge::required_data(
895            "security_cms_encoder_copy_encoded_content",
896            raw,
897            status,
898            error,
899        )
900    }
901
902    /// Wraps the corresponding Security.framework CMS encoder operation.
903    pub fn signer_timestamp(&self, signer_index: usize) -> Result<Option<SystemTime>> {
904        decode_optional_cms_date("security_cms_encoder_copy_signer_timestamp", unsafe {
905            let mut status = 0;
906            let mut error = std::ptr::null_mut();
907            let raw = bridge::security_cms_encoder_copy_signer_timestamp(
908                self.handle.as_ptr(),
909                bridge::len_to_isize(signer_index)?,
910                &raw mut status,
911                &raw mut error,
912            );
913            (raw, status, error)
914        })
915    }
916
917    /// Wraps the corresponding Security.framework CMS encoder operation.
918    pub fn signer_timestamp_with_policy(
919        &self,
920        policy: Option<&Policy>,
921        signer_index: usize,
922    ) -> Result<Option<SystemTime>> {
923        decode_optional_cms_date(
924            "security_cms_encoder_copy_signer_timestamp_with_policy",
925            unsafe {
926                let mut status = 0;
927                let mut error = std::ptr::null_mut();
928                let raw = bridge::security_cms_encoder_copy_signer_timestamp_with_policy(
929                    self.handle.as_ptr(),
930                    policy.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
931                    bridge::len_to_isize(signer_index)?,
932                    &raw mut status,
933                    &raw mut error,
934                );
935                (raw, status, error)
936            },
937        )
938    }
939}
940
941/// Wraps convenience helpers around Security.framework CMS APIs.
942pub struct Cms;
943
944impl Cms {
945    /// Wraps the corresponding Security.framework CMS helper.
946    pub fn encoder() -> Result<CmsEncoder> {
947        let mut status = 0;
948        let mut error = std::ptr::null_mut();
949        let raw = unsafe { bridge::security_cms_encoder_create(&raw mut status, &raw mut error) };
950        bridge::required_handle("security_cms_encoder_create", raw, status, error)
951            .map(CmsEncoder::from_handle)
952    }
953
954    /// Wraps the corresponding Security.framework CMS helper.
955    pub fn decoder() -> Result<CmsDecoder> {
956        let mut status = 0;
957        let mut error = std::ptr::null_mut();
958        let raw = unsafe { bridge::security_cms_decoder_create(&raw mut status, &raw mut error) };
959        bridge::required_handle("security_cms_decoder_create", raw, status, error)
960            .map(CmsDecoder::from_handle)
961    }
962
963    /// Wraps the corresponding Security.framework CMS helper.
964    pub fn encode_supporting_certificates(certificates: &[Certificate]) -> Result<Vec<u8>> {
965        let mut encoder = Self::encoder()?;
966        encoder.add_supporting_certificates(certificates)?;
967        encoder.encoded_content()
968    }
969
970    /// Wraps the corresponding Security.framework CMS helper.
971    pub fn decode_all_certificates(data: &[u8]) -> Result<Vec<Certificate>> {
972        let mut status = 0;
973        let mut error = std::ptr::null_mut();
974        let raw = unsafe {
975            bridge::security_cms_decode_all_certificates(
976                data.as_ptr().cast(),
977                bridge::len_to_isize(data.len())?,
978                &raw mut status,
979                &raw mut error,
980            )
981        };
982        let array_handle =
983            bridge::required_handle("security_cms_decode_all_certificates", raw, status, error)?;
984        Certificate::from_array_handle(&array_handle)
985    }
986
987    /// Wraps the corresponding Security.framework CMS helper.
988    pub fn encode_content(
989        signers: &[Identity],
990        recipients: &[Certificate],
991        encapsulated_content_type_oid: Option<&str>,
992        detached_content: bool,
993        signed_attributes: CmsSignedAttributes,
994        content: &[u8],
995    ) -> Result<Vec<u8>> {
996        let signer_handles = signers.iter().map(Identity::handle).collect::<Vec<_>>();
997        let signer_pointers = bridge::handle_pointer_array(&signer_handles);
998        let recipient_handles = recipients
999            .iter()
1000            .map(Certificate::handle)
1001            .collect::<Vec<_>>();
1002        let recipient_pointers = bridge::handle_pointer_array(&recipient_handles);
1003        let encapsulated_content_type_oid = encapsulated_content_type_oid
1004            .map(bridge::cstring)
1005            .transpose()?;
1006        let mut status = 0;
1007        let mut error = std::ptr::null_mut();
1008        let raw = unsafe {
1009            bridge::security_cms_encode_content(
1010                signer_pointers.as_ptr(),
1011                bridge::len_to_isize(signer_pointers.len())?,
1012                recipient_pointers.as_ptr(),
1013                bridge::len_to_isize(recipient_pointers.len())?,
1014                encapsulated_content_type_oid
1015                    .as_ref()
1016                    .map_or(std::ptr::null(), bridge::BridgeString::as_ptr),
1017                detached_content,
1018                signed_attributes.bits(),
1019                content.as_ptr().cast(),
1020                bridge::len_to_isize(content.len())?,
1021                &raw mut status,
1022                &raw mut error,
1023            )
1024        };
1025        bridge::required_data("security_cms_encode_content", raw, status, error)
1026    }
1027}
1028
1029fn decode_optional_cms_date(
1030    operation: &'static str,
1031    result: (*mut std::ffi::c_void, i32, *mut std::ffi::c_void),
1032) -> Result<Option<SystemTime>> {
1033    let (raw, status, error) = result;
1034    if status != 0 {
1035        return Err(bridge::status_error(operation, status, error)?);
1036    }
1037    bridge::optional_value(raw)?.map_or(Ok(None), |value| {
1038        decode_cms_date(value, operation).map(Some)
1039    })
1040}
1041
1042fn decode_cms_date(value: Value, operation: &'static str) -> Result<SystemTime> {
1043    let unix = value
1044        .as_date()
1045        .ok_or_else(|| SecurityError::UnexpectedType {
1046            operation,
1047            expected: "date",
1048        })?;
1049    let out_of_range = || SecurityError::InvalidArgument("CMS date is out of range".to_owned());
1050    let duration = Duration::try_from_secs_f64(unix.abs()).map_err(|_| out_of_range())?;
1051    if unix >= 0.0 {
1052        UNIX_EPOCH.checked_add(duration).ok_or_else(out_of_range)
1053    } else {
1054        UNIX_EPOCH.checked_sub(duration).ok_or_else(out_of_range)
1055    }
1056}