kanidmd_lib/valueset/
certificate.rs1use crate::{
2 be::dbvalue::DbValueCertificate,
3 prelude::*,
4 schema::SchemaAttribute,
5 valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
6};
7use crypto_glue::{
8 s256::Sha256Output,
9 traits::{DecodeDer, EncodeDer, EncodePem, LineEndingPem},
10 x509::{x509_digest_public_key_sha256, Certificate},
11};
12use kanidm_proto::scim_v1::{
13 client::ScimCertificate as ClientScimCertificate, server::ScimCertificate, JsonValue,
14};
15use std::collections::BTreeMap;
16
17#[derive(Debug, Clone)]
18pub struct ValueSetCertificate {
19 map: BTreeMap<Sha256Output, Box<Certificate>>,
20}
21
22impl ValueSetCertificate {
23 pub fn new(certificate: Box<Certificate>) -> Result<Box<Self>, OperationError> {
24 let mut map = BTreeMap::new();
25
26 let pk_s256 = x509_digest_public_key_sha256(&certificate).ok_or_else(|| {
27 error!("Unable to digest public key");
28 OperationError::VS0002CertificatePublicKeyDigest
29 })?;
30 map.insert(pk_s256, certificate);
31
32 Ok(Box::new(ValueSetCertificate { map }))
33 }
34
35 pub fn from_dbvs2(data: Vec<DbValueCertificate>) -> Result<ValueSet, OperationError> {
36 Self::from_dbv_iter(data.into_iter())
37 }
38
39 fn from_dbv_iter(
40 certs: impl Iterator<Item = DbValueCertificate>,
41 ) -> Result<ValueSet, OperationError> {
42 let mut map = BTreeMap::new();
43
44 for db_cert in certs {
45 match db_cert {
46 DbValueCertificate::V1 { certificate_der } => {
47 let certificate = Certificate::from_der(&certificate_der)
49 .map(Box::new)
50 .map_err(|x509_err| {
51 error!(?x509_err, "Unable to restore certificate from DER");
52 OperationError::VS0003CertificateDerDecode
53 })?;
54
55 let pk_s256 = x509_digest_public_key_sha256(&certificate).ok_or_else(|| {
57 error!("Unable to digest public key");
58 OperationError::VS0004CertificatePublicKeyDigest
59 })?;
60
61 map.insert(pk_s256, certificate);
62 }
63 }
64 }
65
66 Ok(Box::new(ValueSetCertificate { map }))
67 }
68
69 fn to_vec_dbvs(&self) -> Vec<DbValueCertificate> {
70 self.map
71 .iter()
72 .filter_map(|(pk_s256, cert)| {
73 cert.to_der()
74 .map_err(|der_err| {
75 error!(
76 ?pk_s256,
77 ?der_err,
78 "Failed to serialise certificate to der. This value will be dropped!"
79 );
80 })
81 .ok()
82 })
83 .map(|certificate_der| DbValueCertificate::V1 { certificate_der })
84 .collect()
85 }
86
87 #[allow(clippy::should_implement_trait)]
88 pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
89 where
90 T: IntoIterator<Item = Box<Certificate>>,
91 {
92 let mut map = BTreeMap::new();
93
94 for certificate in iter {
95 let pk_s256 = x509_digest_public_key_sha256(&certificate)?;
96 map.insert(pk_s256, certificate);
97 }
98
99 Some(Box::new(ValueSetCertificate { map }))
100 }
101}
102
103impl ValueSetScimPut for ValueSetCertificate {
104 fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
105 let der_values: Vec<ClientScimCertificate> =
106 serde_json::from_value(value).map_err(|err| {
107 error!(?err, "SCIM Certificate syntax invalid");
108 OperationError::SC0012CertificateSyntaxInvalid
109 })?;
110
111 let mut map = BTreeMap::new();
113
114 for ClientScimCertificate { der } in der_values {
115 let certificate = Certificate::from_der(&der)
117 .map(Box::new)
118 .map_err(|x509_err| {
119 error!(?x509_err, "Unable to restore certificate from DER");
120 OperationError::SC0013CertificateInvalidDer
121 })?;
122
123 let pk_s256 = x509_digest_public_key_sha256(&certificate).ok_or_else(|| {
125 error!("Unable to digest public key");
126 OperationError::SC0014CertificateInvalidDigest
127 })?;
128
129 map.insert(pk_s256, certificate);
130 }
131
132 Ok(ValueSetResolveStatus::Resolved(Box::new(
133 ValueSetCertificate { map },
134 )))
135 }
136}
137
138impl ValueSetT for ValueSetCertificate {
139 fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
140 match value {
141 Value::Certificate(certificate) => {
142 let pk_s256 = x509_digest_public_key_sha256(&certificate).ok_or_else(|| {
143 error!("Unable to digest public key");
144 OperationError::VS0005CertificatePublicKeyDigest
145 })?;
146
147 Ok(self.map.insert(pk_s256, certificate).is_none())
149 }
150 _ => {
151 debug_assert!(false);
152 Err(OperationError::InvalidValueState)
153 }
154 }
155 }
156
157 fn clear(&mut self) {
158 self.map.clear();
159 }
160
161 fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
162 if let PartialValue::HexString(hs) = pv {
163 let mut buf = Sha256Output::default();
164 if hex::decode_to_slice(hs, &mut buf).is_ok() {
165 self.map.remove(&buf);
166 }
167 };
168 self.map.is_empty()
169 }
170
171 fn contains(&self, pv: &PartialValue) -> bool {
172 match pv {
173 PartialValue::HexString(hs) => {
174 let mut buf = Sha256Output::default();
175 if hex::decode_to_slice(hs, &mut buf).is_ok() {
176 self.map.contains_key(&buf)
177 } else {
178 false
179 }
180 }
181 _ => false,
182 }
183 }
184
185 fn substring(&self, _pv: &PartialValue) -> bool {
186 false
187 }
188
189 fn startswith(&self, _pv: &PartialValue) -> bool {
190 false
191 }
192
193 fn endswith(&self, _pv: &PartialValue) -> bool {
194 false
195 }
196
197 fn lessthan(&self, _pv: &PartialValue) -> bool {
198 false
199 }
200
201 fn len(&self) -> usize {
202 self.map.len()
203 }
204
205 fn generate_idx_eq_keys(&self) -> Vec<String> {
206 self.map.keys().map(hex::encode).collect()
207 }
208
209 fn syntax(&self) -> SyntaxType {
210 SyntaxType::Certificate
211 }
212
213 fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
214 true
215 }
216
217 fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
218 Box::new(self.map.iter().filter_map(|(pk_s256, cert)| {
219 cert.to_pem(LineEndingPem::LF)
220 .ok()
221 .map(|pem| format!("{}\n{}", hex::encode(pk_s256), pem))
222 }))
223 }
224
225 fn to_scim_value(&self) -> Option<ScimResolveStatus> {
226 let vals: Vec<ScimCertificate> = self
227 .map
228 .iter()
229 .filter_map(|(s256, cert)| {
230 cert.to_der()
231 .map_err(|der_err| {
232 error!(
233 ?s256,
234 ?der_err,
235 "Failed to serialise certificate to der. This value will be dropped!"
236 );
237 })
238 .ok()
239 .map(|der| (s256, der))
240 })
241 .map(|(s256, cert_der)| ScimCertificate {
242 s256: s256.to_vec(),
243 der: cert_der,
244 })
245 .collect::<Vec<_>>();
246
247 if vals.is_empty() {
248 None
249 } else {
250 Some(ScimValueKanidm::from(vals).into())
251 }
252 }
253
254 fn to_db_valueset_v2(&self) -> DbValueSetV2 {
255 let data = self.to_vec_dbvs();
256 DbValueSetV2::Certificate(data)
257 }
258
259 fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
260 Box::new(
261 self.map
262 .keys()
263 .map(hex::encode)
264 .map(PartialValue::HexString),
265 )
266 }
267
268 fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
269 Box::new(self.map.values().cloned().map(Value::Certificate))
270 }
271
272 fn equal(&self, other: &ValueSet) -> bool {
273 if let Some(other) = other.as_certificate_set() {
274 &self.map == other
275 } else {
276 debug_assert!(false);
277 false
278 }
279 }
280
281 fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
282 if let Some(b) = other.as_certificate_set() {
283 mergemaps!(self.map, b)
284 } else {
285 debug_assert!(false);
286 Err(OperationError::InvalidValueState)
287 }
288 }
289
290 fn to_certificate_single(&self) -> Option<&Certificate> {
291 if self.map.len() == 1 {
292 self.map.values().take(1).map(|b| b.as_ref()).next()
293 } else {
294 None
295 }
296 }
297
298 fn as_certificate_set(&self) -> Option<&BTreeMap<Sha256Output, Box<Certificate>>> {
299 Some(&self.map)
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use super::ValueSetCertificate;
306 use crate::prelude::{ScimValueKanidm, ValueSet};
307 use crypto_glue::{traits::DecodePem, x509::Certificate};
308
309 const PEM_DATA: &str = r#"-----BEGIN CERTIFICATE-----
314MIIB3zCCAYWgAwIBAgIUdJ6IWvI+8M6nwK7ykUK7/iBq7yQwCgYIKoZIzj0EAwIw
315RTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGElu
316dGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDA4MjEwNjQ2MzBaFw0yNTA4MjEw
317NjQ2MzBaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYD
318VQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwWTATBgcqhkjOPQIBBggqhkjO
319PQMBBwNCAAS2Szn4NPmgxawC1+MRC41jqobemNkXkRZ9AgozK0zRDFc6k1IHUZ++
320wN0USpXDQYDnJfATqvlpKPebnHxTytt6o1MwUTAdBgNVHQ4EFgQU1oR1x2CnoPap
321JMKPCVVzqWf2ANYwHwYDVR0jBBgwFoAU1oR1x2CnoPapJMKPCVVzqWf2ANYwDwYD
322VR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAgNIADBFAiBpy0o2CY97MIxeQ0HgG44Y
323raBy6edj7W0EIH+yQxkDEwIhAI0nVKaI6duHLAvtKW6CfEQFG6jKg7dyk37YYiRD
3242jS0
325-----END CERTIFICATE-----"#;
326
327 #[test]
328 fn test_scim_certificate() {
329 let cert = Certificate::from_pem(PEM_DATA).unwrap();
330
331 let vs: ValueSet = ValueSetCertificate::new(Box::new(cert)).unwrap();
332
333 let scim_value = vs.to_scim_value().unwrap().assume_resolved();
334
335 let cert = match scim_value {
336 ScimValueKanidm::ArrayCertificate(mut set) => set.pop().unwrap(),
337 _ => unreachable!(),
338 };
339
340 let expect_s256 =
341 hex::decode("8c98a09d0a50db92ccb6d05be846d9b9315015520d19a3e1739aeb8d84ebc28d")
342 .unwrap();
343
344 assert_eq!(cert.s256, expect_s256);
345
346 crate::valueset::scim_json_put_reflexive::<ValueSetCertificate>(&vs, &[])
348 }
349}