Skip to main content

security/
code.rs

1use base64::Engine;
2use bitflags::bitflags;
3use serde_json::Value;
4use std::collections::BTreeMap;
5use std::ffi::c_void;
6use std::path::{Path, PathBuf};
7
8use crate::bridge;
9use crate::error::{Result, SecurityError};
10
11bitflags! {
12    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13    /// Mirrors `SecCSFlags`.
14    pub struct CodeSigningFlags: u32 {
15        /// Mirrors a `SecCSFlags` bit.
16        const CHECK_ALL_ARCHITECTURES = 1 << 0;
17        /// Mirrors a `SecCSFlags` bit.
18        const DO_NOT_VALIDATE_EXECUTABLE = 1 << 1;
19        /// Mirrors a `SecCSFlags` bit.
20        const DO_NOT_VALIDATE_RESOURCES = 1 << 2;
21        /// Mirrors a `SecCSFlags` bit.
22        const BASIC_VALIDATE_ONLY = Self::DO_NOT_VALIDATE_EXECUTABLE.bits() | Self::DO_NOT_VALIDATE_RESOURCES.bits();
23        /// Mirrors a `SecCSFlags` bit.
24        const CHECK_NESTED_CODE = 1 << 3;
25        /// Mirrors a `SecCSFlags` bit.
26        const STRICT_VALIDATE = 1 << 4;
27        /// Mirrors a `SecCSFlags` bit.
28        const FULL_REPORT = 1 << 5;
29        /// Mirrors a `SecCSFlags` bit.
30        const CHECK_GATEKEEPER_ARCHITECTURES = (1 << 6) | Self::CHECK_ALL_ARCHITECTURES.bits();
31        /// Mirrors a `SecCSFlags` bit.
32        const RESTRICT_SYMLINKS = 1 << 7;
33        /// Mirrors a `SecCSFlags` bit.
34        const RESTRICT_TO_APP_LIKE = 1 << 8;
35        /// Mirrors a `SecCSFlags` bit.
36        const RESTRICT_SIDEBAND_DATA = 1 << 9;
37        /// Mirrors a `SecCSFlags` bit.
38        const USE_SOFTWARE_SIGNING_CERT = 1 << 10;
39        /// Mirrors a `SecCSFlags` bit.
40        const VALIDATE_PEH = 1 << 11;
41        /// Mirrors a `SecCSFlags` bit.
42        const SINGLE_THREADED = 1 << 12;
43        /// Mirrors a `SecCSFlags` bit.
44        const ALLOW_NETWORK_ACCESS = 1 << 16;
45        /// Mirrors a `SecCSFlags` bit.
46        const FAST_EXECUTABLE_VALIDATION = 1 << 17;
47        const CHECK_TRUSTED_ANCHORS = 1 << 27;
48        const NO_NETWORK_ACCESS = 1 << 29;
49        const ENFORCE_REVOCATION_CHECKS = 1 << 30;
50        const CONSIDER_EXPIRATION = 1 << 31;
51    }
52}
53
54bitflags! {
55    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56    pub struct CodeStatus: u32 {
57        const VALID = 0x0000_0001;
58        const HARD = 0x0000_0100;
59        const KILL = 0x0000_0200;
60        const PLATFORM = 0x0400_0000;
61        const DEBUGGED = 0x1000_0000;
62    }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct AuditToken([u32; 8]);
67
68impl AuditToken {
69    pub const LEN: usize = 32;
70
71    pub const fn from_raw(values: [u32; 8]) -> Self {
72        Self(values)
73    }
74
75    pub const fn to_raw(self) -> [u32; 8] {
76        self.0
77    }
78
79    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
80        if bytes.len() != Self::LEN {
81            return Err(SecurityError::InvalidArgument(format!(
82                "an audit token is {} bytes, got {}",
83                Self::LEN,
84                bytes.len()
85            )));
86        }
87        let mut values = [0_u32; 8];
88        for (value, chunk) in values.iter_mut().zip(bytes.chunks_exact(4)) {
89            *value = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
90        }
91        Ok(Self(values))
92    }
93
94    pub fn to_bytes(self) -> [u8; 32] {
95        let mut bytes = [0_u8; 32];
96        for (chunk, value) in bytes.chunks_exact_mut(4).zip(self.0) {
97            chunk.copy_from_slice(&value.to_ne_bytes());
98        }
99        bytes
100    }
101
102    pub fn current() -> Result<Self> {
103        let mut values = [0_u32; 8];
104        if unsafe { bridge::security_audit_token_copy_current(values.as_mut_ptr()) } {
105            Ok(Self(values))
106        } else {
107            Err(SecurityError::InvalidArgument(
108                "task_info(TASK_AUDIT_TOKEN) failed for the current task".to_owned(),
109            ))
110        }
111    }
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
115#[non_exhaustive]
116/// Mirrors values returned by `SecCodeCopySigningInformation`.
117pub enum SigningValue {
118    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
119    Boolean(bool),
120    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
121    Integer(i64),
122    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
123    String(String),
124    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
125    Data(Vec<u8>),
126    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
127    Array(Vec<Self>),
128    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
129    Dictionary(BTreeMap<String, Self>),
130    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
131    Unknown(String),
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
135/// Mirrors structured data returned by `SecCodeCopySigningInformation`.
136pub struct SigningInformation {
137    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
138    pub identifier: Option<String>,
139    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
140    pub team_identifier: Option<String>,
141    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
142    pub entitlements: BTreeMap<String, SigningValue>,
143    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
144    pub sandboxed: bool,
145    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
146    pub status: Option<u32>,
147}
148
149impl SigningInformation {
150    /// Wraps the corresponding Security.framework operation for `SigningInformation`.
151    pub const fn is_signed(&self) -> bool {
152        self.identifier.is_some()
153    }
154
155    pub fn code_status(&self) -> Option<CodeStatus> {
156        self.status.map(CodeStatus::from_bits_retain)
157    }
158
159    fn from_json(value: &Value) -> Self {
160        let entitlements = find_object(
161            value,
162            &[
163                "entitlements-dict",
164                "EntitlementsDict",
165                "entitlements",
166                "Entitlements",
167            ],
168        );
169        Self {
170            identifier: find_string(value, &["identifier", "Identifier"]),
171            team_identifier: find_string(value, &["teamid", "TeamIdentifier", "teamIdentifier"]),
172            entitlements: entitlements.map(json_object_to_map).unwrap_or_default(),
173            sandboxed: matches!(
174                entitlements.and_then(|value| value.get("com.apple.security.app-sandbox")),
175                Some(Value::Bool(true))
176            ),
177            status: find_integer(value, &["status", "Status"])
178                .and_then(|value| u32::try_from(value).ok()),
179        }
180    }
181}
182
183#[derive(Debug)]
184/// Wraps `SecCodeRef`.
185pub struct Code {
186    handle: bridge::Handle,
187}
188
189impl Code {
190    /// Wraps the corresponding `SecCodeRef` operation.
191    pub fn type_id() -> usize {
192        unsafe { bridge::security_code_get_type_id() }
193    }
194
195    /// Wraps the corresponding `SecCodeRef` operation.
196    pub fn current() -> Result<Self> {
197        let mut status = 0;
198        let mut error = std::ptr::null_mut();
199        let raw = unsafe { bridge::security_code_copy_self(&raw mut status, &raw mut error) };
200        bridge::required_handle("security_code_copy_self", raw, status, error)
201            .map(|handle| Self { handle })
202    }
203
204    /// Wraps the corresponding `SecCodeRef` operation.
205    pub fn host(&self) -> Result<Self> {
206        let mut status = 0;
207        let mut error = std::ptr::null_mut();
208        let raw = unsafe {
209            bridge::security_code_copy_host(self.handle.as_ptr(), &raw mut status, &raw mut error)
210        };
211        bridge::required_handle("security_code_copy_host", raw, status, error)
212            .map(|handle| Self { handle })
213    }
214
215    /// Wraps the corresponding `SecCodeRef` operation.
216    pub fn guest_with_attributes(
217        host: Option<&Self>,
218        attributes: Option<&Value>,
219        flags: CodeSigningFlags,
220    ) -> Result<Self> {
221        let attributes = attributes.map(bridge::json_cstring).transpose()?;
222        let mut status = 0;
223        let mut error = std::ptr::null_mut();
224        let raw = unsafe {
225            bridge::security_code_copy_guest_with_attributes(
226                host.map_or(std::ptr::null_mut(), |value| value.handle.as_ptr()),
227                attributes
228                    .as_ref()
229                    .map_or(std::ptr::null(), |value| value.as_ptr()),
230                flags.bits(),
231                &raw mut status,
232                &raw mut error,
233            )
234        };
235        bridge::required_handle(
236            "security_code_copy_guest_with_attributes",
237            raw,
238            status,
239            error,
240        )
241        .map(|handle| Self { handle })
242    }
243
244    /// Wraps the corresponding `SecCodeRef` operation.
245    pub fn static_code(&self) -> Result<StaticCode> {
246        let mut status = 0;
247        let mut error = std::ptr::null_mut();
248        let raw = unsafe {
249            bridge::security_code_copy_static_code(
250                self.handle.as_ptr(),
251                &raw mut status,
252                &raw mut error,
253            )
254        };
255        bridge::required_handle("security_code_copy_static_code", raw, status, error)
256            .map(StaticCode::from_handle)
257    }
258
259    pub fn guest_with_audit_token(audit_token: &AuditToken) -> Result<Self> {
260        let values = audit_token.to_raw();
261        let mut status = 0;
262        let mut error = std::ptr::null_mut();
263        let raw = unsafe {
264            bridge::security_code_copy_guest_with_audit_token(
265                values.as_ptr(),
266                &raw mut status,
267                &raw mut error,
268            )
269        };
270        bridge::required_handle(
271            "security_code_copy_guest_with_audit_token",
272            raw,
273            status,
274            error,
275        )
276        .map(|handle| Self { handle })
277    }
278
279    #[allow(clippy::missing_safety_doc)]
280    pub unsafe fn from_xpc_message(message: *mut c_void) -> Result<Self> {
281        if message.is_null() {
282            return Err(SecurityError::InvalidArgument(
283                "an XPC message object is required".to_owned(),
284            ));
285        }
286        let mut status = 0;
287        let mut error = std::ptr::null_mut();
288        let raw = unsafe {
289            bridge::security_code_create_with_xpc_message(message, &raw mut status, &raw mut error)
290        };
291        bridge::required_handle("security_code_create_with_xpc_message", raw, status, error)
292            .map(|handle| Self { handle })
293    }
294
295    pub fn audit_token(&self) -> Option<AuditToken> {
296        let mut values = [0_u32; 8];
297        unsafe { bridge::security_code_copy_audit_token(self.handle.as_ptr(), values.as_mut_ptr()) }
298            .then_some(AuditToken(values))
299    }
300
301    pub fn check_validity(
302        &self,
303        flags: CodeSigningFlags,
304        requirement: Option<&Requirement>,
305    ) -> Result<()> {
306        let mut error = std::ptr::null_mut();
307        let status = unsafe {
308            bridge::security_code_check_validity(
309                self.handle.as_ptr(),
310                flags.bits(),
311                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
312                &raw mut error,
313            )
314        };
315        bridge::status_result("security_code_check_validity", status, error)
316    }
317
318    /// Wraps the corresponding `SecCodeRef` operation.
319    pub fn signing_information(&self) -> Result<SigningInformation> {
320        let mut status = 0;
321        let mut error = std::ptr::null_mut();
322        let raw = unsafe {
323            bridge::security_code_copy_signing_information(
324                self.handle.as_ptr(),
325                &raw mut status,
326                &raw mut error,
327            )
328        };
329        let value: Value =
330            bridge::required_json("security_code_copy_signing_information", raw, status, error)?;
331        Ok(SigningInformation::from_json(&value))
332    }
333
334    /// Wraps the corresponding `SecCodeRef` operation.
335    pub fn task(&self) -> Result<Task> {
336        let audit_token = self.audit_token().ok_or_else(|| {
337            SecurityError::Unsupported(
338                "this code object was not looked up by audit token, so its task cannot be \
339                 identified without a PID race; use Code::guest_with_audit_token"
340                    .to_owned(),
341            )
342        })?;
343        Task::from_audit_token(&audit_token)
344    }
345}
346
347#[derive(Debug)]
348/// Wraps `SecRequirementRef`.
349pub struct Requirement {
350    handle: bridge::Handle,
351}
352
353impl Requirement {
354    fn from_handle(handle: bridge::Handle) -> Self {
355        Self { handle }
356    }
357
358    fn handle(&self) -> &bridge::Handle {
359        &self.handle
360    }
361
362    /// Wraps the corresponding `SecRequirementRef` operation.
363    pub fn type_id() -> usize {
364        unsafe { bridge::security_requirement_get_type_id() }
365    }
366
367    /// Wraps the corresponding `SecRequirementRef` operation.
368    pub fn from_data(data: &[u8]) -> Result<Self> {
369        let mut status = 0;
370        let mut error = std::ptr::null_mut();
371        let raw = unsafe {
372            bridge::security_requirement_create_with_data(
373                data.as_ptr().cast(),
374                bridge::len_to_isize(data.len())?,
375                &raw mut status,
376                &raw mut error,
377            )
378        };
379        bridge::required_handle("security_requirement_create_with_data", raw, status, error)
380            .map(Self::from_handle)
381    }
382
383    /// Wraps the corresponding `SecRequirementRef` operation.
384    pub fn from_string(text: &str) -> Result<Self> {
385        let text = bridge::cstring(text)?;
386        let mut status = 0;
387        let mut error = std::ptr::null_mut();
388        let raw = unsafe {
389            bridge::security_requirement_create_with_string(
390                text.as_ptr(),
391                &raw mut status,
392                &raw mut error,
393            )
394        };
395        bridge::required_handle(
396            "security_requirement_create_with_string",
397            raw,
398            status,
399            error,
400        )
401        .map(Self::from_handle)
402    }
403
404    /// Wraps the corresponding `SecRequirementRef` operation.
405    pub fn from_string_with_errors(text: &str) -> Result<Self> {
406        let text = bridge::cstring(text)?;
407        let mut status = 0;
408        let mut error = std::ptr::null_mut();
409        let raw = unsafe {
410            bridge::security_requirement_create_with_string_and_errors(
411                text.as_ptr(),
412                &raw mut status,
413                &raw mut error,
414            )
415        };
416        bridge::required_handle(
417            "security_requirement_create_with_string_and_errors",
418            raw,
419            status,
420            error,
421        )
422        .map(Self::from_handle)
423    }
424
425    /// Wraps the corresponding `SecRequirementRef` operation.
426    pub fn data(&self) -> Result<Vec<u8>> {
427        let mut status = 0;
428        let mut error = std::ptr::null_mut();
429        let raw = unsafe {
430            bridge::security_requirement_copy_data(
431                self.handle.as_ptr(),
432                &raw mut status,
433                &raw mut error,
434            )
435        };
436        bridge::required_data("security_requirement_copy_data", raw, status, error)
437    }
438
439    /// Wraps the corresponding `SecRequirementRef` operation.
440    pub fn string(&self) -> Result<String> {
441        let mut status = 0;
442        let mut error = std::ptr::null_mut();
443        let raw = unsafe {
444            bridge::security_requirement_copy_string(
445                self.handle.as_ptr(),
446                &raw mut status,
447                &raw mut error,
448            )
449        };
450        bridge::required_string("security_requirement_copy_string", raw, status, error)
451    }
452}
453
454#[derive(Debug)]
455/// Wraps `SecStaticCodeRef`.
456pub struct StaticCode {
457    handle: bridge::Handle,
458}
459
460impl StaticCode {
461    fn from_handle(handle: bridge::Handle) -> Self {
462        Self { handle }
463    }
464
465    /// Wraps the corresponding `SecStaticCodeRef` operation.
466    pub fn type_id() -> usize {
467        unsafe { bridge::security_static_code_get_type_id() }
468    }
469
470    /// Wraps the corresponding `SecStaticCodeRef` operation.
471    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
472        let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
473        let mut status = 0;
474        let mut error = std::ptr::null_mut();
475        let raw = unsafe {
476            bridge::security_static_code_create_with_path(
477                path.as_ptr(),
478                &raw mut status,
479                &raw mut error,
480            )
481        };
482        bridge::required_handle("security_static_code_create_with_path", raw, status, error)
483            .map(Self::from_handle)
484    }
485
486    /// Wraps the corresponding `SecStaticCodeRef` operation.
487    pub fn from_path_with_attributes(path: impl AsRef<Path>, attributes: &Value) -> Result<Self> {
488        let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
489        let attributes = bridge::json_cstring(attributes)?;
490        let mut status = 0;
491        let mut error = std::ptr::null_mut();
492        let raw = unsafe {
493            bridge::security_static_code_create_with_path_and_attributes(
494                path.as_ptr(),
495                attributes.as_ptr(),
496                &raw mut status,
497                &raw mut error,
498            )
499        };
500        bridge::required_handle(
501            "security_static_code_create_with_path_and_attributes",
502            raw,
503            status,
504            error,
505        )
506        .map(Self::from_handle)
507    }
508
509    /// Wraps the corresponding `SecStaticCodeRef` operation.
510    pub fn check_validity(&self) -> Result<()> {
511        let mut error = std::ptr::null_mut();
512        let status = unsafe {
513            bridge::security_static_code_check_static_validity_with_errors(
514                self.handle.as_ptr(),
515                CodeSigningFlags::empty().bits(),
516                std::ptr::null_mut(),
517                &raw mut error,
518            )
519        };
520        bridge::status_result(
521            "security_static_code_check_static_validity_with_errors",
522            status,
523            error,
524        )
525    }
526
527    /// Wraps the corresponding `SecStaticCodeRef` operation.
528    pub fn check_validity_with_errors(
529        &self,
530        flags: CodeSigningFlags,
531        requirement: Option<&Requirement>,
532    ) -> Result<()> {
533        let mut error = std::ptr::null_mut();
534        let status = unsafe {
535            bridge::security_static_code_check_static_validity_with_errors(
536                self.handle.as_ptr(),
537                flags.bits(),
538                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
539                &raw mut error,
540            )
541        };
542        bridge::status_result(
543            "security_static_code_check_static_validity_with_errors",
544            status,
545            error,
546        )
547    }
548
549    /// Wraps the corresponding `SecStaticCodeRef` operation.
550    pub fn check_static_validity(
551        &self,
552        flags: CodeSigningFlags,
553        requirement: Option<&Requirement>,
554    ) -> Result<()> {
555        let mut error = std::ptr::null_mut();
556        let status = unsafe {
557            bridge::security_static_code_check_static_validity(
558                self.handle.as_ptr(),
559                flags.bits(),
560                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
561                &raw mut error,
562            )
563        };
564        bridge::status_result("security_static_code_check_static_validity", status, error)
565    }
566
567    /// Wraps the corresponding `SecStaticCodeRef` operation.
568    pub fn check_static_validity_with_errors(
569        &self,
570        flags: CodeSigningFlags,
571        requirement: Option<&Requirement>,
572    ) -> Result<()> {
573        let mut error = std::ptr::null_mut();
574        let status = unsafe {
575            bridge::security_static_code_check_static_validity_with_errors(
576                self.handle.as_ptr(),
577                flags.bits(),
578                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
579                &raw mut error,
580            )
581        };
582        bridge::status_result(
583            "security_static_code_check_static_validity_with_errors",
584            status,
585            error,
586        )
587    }
588
589    /// Wraps the corresponding `SecStaticCodeRef` operation.
590    pub fn path(&self) -> Result<PathBuf> {
591        let mut status = 0;
592        let mut error = std::ptr::null_mut();
593        let raw = unsafe {
594            bridge::security_static_code_copy_path(
595                self.handle.as_ptr(),
596                &raw mut status,
597                &raw mut error,
598            )
599        };
600        bridge::required_string("security_static_code_copy_path", raw, status, error)
601            .map(PathBuf::from)
602    }
603
604    /// Wraps the corresponding `SecStaticCodeRef` operation.
605    pub fn designated_requirement(&self) -> Result<String> {
606        let mut status = 0;
607        let mut error = std::ptr::null_mut();
608        let raw = unsafe {
609            bridge::security_static_code_copy_designated_requirement(
610                self.handle.as_ptr(),
611                &raw mut status,
612                &raw mut error,
613            )
614        };
615        bridge::required_string(
616            "security_static_code_copy_designated_requirement",
617            raw,
618            status,
619            error,
620        )
621    }
622
623    /// Wraps the corresponding `SecStaticCodeRef` operation.
624    pub fn signing_information(&self) -> Result<SigningInformation> {
625        let mut status = 0;
626        let mut error = std::ptr::null_mut();
627        let raw = unsafe {
628            bridge::security_static_code_copy_signing_information(
629                self.handle.as_ptr(),
630                &raw mut status,
631                &raw mut error,
632            )
633        };
634        let value: Value = bridge::required_json(
635            "security_static_code_copy_signing_information",
636            raw,
637            status,
638            error,
639        )?;
640        Ok(SigningInformation::from_json(&value))
641    }
642
643    /// Wraps the corresponding `SecStaticCodeRef` operation.
644    pub fn validate_file_resource(
645        &self,
646        relative_path: &str,
647        data: &[u8],
648        flags: CodeSigningFlags,
649    ) -> Result<()> {
650        let relative_path = bridge::cstring(relative_path)?;
651        let mut error = std::ptr::null_mut();
652        let status = unsafe {
653            bridge::security_static_code_validate_file_resource(
654                self.handle.as_ptr(),
655                relative_path.as_ptr(),
656                data.as_ptr().cast(),
657                bridge::len_to_isize(data.len())?,
658                flags.bits(),
659                &raw mut error,
660            )
661        };
662        bridge::status_result("security_static_code_validate_file_resource", status, error)
663    }
664
665    /// Wraps the corresponding `SecStaticCodeRef` operation.
666    pub fn map_memory(&self, flags: CodeSigningFlags) -> Result<()> {
667        let mut error = std::ptr::null_mut();
668        let status = unsafe {
669            bridge::security_static_code_map_memory(
670                self.handle.as_ptr(),
671                flags.bits(),
672                &raw mut error,
673            )
674        };
675        bridge::status_result("security_static_code_map_memory", status, error)
676    }
677}
678
679#[derive(Debug)]
680/// Wraps `SecTaskRef`.
681pub struct Task {
682    handle: bridge::Handle,
683}
684
685impl Task {
686    /// Wraps the corresponding `SecTaskRef` operation.
687    pub fn type_id() -> usize {
688        unsafe { bridge::security_task_get_type_id() }
689    }
690
691    /// Wraps the corresponding `SecTaskRef` operation.
692    pub fn current() -> Result<Self> {
693        let mut status = 0;
694        let mut error = std::ptr::null_mut();
695        let raw =
696            unsafe { bridge::security_task_create_from_self(&raw mut status, &raw mut error) };
697        bridge::required_handle("security_task_create_from_self", raw, status, error)
698            .map(|handle| Self { handle })
699    }
700
701    pub fn from_audit_token(audit_token: &AuditToken) -> Result<Self> {
702        let values = audit_token.to_raw();
703        let mut status = 0;
704        let mut error = std::ptr::null_mut();
705        let raw = unsafe {
706            bridge::security_task_create_with_audit_token(
707                values.as_ptr(),
708                &raw mut status,
709                &raw mut error,
710            )
711        };
712        bridge::required_handle("security_task_create_with_audit_token", raw, status, error)
713            .map(|handle| Self { handle })
714    }
715
716    /// Wraps the corresponding `SecTaskRef` operation.
717    pub fn current_with_audit_token() -> Result<Self> {
718        let mut status = 0;
719        let mut error = std::ptr::null_mut();
720        let raw = unsafe {
721            bridge::security_task_create_from_current_audit_token(&raw mut status, &raw mut error)
722        };
723        bridge::required_handle(
724            "security_task_create_from_current_audit_token",
725            raw,
726            status,
727            error,
728        )
729        .map(|handle| Self { handle })
730    }
731
732    /// Wraps the corresponding `SecTaskRef` operation.
733    pub fn signing_identifier(&self) -> Result<Option<String>> {
734        let mut status = 0;
735        let mut error = std::ptr::null_mut();
736        let raw = unsafe {
737            bridge::security_task_copy_signing_identifier(
738                self.handle.as_ptr(),
739                &raw mut status,
740                &raw mut error,
741            )
742        };
743        if raw.is_null() && status == 0 {
744            Ok(None)
745        } else {
746            bridge::required_string("security_task_copy_signing_identifier", raw, status, error)
747                .map(Some)
748        }
749    }
750
751    /// Wraps the corresponding `SecTaskRef` operation.
752    pub fn entitlement(&self, entitlement: &str) -> Result<Option<Value>> {
753        let entitlement = bridge::cstring(entitlement)?;
754        let mut status = 0;
755        let mut error = std::ptr::null_mut();
756        let raw = unsafe {
757            bridge::security_task_copy_value_for_entitlement(
758                self.handle.as_ptr(),
759                entitlement.as_ptr(),
760                &raw mut status,
761                &raw mut error,
762            )
763        };
764        if raw.is_null() && status == 0 {
765            return Ok(None);
766        }
767        let value: Value = bridge::required_json(
768            "security_task_copy_value_for_entitlement",
769            raw,
770            status,
771            error,
772        )?;
773        Ok(Some(value))
774    }
775
776    /// Wraps the corresponding `SecTaskRef` operation.
777    pub fn entitlements(&self, entitlements: &[&str]) -> Result<Value> {
778        let entitlements = bridge::json_cstring(&entitlements)?;
779        let mut status = 0;
780        let mut error = std::ptr::null_mut();
781        let raw = unsafe {
782            bridge::security_task_copy_values_for_entitlements(
783                self.handle.as_ptr(),
784                entitlements.as_ptr(),
785                &raw mut status,
786                &raw mut error,
787            )
788        };
789        bridge::required_json(
790            "security_task_copy_values_for_entitlements",
791            raw,
792            status,
793            error,
794        )
795    }
796}
797
798fn find_object<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a serde_json::Map<String, Value>> {
799    keys.iter()
800        .find_map(|key| value.get(*key))
801        .and_then(Value::as_object)
802}
803
804fn find_string(value: &Value, keys: &[&str]) -> Option<String> {
805    keys.iter()
806        .find_map(|key| value.get(*key))
807        .and_then(Value::as_str)
808        .map(ToOwned::to_owned)
809}
810
811fn find_integer(value: &Value, keys: &[&str]) -> Option<i64> {
812    keys.iter()
813        .find_map(|key| value.get(*key))
814        .and_then(Value::as_i64)
815}
816
817fn json_object_to_map(object: &serde_json::Map<String, Value>) -> BTreeMap<String, SigningValue> {
818    object
819        .iter()
820        .map(|(key, value)| (key.clone(), signing_value(value)))
821        .collect()
822}
823
824fn signing_value(value: &Value) -> SigningValue {
825    match value {
826        Value::Bool(value) => SigningValue::Boolean(*value),
827        Value::Number(value) => value.as_i64().map_or_else(
828            || SigningValue::Unknown(value.to_string()),
829            SigningValue::Integer,
830        ),
831        Value::String(value) => SigningValue::String(value.clone()),
832        Value::Array(values) => {
833            if let Some(data) = data_from_wrapped_json(value) {
834                SigningValue::Data(data)
835            } else {
836                SigningValue::Array(values.iter().map(signing_value).collect())
837            }
838        }
839        Value::Object(object) => {
840            if let Some(data) = data_from_wrapped_json(value) {
841                SigningValue::Data(data)
842            } else {
843                SigningValue::Dictionary(json_object_to_map(object))
844            }
845        }
846        Value::Null => SigningValue::Unknown("null".to_owned()),
847    }
848}
849
850fn data_from_wrapped_json(value: &Value) -> Option<Vec<u8>> {
851    let object = value.as_object()?;
852    if object.get("_type")?.as_str()? != "data" {
853        return None;
854    }
855    let base64 = object.get("base64")?.as_str()?;
856    base64::engine::general_purpose::STANDARD
857        .decode(base64)
858        .ok()
859}