Skip to main content

security/
identity.rs

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