Skip to main content

security/
identity.rs

1use serde_json::Value;
2use zeroize::Zeroizing;
3
4use crate::bridge;
5use crate::certificate::Certificate;
6use crate::error::{status, Result, SecurityError, StatusError};
7use crate::key::PrivateKey;
8
9#[derive(Debug)]
10/// Wraps `SecIdentityRef`.
11pub struct Identity {
12    handle: bridge::Handle,
13}
14
15impl Identity {
16    pub(crate) fn from_handle(handle: bridge::Handle) -> Self {
17        Self { handle }
18    }
19
20    pub(crate) fn handle(&self) -> &bridge::Handle {
21        &self.handle
22    }
23
24    /// Wraps the corresponding `SecIdentityRef` operation.
25    pub fn type_id() -> usize {
26        unsafe { bridge::security_identity_get_type_id() }
27    }
28
29    /// Wraps the corresponding `SecIdentityRef` operation.
30    pub fn import_pkcs12_first(data: &[u8], password: &str) -> Result<Self> {
31        let password = Zeroizing::new(bridge::cstring(password)?.into_bytes_with_nul());
32        let mut status = 0;
33        let mut error = std::ptr::null_mut();
34        let raw = unsafe {
35            bridge::security_identity_import_pkcs12_first(
36                data.as_ptr().cast(),
37                bridge::len_to_isize(data.len())?,
38                password.as_ptr().cast(),
39                &raw mut status,
40                &raw mut error,
41            )
42        };
43        bridge::required_handle("security_identity_import_pkcs12_first", raw, status, error)
44            .map(Self::from_handle)
45            .map_err(|error| match error {
46                SecurityError::Status(StatusError {
47                    status: status::UNIMPLEMENTED,
48                    message,
49                    ..
50                }) => SecurityError::Unsupported(message),
51                other => other,
52            })
53    }
54
55    /// Wraps the corresponding `SecIdentityRef` operation.
56    pub fn from_certificate_and_private_key(
57        certificate: &Certificate,
58        private_key: &PrivateKey,
59    ) -> Result<Self> {
60        let mut status = 0;
61        let mut error = std::ptr::null_mut();
62        let raw = unsafe {
63            bridge::security_identity_create(
64                certificate.handle().as_ptr(),
65                private_key.handle().as_ptr(),
66                &raw mut status,
67                &raw mut error,
68            )
69        };
70        bridge::required_handle("security_identity_create", raw, status, error)
71            .map(Self::from_handle)
72    }
73
74    /// Wraps the corresponding `SecIdentityRef` operation.
75    pub fn with_certificate(certificate: &Certificate) -> Result<Self> {
76        let mut status = 0;
77        let mut error = std::ptr::null_mut();
78        let raw = unsafe {
79            bridge::security_identity_create_with_certificate(
80                certificate.handle().as_ptr(),
81                &raw mut status,
82                &raw mut error,
83            )
84        };
85        bridge::required_handle(
86            "security_identity_create_with_certificate",
87            raw,
88            status,
89            error,
90        )
91        .map(Self::from_handle)
92    }
93
94    /// Wraps the corresponding `SecIdentityRef` operation.
95    pub fn preferred(
96        name: &str,
97        key_usage: &[&str],
98        valid_issuers: &[Vec<u8>],
99    ) -> Result<Option<Self>> {
100        let name = bridge::cstring(name)?;
101        let key_usage = (!key_usage.is_empty())
102            .then(|| bridge::json_cstring(&key_usage))
103            .transpose()?;
104        let valid_issuers = (!valid_issuers.is_empty())
105            .then(|| bridge::json_cstring(&valid_issuers))
106            .transpose()?;
107        let mut status = 0;
108        let mut error = std::ptr::null_mut();
109        let raw = unsafe {
110            bridge::security_identity_copy_preferred(
111                name.as_ptr(),
112                key_usage
113                    .as_ref()
114                    .map_or(std::ptr::null(), |value| value.as_ptr()),
115                valid_issuers
116                    .as_ref()
117                    .map_or(std::ptr::null(), |value| value.as_ptr()),
118                &raw mut status,
119                &raw mut error,
120            )
121        };
122        if raw.is_null() && status == 0 {
123            Ok(None)
124        } else {
125            bridge::required_handle("security_identity_copy_preferred", raw, status, error)
126                .map(Self::from_handle)
127                .map(Some)
128        }
129    }
130
131    /// Wraps the corresponding `SecIdentityRef` operation.
132    pub fn set_preferred(identity: Option<&Self>, name: &str, key_usage: &[&str]) -> Result<()> {
133        let name = bridge::cstring(name)?;
134        let key_usage = (!key_usage.is_empty())
135            .then(|| bridge::json_cstring(&key_usage))
136            .transpose()?;
137        let mut error = std::ptr::null_mut();
138        let status = unsafe {
139            bridge::security_identity_set_preferred(
140                identity.map_or(std::ptr::null_mut(), |value| value.handle.as_ptr()),
141                name.as_ptr(),
142                key_usage
143                    .as_ref()
144                    .map_or(std::ptr::null(), |value| value.as_ptr()),
145                &raw mut error,
146            )
147        };
148        bridge::status_result("security_identity_set_preferred", status, error)
149    }
150
151    /// Wraps the corresponding `SecIdentityRef` operation.
152    pub fn copy_system_identity(domain: &str) -> Result<Self> {
153        let domain = bridge::cstring(domain)?;
154        let mut status = 0;
155        let mut error = std::ptr::null_mut();
156        let raw = unsafe {
157            bridge::security_identity_copy_system_identity(
158                domain.as_ptr(),
159                &raw mut status,
160                &raw mut error,
161            )
162        };
163        bridge::required_handle("security_identity_copy_system_identity", raw, status, error)
164            .map(Self::from_handle)
165    }
166
167    /// Wraps the corresponding `SecIdentityRef` operation.
168    pub fn set_system_identity(domain: &str, identity: Option<&Self>) -> Result<()> {
169        let domain = bridge::cstring(domain)?;
170        let mut error = std::ptr::null_mut();
171        let status = unsafe {
172            bridge::security_identity_set_system_identity(
173                domain.as_ptr(),
174                identity.map_or(std::ptr::null_mut(), |value| value.handle.as_ptr()),
175                &raw mut error,
176            )
177        };
178        bridge::status_result("security_identity_set_system_identity", status, error)
179    }
180
181    /// Wraps the corresponding `SecIdentityRef` operation.
182    pub fn actual_domain(&self) -> Result<Option<String>> {
183        let raw = unsafe { bridge::security_identity_copy_actual_domain(self.handle.as_ptr()) };
184        bridge::optional_string(raw)
185    }
186
187    /// Wraps the corresponding `SecIdentityRef` operation.
188    pub fn label(&self) -> Result<Option<String>> {
189        let raw = unsafe { bridge::security_identity_copy_label(self.handle.as_ptr()) };
190        bridge::optional_string(raw)
191    }
192
193    /// Wraps the corresponding `SecIdentityRef` operation.
194    pub fn chain_count(&self) -> usize {
195        usize::try_from(unsafe { bridge::security_identity_get_chain_count(self.handle.as_ptr()) })
196            .unwrap_or_default()
197    }
198
199    /// Wraps the corresponding `SecIdentityRef` operation.
200    pub fn certificate(&self) -> Result<Certificate> {
201        let mut status = 0;
202        let mut error = std::ptr::null_mut();
203        let raw = unsafe {
204            bridge::security_identity_copy_certificate(
205                self.handle.as_ptr(),
206                &raw mut status,
207                &raw mut error,
208            )
209        };
210        bridge::required_handle("security_identity_copy_certificate", raw, status, error)
211            .map(Certificate::from_handle)
212    }
213
214    /// Wraps the corresponding `SecIdentityRef` operation.
215    pub fn private_key_attributes(&self) -> Result<Value> {
216        let mut status = 0;
217        let mut error = std::ptr::null_mut();
218        let raw = unsafe {
219            bridge::security_identity_copy_private_key_attributes(
220                self.handle.as_ptr(),
221                &raw mut status,
222                &raw mut error,
223            )
224        };
225        bridge::required_json(
226            "security_identity_copy_private_key_attributes",
227            raw,
228            status,
229            error,
230        )
231    }
232}