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
//! OSX specific extensions to identity functionality.
use core_foundation::array::CFArray;
use core_foundation::base::TCFType;
use security_framework_sys::identity::SecIdentityCreateWithCertificate;
use std::ptr;

use crate::base::Result;
use crate::certificate::SecCertificate;
use crate::cvt;
use crate::identity::SecIdentity;
use crate::os::macos::keychain::SecKeychain;

/// An extension trait adding OSX specific functionality to `SecIdentity`.
pub trait SecIdentityExt {
    /// Creates an identity corresponding to a certificate, looking in the
    /// provided keychains for the corresponding private key.
    ///
    /// To search the default keychains, use an empty slice for `keychains`.
    ///
    /// <https://developer.apple.com/documentation/security/1401160-secidentitycreatewithcertificate>
    fn with_certificate(
        keychains: &[SecKeychain],
        certificate: &SecCertificate,
    ) -> Result<SecIdentity>;
}

impl SecIdentityExt for SecIdentity {
    fn with_certificate(keychains: &[SecKeychain], certificate: &SecCertificate) -> Result<Self> {
        let keychains = CFArray::from_CFTypes(keychains);
        unsafe {
            let mut identity = ptr::null_mut();
            cvt(SecIdentityCreateWithCertificate(
                if keychains.len() > 0 {keychains.as_CFTypeRef()} else {ptr::null()},
                certificate.as_concrete_TypeRef(),
                &mut identity,
            ))?;
            Ok(Self::wrap_under_create_rule(identity))
        }
    }
}

#[cfg(test)]
mod test {
    use tempfile::tempdir;

    use super::*;
    use crate::os::macos::certificate::SecCertificateExt;
    use crate::os::macos::import_export::ImportOptions;
    use crate::os::macos::keychain::CreateOptions;
    use crate::os::macos::test::identity;
    use crate::test;

    #[test]
    fn certificate() {
        let dir = p!(tempdir());
        let identity = identity(dir.path());
        let certificate = p!(identity.certificate());
        assert_eq!("foobar.com", p!(certificate.common_name()));
    }

    #[test]
    fn private_key() {
        let dir = p!(tempdir());
        let identity = identity(dir.path());
        p!(identity.private_key());
    }

    #[test]
    fn with_certificate() {
        let dir = p!(tempdir());

        let mut keychain = p!(CreateOptions::new()
            .password("foobar")
            .create(dir.path().join("test.keychain")));

        let key = include_bytes!("../../../test/server.key");
        p!(ImportOptions::new()
            .filename("server.key")
            .keychain(&mut keychain)
            .import(key));

        let cert = test::certificate();
        p!(SecIdentity::with_certificate(&[keychain], &cert));
    }
}