security-rs 0.6.0

Safe Rust bindings for Apple's Security framework — keychain, identity, certificates, trust, authorization, CMS, SecureTransport, and cryptographic primitives on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
use base64::Engine;
use bitflags::bitflags;
use serde_json::Value;
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::path::{Path, PathBuf};

use crate::bridge;
use crate::error::{Result, SecurityError};

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    /// Mirrors `SecCSFlags`.
    pub struct CodeSigningFlags: u32 {
        /// Mirrors a `SecCSFlags` bit.
        const CHECK_ALL_ARCHITECTURES = 1 << 0;
        /// Mirrors a `SecCSFlags` bit.
        const DO_NOT_VALIDATE_EXECUTABLE = 1 << 1;
        /// Mirrors a `SecCSFlags` bit.
        const DO_NOT_VALIDATE_RESOURCES = 1 << 2;
        /// Mirrors a `SecCSFlags` bit.
        const BASIC_VALIDATE_ONLY = Self::DO_NOT_VALIDATE_EXECUTABLE.bits() | Self::DO_NOT_VALIDATE_RESOURCES.bits();
        /// Mirrors a `SecCSFlags` bit.
        const CHECK_NESTED_CODE = 1 << 3;
        /// Mirrors a `SecCSFlags` bit.
        const STRICT_VALIDATE = 1 << 4;
        /// Mirrors a `SecCSFlags` bit.
        const FULL_REPORT = 1 << 5;
        /// Mirrors a `SecCSFlags` bit.
        const CHECK_GATEKEEPER_ARCHITECTURES = (1 << 6) | Self::CHECK_ALL_ARCHITECTURES.bits();
        /// Mirrors a `SecCSFlags` bit.
        const RESTRICT_SYMLINKS = 1 << 7;
        /// Mirrors a `SecCSFlags` bit.
        const RESTRICT_TO_APP_LIKE = 1 << 8;
        /// Mirrors a `SecCSFlags` bit.
        const RESTRICT_SIDEBAND_DATA = 1 << 9;
        /// Mirrors a `SecCSFlags` bit.
        const USE_SOFTWARE_SIGNING_CERT = 1 << 10;
        /// Mirrors a `SecCSFlags` bit.
        const VALIDATE_PEH = 1 << 11;
        /// Mirrors a `SecCSFlags` bit.
        const SINGLE_THREADED = 1 << 12;
        /// Mirrors a `SecCSFlags` bit.
        const ALLOW_NETWORK_ACCESS = 1 << 16;
        /// Mirrors a `SecCSFlags` bit.
        const FAST_EXECUTABLE_VALIDATION = 1 << 17;
        const CHECK_TRUSTED_ANCHORS = 1 << 27;
        const NO_NETWORK_ACCESS = 1 << 29;
        const ENFORCE_REVOCATION_CHECKS = 1 << 30;
        const CONSIDER_EXPIRATION = 1 << 31;
    }
}

bitflags! {
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct CodeStatus: u32 {
        const VALID = 0x0000_0001;
        const HARD = 0x0000_0100;
        const KILL = 0x0000_0200;
        const PLATFORM = 0x0400_0000;
        const DEBUGGED = 0x1000_0000;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AuditToken([u32; 8]);

impl AuditToken {
    pub const LEN: usize = 32;

    pub const fn from_raw(values: [u32; 8]) -> Self {
        Self(values)
    }

    pub const fn to_raw(self) -> [u32; 8] {
        self.0
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != Self::LEN {
            return Err(SecurityError::InvalidArgument(format!(
                "an audit token is {} bytes, got {}",
                Self::LEN,
                bytes.len()
            )));
        }
        let mut values = [0_u32; 8];
        for (value, chunk) in values.iter_mut().zip(bytes.chunks_exact(4)) {
            *value = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
        }
        Ok(Self(values))
    }

    pub fn to_bytes(self) -> [u8; 32] {
        let mut bytes = [0_u8; 32];
        for (chunk, value) in bytes.chunks_exact_mut(4).zip(self.0) {
            chunk.copy_from_slice(&value.to_ne_bytes());
        }
        bytes
    }

    pub fn current() -> Result<Self> {
        let mut values = [0_u32; 8];
        if unsafe { bridge::security_audit_token_copy_current(values.as_mut_ptr()) } {
            Ok(Self(values))
        } else {
            Err(SecurityError::InvalidArgument(
                "task_info(TASK_AUDIT_TOKEN) failed for the current task".to_owned(),
            ))
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Mirrors values returned by `SecCodeCopySigningInformation`.
pub enum SigningValue {
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Boolean(bool),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Integer(i64),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    String(String),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Data(Vec<u8>),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Array(Vec<Self>),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Dictionary(BTreeMap<String, Self>),
    /// Mirrors a value decoded from `SecCodeCopySigningInformation`.
    Unknown(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Mirrors structured data returned by `SecCodeCopySigningInformation`.
pub struct SigningInformation {
    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
    pub identifier: Option<String>,
    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
    pub team_identifier: Option<String>,
    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
    pub entitlements: BTreeMap<String, SigningValue>,
    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
    pub sandboxed: bool,
    /// Mirrors a field returned by `SecCodeCopySigningInformation`.
    pub status: Option<u32>,
}

impl SigningInformation {
    /// Wraps the corresponding Security.framework operation for `SigningInformation`.
    pub const fn is_signed(&self) -> bool {
        self.identifier.is_some()
    }

    pub fn code_status(&self) -> Option<CodeStatus> {
        self.status.map(CodeStatus::from_bits_retain)
    }

    fn from_json(value: &Value) -> Self {
        let entitlements = find_object(
            value,
            &[
                "entitlements-dict",
                "EntitlementsDict",
                "entitlements",
                "Entitlements",
            ],
        );
        Self {
            identifier: find_string(value, &["identifier", "Identifier"]),
            team_identifier: find_string(value, &["teamid", "TeamIdentifier", "teamIdentifier"]),
            entitlements: entitlements.map(json_object_to_map).unwrap_or_default(),
            sandboxed: matches!(
                entitlements.and_then(|value| value.get("com.apple.security.app-sandbox")),
                Some(Value::Bool(true))
            ),
            status: find_integer(value, &["status", "Status"])
                .and_then(|value| u32::try_from(value).ok()),
        }
    }
}

#[derive(Debug)]
/// Wraps `SecCodeRef`.
pub struct Code {
    handle: bridge::Handle,
}

impl Code {
    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn type_id() -> usize {
        unsafe { bridge::security_code_get_type_id() }
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn current() -> Result<Self> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe { bridge::security_code_copy_self(&raw mut status, &raw mut error) };
        bridge::required_handle("security_code_copy_self", raw, status, error)
            .map(|handle| Self { handle })
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn host(&self) -> Result<Self> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_copy_host(self.handle.as_ptr(), &raw mut status, &raw mut error)
        };
        bridge::required_handle("security_code_copy_host", raw, status, error)
            .map(|handle| Self { handle })
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn guest_with_attributes(
        host: Option<&Self>,
        attributes: Option<&Value>,
        flags: CodeSigningFlags,
    ) -> Result<Self> {
        let attributes = attributes.map(bridge::json_cstring).transpose()?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_copy_guest_with_attributes(
                host.map_or(std::ptr::null_mut(), |value| value.handle.as_ptr()),
                attributes
                    .as_ref()
                    .map_or(std::ptr::null(), |value| value.as_ptr()),
                flags.bits(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle(
            "security_code_copy_guest_with_attributes",
            raw,
            status,
            error,
        )
        .map(|handle| Self { handle })
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn static_code(&self) -> Result<StaticCode> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_copy_static_code(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle("security_code_copy_static_code", raw, status, error)
            .map(StaticCode::from_handle)
    }

    pub fn guest_with_audit_token(audit_token: &AuditToken) -> Result<Self> {
        let values = audit_token.to_raw();
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_copy_guest_with_audit_token(
                values.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle(
            "security_code_copy_guest_with_audit_token",
            raw,
            status,
            error,
        )
        .map(|handle| Self { handle })
    }

    #[allow(clippy::missing_safety_doc)]
    pub unsafe fn from_xpc_message(message: *mut c_void) -> Result<Self> {
        if message.is_null() {
            return Err(SecurityError::InvalidArgument(
                "an XPC message object is required".to_owned(),
            ));
        }
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_create_with_xpc_message(message, &raw mut status, &raw mut error)
        };
        bridge::required_handle("security_code_create_with_xpc_message", raw, status, error)
            .map(|handle| Self { handle })
    }

    pub fn audit_token(&self) -> Option<AuditToken> {
        let mut values = [0_u32; 8];
        unsafe { bridge::security_code_copy_audit_token(self.handle.as_ptr(), values.as_mut_ptr()) }
            .then_some(AuditToken(values))
    }

    pub fn check_validity(
        &self,
        flags: CodeSigningFlags,
        requirement: Option<&Requirement>,
    ) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_code_check_validity(
                self.handle.as_ptr(),
                flags.bits(),
                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
                &raw mut error,
            )
        };
        bridge::status_result("security_code_check_validity", status, error)
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn signing_information(&self) -> Result<SigningInformation> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_code_copy_signing_information(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        let value: Value =
            bridge::required_json("security_code_copy_signing_information", raw, status, error)?;
        Ok(SigningInformation::from_json(&value))
    }

    /// Wraps the corresponding `SecCodeRef` operation.
    pub fn task(&self) -> Result<Task> {
        let audit_token = self.audit_token().ok_or_else(|| {
            SecurityError::Unsupported(
                "this code object was not looked up by audit token, so its task cannot be \
                 identified without a PID race; use Code::guest_with_audit_token"
                    .to_owned(),
            )
        })?;
        Task::from_audit_token(&audit_token)
    }
}

#[derive(Debug)]
/// Wraps `SecRequirementRef`.
pub struct Requirement {
    handle: bridge::Handle,
}

impl Requirement {
    fn from_handle(handle: bridge::Handle) -> Self {
        Self { handle }
    }

    fn handle(&self) -> &bridge::Handle {
        &self.handle
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn type_id() -> usize {
        unsafe { bridge::security_requirement_get_type_id() }
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn from_data(data: &[u8]) -> Result<Self> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_requirement_create_with_data(
                data.as_ptr().cast(),
                bridge::len_to_isize(data.len())?,
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle("security_requirement_create_with_data", raw, status, error)
            .map(Self::from_handle)
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn from_string(text: &str) -> Result<Self> {
        let text = bridge::cstring(text)?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_requirement_create_with_string(
                text.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle(
            "security_requirement_create_with_string",
            raw,
            status,
            error,
        )
        .map(Self::from_handle)
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn from_string_with_errors(text: &str) -> Result<Self> {
        let text = bridge::cstring(text)?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_requirement_create_with_string_and_errors(
                text.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle(
            "security_requirement_create_with_string_and_errors",
            raw,
            status,
            error,
        )
        .map(Self::from_handle)
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn data(&self) -> Result<Vec<u8>> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_requirement_copy_data(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_data("security_requirement_copy_data", raw, status, error)
    }

    /// Wraps the corresponding `SecRequirementRef` operation.
    pub fn string(&self) -> Result<String> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_requirement_copy_string(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_string("security_requirement_copy_string", raw, status, error)
    }
}

#[derive(Debug)]
/// Wraps `SecStaticCodeRef`.
pub struct StaticCode {
    handle: bridge::Handle,
}

impl StaticCode {
    fn from_handle(handle: bridge::Handle) -> Self {
        Self { handle }
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn type_id() -> usize {
        unsafe { bridge::security_static_code_get_type_id() }
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_static_code_create_with_path(
                path.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle("security_static_code_create_with_path", raw, status, error)
            .map(Self::from_handle)
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn from_path_with_attributes(path: impl AsRef<Path>, attributes: &Value) -> Result<Self> {
        let path = bridge::cstring(&path.as_ref().to_string_lossy())?;
        let attributes = bridge::json_cstring(attributes)?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_static_code_create_with_path_and_attributes(
                path.as_ptr(),
                attributes.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle(
            "security_static_code_create_with_path_and_attributes",
            raw,
            status,
            error,
        )
        .map(Self::from_handle)
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn check_validity(&self) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_check_static_validity_with_errors(
                self.handle.as_ptr(),
                CodeSigningFlags::empty().bits(),
                std::ptr::null_mut(),
                &raw mut error,
            )
        };
        bridge::status_result(
            "security_static_code_check_static_validity_with_errors",
            status,
            error,
        )
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn check_validity_with_errors(
        &self,
        flags: CodeSigningFlags,
        requirement: Option<&Requirement>,
    ) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_check_static_validity_with_errors(
                self.handle.as_ptr(),
                flags.bits(),
                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
                &raw mut error,
            )
        };
        bridge::status_result(
            "security_static_code_check_static_validity_with_errors",
            status,
            error,
        )
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn check_static_validity(
        &self,
        flags: CodeSigningFlags,
        requirement: Option<&Requirement>,
    ) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_check_static_validity(
                self.handle.as_ptr(),
                flags.bits(),
                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
                &raw mut error,
            )
        };
        bridge::status_result("security_static_code_check_static_validity", status, error)
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn check_static_validity_with_errors(
        &self,
        flags: CodeSigningFlags,
        requirement: Option<&Requirement>,
    ) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_check_static_validity_with_errors(
                self.handle.as_ptr(),
                flags.bits(),
                requirement.map_or(std::ptr::null_mut(), |value| value.handle().as_ptr()),
                &raw mut error,
            )
        };
        bridge::status_result(
            "security_static_code_check_static_validity_with_errors",
            status,
            error,
        )
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn path(&self) -> Result<PathBuf> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_static_code_copy_path(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_string("security_static_code_copy_path", raw, status, error)
            .map(PathBuf::from)
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn designated_requirement(&self) -> Result<String> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_static_code_copy_designated_requirement(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_string(
            "security_static_code_copy_designated_requirement",
            raw,
            status,
            error,
        )
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn signing_information(&self) -> Result<SigningInformation> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_static_code_copy_signing_information(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        let value: Value = bridge::required_json(
            "security_static_code_copy_signing_information",
            raw,
            status,
            error,
        )?;
        Ok(SigningInformation::from_json(&value))
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn validate_file_resource(
        &self,
        relative_path: &str,
        data: &[u8],
        flags: CodeSigningFlags,
    ) -> Result<()> {
        let relative_path = bridge::cstring(relative_path)?;
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_validate_file_resource(
                self.handle.as_ptr(),
                relative_path.as_ptr(),
                data.as_ptr().cast(),
                bridge::len_to_isize(data.len())?,
                flags.bits(),
                &raw mut error,
            )
        };
        bridge::status_result("security_static_code_validate_file_resource", status, error)
    }

    /// Wraps the corresponding `SecStaticCodeRef` operation.
    pub fn map_memory(&self, flags: CodeSigningFlags) -> Result<()> {
        let mut error = std::ptr::null_mut();
        let status = unsafe {
            bridge::security_static_code_map_memory(
                self.handle.as_ptr(),
                flags.bits(),
                &raw mut error,
            )
        };
        bridge::status_result("security_static_code_map_memory", status, error)
    }
}

#[derive(Debug)]
/// Wraps `SecTaskRef`.
pub struct Task {
    handle: bridge::Handle,
}

impl Task {
    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn type_id() -> usize {
        unsafe { bridge::security_task_get_type_id() }
    }

    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn current() -> Result<Self> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw =
            unsafe { bridge::security_task_create_from_self(&raw mut status, &raw mut error) };
        bridge::required_handle("security_task_create_from_self", raw, status, error)
            .map(|handle| Self { handle })
    }

    pub fn from_audit_token(audit_token: &AuditToken) -> Result<Self> {
        let values = audit_token.to_raw();
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_task_create_with_audit_token(
                values.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_handle("security_task_create_with_audit_token", raw, status, error)
            .map(|handle| Self { handle })
    }

    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn current_with_audit_token() -> Result<Self> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_task_create_from_current_audit_token(&raw mut status, &raw mut error)
        };
        bridge::required_handle(
            "security_task_create_from_current_audit_token",
            raw,
            status,
            error,
        )
        .map(|handle| Self { handle })
    }

    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn signing_identifier(&self) -> Result<Option<String>> {
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_task_copy_signing_identifier(
                self.handle.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        if raw.is_null() && status == 0 {
            Ok(None)
        } else {
            bridge::required_string("security_task_copy_signing_identifier", raw, status, error)
                .map(Some)
        }
    }

    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn entitlement(&self, entitlement: &str) -> Result<Option<Value>> {
        let entitlement = bridge::cstring(entitlement)?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_task_copy_value_for_entitlement(
                self.handle.as_ptr(),
                entitlement.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        if raw.is_null() && status == 0 {
            return Ok(None);
        }
        let value: Value = bridge::required_json(
            "security_task_copy_value_for_entitlement",
            raw,
            status,
            error,
        )?;
        Ok(Some(value))
    }

    /// Wraps the corresponding `SecTaskRef` operation.
    pub fn entitlements(&self, entitlements: &[&str]) -> Result<Value> {
        let entitlements = bridge::json_cstring(&entitlements)?;
        let mut status = 0;
        let mut error = std::ptr::null_mut();
        let raw = unsafe {
            bridge::security_task_copy_values_for_entitlements(
                self.handle.as_ptr(),
                entitlements.as_ptr(),
                &raw mut status,
                &raw mut error,
            )
        };
        bridge::required_json(
            "security_task_copy_values_for_entitlements",
            raw,
            status,
            error,
        )
    }
}

fn find_object<'a>(value: &'a Value, keys: &[&str]) -> Option<&'a serde_json::Map<String, Value>> {
    keys.iter()
        .find_map(|key| value.get(*key))
        .and_then(Value::as_object)
}

fn find_string(value: &Value, keys: &[&str]) -> Option<String> {
    keys.iter()
        .find_map(|key| value.get(*key))
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
}

fn find_integer(value: &Value, keys: &[&str]) -> Option<i64> {
    keys.iter()
        .find_map(|key| value.get(*key))
        .and_then(Value::as_i64)
}

fn json_object_to_map(object: &serde_json::Map<String, Value>) -> BTreeMap<String, SigningValue> {
    object
        .iter()
        .map(|(key, value)| (key.clone(), signing_value(value)))
        .collect()
}

fn signing_value(value: &Value) -> SigningValue {
    match value {
        Value::Bool(value) => SigningValue::Boolean(*value),
        Value::Number(value) => value.as_i64().map_or_else(
            || SigningValue::Unknown(value.to_string()),
            SigningValue::Integer,
        ),
        Value::String(value) => SigningValue::String(value.clone()),
        Value::Array(values) => {
            if let Some(data) = data_from_wrapped_json(value) {
                SigningValue::Data(data)
            } else {
                SigningValue::Array(values.iter().map(signing_value).collect())
            }
        }
        Value::Object(object) => {
            if let Some(data) = data_from_wrapped_json(value) {
                SigningValue::Data(data)
            } else {
                SigningValue::Dictionary(json_object_to_map(object))
            }
        }
        Value::Null => SigningValue::Unknown("null".to_owned()),
    }
}

fn data_from_wrapped_json(value: &Value) -> Option<Vec<u8>> {
    let object = value.as_object()?;
    if object.get("_type")?.as_str()? != "data" {
        return None;
    }
    let base64 = object.get("base64")?.as_str()?;
    base64::engine::general_purpose::STANDARD
        .decode(base64)
        .ok()
}