Skip to main content

kanidmd_lib/valueset/
address.rs

1use crate::{
2    be::dbvalue::DbValueAddressV1,
3    prelude::*,
4    schema::SchemaAttribute,
5    utils::trigraph_iter,
6    value::{Address, VALIDATE_EMAIL_RE},
7    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
8};
9use kanidm_proto::scim_v1::{
10    client::ScimAddress as ScimAddressClient, server::ScimAddress, JsonValue, ScimMail,
11};
12use smolset::SmolSet;
13use std::collections::BTreeSet;
14
15#[derive(Debug, Clone)]
16pub struct ValueSetAddress {
17    set: SmolSet<[Address; 1]>,
18}
19
20impl ValueSetAddress {
21    pub fn new(b: Address) -> Box<Self> {
22        let mut set = SmolSet::new();
23        set.insert(b);
24        Box::new(ValueSetAddress { set })
25    }
26
27    pub fn push(&mut self, b: Address) -> bool {
28        self.set.insert(b)
29    }
30
31    pub fn from_dbvs2(data: Vec<DbValueAddressV1>) -> Result<ValueSet, OperationError> {
32        let set = data
33            .into_iter()
34            .map(
35                |DbValueAddressV1 {
36                     formatted,
37                     street_address,
38                     locality,
39                     region,
40                     postal_code,
41                     country,
42                 }| {
43                    Address {
44                        formatted,
45                        street_address,
46                        locality,
47                        region,
48                        postal_code,
49                        country,
50                    }
51                },
52            )
53            .collect();
54        Ok(Box::new(ValueSetAddress { set }))
55    }
56}
57
58impl ValueSetScimPut for ValueSetAddress {
59    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
60        let addresses: Vec<ScimAddressClient> = serde_json::from_value(value).map_err(|err| {
61            error!(?err, "SCIM Address syntax invalid");
62            OperationError::SC0011AddressSyntaxInvalid
63        })?;
64
65        let set = addresses
66            .into_iter()
67            .map(
68                |ScimAddressClient {
69                     street_address,
70                     locality,
71                     region,
72                     postal_code,
73                     country,
74                 }| {
75                    let formatted =
76                        format!("{street_address}, {locality}, {region}, {postal_code}, {country}");
77                    Address {
78                        formatted,
79                        street_address,
80                        locality,
81                        region,
82                        postal_code,
83                        country,
84                    }
85                },
86            )
87            .collect();
88
89        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetAddress {
90            set,
91        })))
92    }
93}
94
95impl FromIterator<Address> for Option<Box<ValueSetAddress>> {
96    fn from_iter<T>(iter: T) -> Option<Box<ValueSetAddress>>
97    where
98        T: IntoIterator<Item = Address>,
99    {
100        let set = iter.into_iter().collect();
101        Some(Box::new(ValueSetAddress { set }))
102    }
103}
104
105impl ValueSetT for ValueSetAddress {
106    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
107        match value {
108            Value::Address(u) => Ok(self.set.insert(u)),
109            _ => {
110                debug_assert!(false);
111                Err(OperationError::InvalidValueState)
112            }
113        }
114    }
115
116    fn clear(&mut self) {
117        self.set.clear();
118    }
119
120    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
121        match pv {
122            PartialValue::Address(_) => {
123                unreachable!()
124            }
125            _ => {
126                debug_assert!(false);
127            }
128        };
129        self.set.is_empty()
130    }
131
132    fn contains(&self, pv: &PartialValue) -> bool {
133        match pv {
134            PartialValue::Address(_) => {
135                unreachable!()
136            }
137            _ => false,
138        }
139    }
140
141    fn substring(&self, _pv: &PartialValue) -> bool {
142        false
143    }
144
145    fn startswith(&self, _pv: &PartialValue) -> bool {
146        false
147    }
148
149    fn endswith(&self, _pv: &PartialValue) -> bool {
150        false
151    }
152
153    fn lessthan(&self, _pv: &PartialValue) -> bool {
154        false
155    }
156
157    fn len(&self) -> usize {
158        self.set.len()
159    }
160
161    fn generate_idx_eq_keys(&self) -> Vec<String> {
162        unreachable!();
163        // self.set.iter().map(|b| b.to_string()).collect()
164    }
165
166    fn syntax(&self) -> SyntaxType {
167        unreachable!();
168    }
169
170    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
171        true
172    }
173
174    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
175        Box::new(self.set.iter().map(|a| a.formatted.clone()))
176    }
177
178    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
179        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
180            self.set
181                .iter()
182                .map(|a| ScimAddress {
183                    formatted: a.formatted.clone(),
184                    street_address: a.street_address.clone(),
185                    locality: a.locality.clone(),
186                    region: a.region.clone(),
187                    postal_code: a.postal_code.clone(),
188                    country: a.country.clone(),
189                })
190                .collect::<Vec<_>>(),
191        )))
192    }
193
194    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
195        DbValueSetV2::Address(
196            self.set
197                .iter()
198                .map(|a| DbValueAddressV1 {
199                    formatted: a.formatted.clone(),
200                    street_address: a.street_address.clone(),
201                    locality: a.locality.clone(),
202                    region: a.region.clone(),
203                    postal_code: a.postal_code.clone(),
204                    country: a.country.clone(),
205                })
206                .collect(),
207        )
208    }
209
210    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
211        Box::new(
212            self.set
213                .iter()
214                .map(|s| PartialValue::Address(s.formatted.clone())),
215        )
216    }
217
218    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
219        Box::new(self.set.iter().cloned().map(Value::Address))
220    }
221
222    fn equal(&self, other: &ValueSet) -> bool {
223        if let Some(other) = other.as_address_set() {
224            &self.set == other
225        } else {
226            debug_assert!(false);
227            false
228        }
229    }
230
231    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
232        if let Some(b) = other.as_address_set() {
233            mergesets!(self.set, b)
234        } else {
235            debug_assert!(false);
236            Err(OperationError::InvalidValueState)
237        }
238    }
239
240    /*
241    fn to_address_single(&self) -> Option<&Address> {
242        if self.set.len() == 1 {
243            self.set.iter().take(1).next()
244        } else {
245            None
246        }
247    }
248    */
249
250    fn as_address_set(&self) -> Option<&SmolSet<[Address; 1]>> {
251        Some(&self.set)
252    }
253}
254
255#[derive(Debug, Clone)]
256pub struct ValueSetEmailAddress {
257    primary: String,
258    set: BTreeSet<String>,
259}
260
261impl ValueSetEmailAddress {
262    pub fn new(primary: String) -> Box<Self> {
263        let mut set = BTreeSet::new();
264        set.insert(primary.clone());
265        Box::new(ValueSetEmailAddress { primary, set })
266    }
267
268    pub fn push(&mut self, a: String, primary: bool) -> bool {
269        if primary {
270            self.primary.clone_from(&a);
271        }
272        self.set.insert(a)
273    }
274
275    pub fn from_dbvs2(primary: String, data: Vec<String>) -> Result<ValueSet, OperationError> {
276        let set: BTreeSet<_> = data.into_iter().collect();
277
278        if set.contains(&primary) {
279            Ok(Box::new(ValueSetEmailAddress { primary, set }))
280        } else {
281            Err(OperationError::InvalidValueState)
282        }
283    }
284
285    pub fn from_repl_v1(primary: &str, data: &[String]) -> Result<ValueSet, OperationError> {
286        let set: BTreeSet<_> = data.iter().cloned().collect();
287
288        if set.contains(primary) {
289            Ok(Box::new(ValueSetEmailAddress {
290                primary: primary.to_string(),
291                set,
292            }))
293        } else {
294            Err(OperationError::InvalidValueState)
295        }
296    }
297
298    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
299    // types, and tuples are always foreign.
300    #[allow(clippy::should_implement_trait)]
301    pub fn from_iter<T>(iter: T) -> Option<Box<ValueSetEmailAddress>>
302    where
303        T: IntoIterator<Item = (String, bool)>,
304    {
305        let mut primary = None;
306        let set = iter
307            .into_iter()
308            .map(|(a, p)| {
309                if p {
310                    primary = Some(a.clone());
311                }
312                a
313            })
314            .collect();
315
316        if let Some(primary) = primary {
317            Some(Box::new(ValueSetEmailAddress { primary, set }))
318        } else {
319            set.iter()
320                .next()
321                .cloned()
322                .map(|primary| Box::new(ValueSetEmailAddress { primary, set }))
323        }
324    }
325}
326
327impl ValueSetScimPut for ValueSetEmailAddress {
328    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
329        let scim_mails: Vec<ScimMail> = serde_json::from_value(value).map_err(|err| {
330            error!(?err, "SCIM Mail Attribute Syntax Invalid");
331            OperationError::SC0003MailSyntaxInvalid
332        })?;
333
334        let mut primary = None;
335        let set: BTreeSet<_> = scim_mails
336            .into_iter()
337            .map(
338                |ScimMail {
339                     value,
340                     primary: is_primary,
341                 }| {
342                    if is_primary {
343                        primary = Some(value.clone());
344                    }
345                    value
346                },
347            )
348            .collect();
349
350        let primary = primary
351            .or_else(|| set.iter().next().cloned())
352            .ok_or_else(|| {
353                error!(
354                    "Mail attribute has no values that can be used as the primary mail address."
355                );
356                OperationError::SC0003MailSyntaxInvalid
357            })?;
358
359        Ok(ValueSetResolveStatus::Resolved(Box::new(
360            ValueSetEmailAddress { primary, set },
361        )))
362    }
363}
364
365impl ValueSetT for ValueSetEmailAddress {
366    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
367        match value {
368            Value::EmailAddress(a, p) => {
369                // if the set was empty, we need to force update primary.
370                if p || self.set.is_empty() {
371                    self.primary.clone_from(&a);
372                }
373                Ok(self.set.insert(a))
374            }
375            _ => {
376                debug_assert!(false);
377                Err(OperationError::InvalidValueState)
378            }
379        }
380    }
381
382    fn clear(&mut self) {
383        self.set.clear();
384    }
385
386    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
387        if let PartialValue::EmailAddress(a) = pv {
388            self.set.remove(a);
389            if &self.primary == a {
390                // if we can, inject another former address into primary.
391                if let Some(n) = self.set.iter().take(1).next().cloned() {
392                    self.primary = n
393                }
394            }
395        };
396        self.set.is_empty()
397    }
398
399    fn contains(&self, pv: &PartialValue) -> bool {
400        match pv {
401            PartialValue::EmailAddress(a) => self.set.contains(a),
402            _ => false,
403        }
404    }
405
406    fn substring(&self, pv: &PartialValue) -> bool {
407        match pv {
408            PartialValue::EmailAddress(s2) => {
409                // We lowercase as LDAP and similar expect case insensitive searches here.
410                let s2_lower = s2.to_lowercase();
411                self.set
412                    .iter()
413                    .any(|s1| s1.to_lowercase().contains(&s2_lower))
414            }
415            _ => {
416                debug_assert!(false);
417                false
418            }
419        }
420    }
421
422    fn startswith(&self, pv: &PartialValue) -> bool {
423        match pv {
424            PartialValue::EmailAddress(s2) => {
425                // We lowercase as LDAP and similar expect case insensitive searches here.
426                let s2_lower = s2.to_lowercase();
427                self.set
428                    .iter()
429                    .any(|s1| s1.to_lowercase().starts_with(&s2_lower))
430            }
431            _ => {
432                debug_assert!(false);
433                false
434            }
435        }
436    }
437
438    fn endswith(&self, pv: &PartialValue) -> bool {
439        match pv {
440            PartialValue::EmailAddress(s2) => {
441                // We lowercase as LDAP and similar expect case insensitive searches here.
442                let s2_lower = s2.to_lowercase();
443                self.set
444                    .iter()
445                    .any(|s1| s1.to_lowercase().ends_with(&s2_lower))
446            }
447            _ => {
448                debug_assert!(false);
449                false
450            }
451        }
452    }
453
454    fn lessthan(&self, _pv: &PartialValue) -> bool {
455        false
456    }
457
458    fn len(&self) -> usize {
459        self.set.len()
460    }
461
462    fn generate_idx_eq_keys(&self) -> Vec<String> {
463        self.set.iter().cloned().collect()
464    }
465
466    fn generate_idx_sub_keys(&self) -> Vec<String> {
467        let lower: Vec<_> = self.set.iter().map(|s| s.to_lowercase()).collect();
468        let mut trigraphs: Vec<_> = lower.iter().flat_map(|v| trigraph_iter(v)).collect();
469
470        trigraphs.sort_unstable();
471        trigraphs.dedup();
472
473        trigraphs.into_iter().map(String::from).collect()
474    }
475
476    fn syntax(&self) -> SyntaxType {
477        SyntaxType::EmailAddress
478    }
479
480    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
481        self.set.contains(&self.primary)
482            && self
483                .set
484                .iter()
485                .all(|mail| VALIDATE_EMAIL_RE.is_match(mail.as_str()))
486    }
487
488    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
489        if self.primary.is_empty() {
490            Box::new(self.set.iter().cloned())
491        } else {
492            Box::new(
493                std::iter::once(self.primary.clone()).chain(
494                    self.set
495                        .iter()
496                        .filter(|mail| **mail != self.primary)
497                        .cloned(),
498                ),
499            )
500        }
501    }
502
503    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
504        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
505            self.set
506                .iter()
507                .map(|mail| {
508                    let primary = **mail == self.primary;
509                    ScimMail {
510                        primary,
511                        value: mail.clone(),
512                    }
513                })
514                .collect::<Vec<_>>(),
515        )))
516    }
517
518    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
519        DbValueSetV2::EmailAddress(self.primary.clone(), self.set.iter().cloned().collect())
520    }
521
522    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
523        Box::new(self.set.iter().cloned().map(PartialValue::EmailAddress))
524    }
525
526    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
527        Box::new(self.set.iter().cloned().map(|a| {
528            let p = a == self.primary;
529            Value::EmailAddress(a, p)
530        }))
531    }
532
533    fn equal(&self, other: &ValueSet) -> bool {
534        if let Some((p_b, set_b)) = other.as_emailaddress_set() {
535            &self.set == set_b && &self.primary == p_b
536        } else {
537            debug_assert!(false);
538            false
539        }
540    }
541
542    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
543        if let Some((_p, set_b)) = other.as_emailaddress_set() {
544            mergesets!(self.set, set_b)
545        } else {
546            debug_assert!(false);
547            Err(OperationError::InvalidValueState)
548        }
549    }
550
551    fn as_emailaddress_set(&self) -> Option<(&String, &BTreeSet<String>)> {
552        if self.set.is_empty() {
553            None
554        } else {
555            Some((&self.primary, &self.set))
556        }
557    }
558
559    fn to_email_address_primary_str(&self) -> Option<&str> {
560        if self.set.is_empty() {
561            None
562        } else {
563            Some(self.primary.as_str())
564        }
565    }
566
567    fn as_email_str_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
568        Some(Box::new(self.set.iter().map(|s| s.as_str())))
569    }
570}
571
572/*
573#[derive(Debug, Clone)]
574pub struct ValueSetPhoneNumber {
575    primary: String,
576    set: BTreeSet<String>,
577}
578*/
579
580#[cfg(test)]
581mod tests {
582    use super::{ValueSetAddress, ValueSetEmailAddress};
583    use crate::{
584        repl::cid::Cid,
585        value::{Address, PartialValue, Value},
586        valueset::{self, ValueSet},
587    };
588
589    #[test]
590    fn test_valueset_emailaddress() {
591        // Can be created
592        //
593        let mut vs: ValueSet = ValueSetEmailAddress::new("claire@example.com".to_string());
594
595        assert_eq!(vs.len(), 1);
596        assert_eq!(
597            vs.to_email_address_primary_str(),
598            Some("claire@example.com")
599        );
600
601        // Add another, still not primary.
602        assert!(
603            vs.insert_checked(
604                Value::new_email_address_s("alice@example.com").expect("Invalid Email")
605            ) == Ok(true)
606        );
607
608        assert_eq!(vs.len(), 2);
609        assert_eq!(
610            vs.to_email_address_primary_str(),
611            Some("claire@example.com")
612        );
613
614        // Update primary
615        assert!(
616            vs.insert_checked(
617                Value::new_email_address_primary_s("primary@example.com").expect("Invalid Email")
618            ) == Ok(true)
619        );
620        assert_eq!(
621            vs.to_email_address_primary_str(),
622            Some("primary@example.com")
623        );
624
625        // Restore from dbv1, ensure correct primary
626        let vs2 = valueset::from_db_valueset_v2(vs.to_db_valueset_v2())
627            .expect("Failed to construct vs2 from dbvalue");
628
629        assert_eq!(&vs, &vs2);
630        assert_eq!(
631            vs.to_email_address_primary_str(),
632            vs2.to_email_address_primary_str()
633        );
634
635        // Remove primary, assert it's gone and that the "first" address is assigned.
636        assert!(!vs.remove(
637            &PartialValue::new_email_address_s("primary@example.com"),
638            &Cid::new_zero()
639        ));
640        assert_eq!(vs.len(), 2);
641        assert_eq!(vs.to_email_address_primary_str(), Some("alice@example.com"));
642
643        // Restore from dbv1, alice persisted.
644        let vs3 = valueset::from_db_valueset_v2(vs.to_db_valueset_v2())
645            .expect("Failed to construct vs2 from dbvalue");
646        assert_eq!(&vs, &vs3);
647        assert_eq!(vs3.len(), 2);
648        assert!(vs3
649            .as_emailaddress_set()
650            .map(|(_p, s)| s)
651            .unwrap()
652            .contains("alice@example.com"));
653        assert!(vs3
654            .as_emailaddress_set()
655            .map(|(_p, s)| s)
656            .unwrap()
657            .contains("claire@example.com"));
658
659        // If we clear, no primary.
660        vs.clear();
661        assert_eq!(vs.len(), 0);
662        assert!(vs.to_email_address_primary_str().is_none());
663    }
664
665    #[test]
666    fn test_scim_emailaddress() {
667        let mut vs: ValueSet = ValueSetEmailAddress::new("claire@example.com".to_string());
668        // Add another, still not primary.
669        assert!(
670            vs.insert_checked(
671                Value::new_email_address_s("alice@example.com").expect("Invalid Email")
672            ) == Ok(true)
673        );
674
675        let data = r#"[
676          {
677            "primary": false,
678            "value": "alice@example.com"
679          },
680          {
681            "primary": true,
682            "value": "claire@example.com"
683          }
684        ]"#;
685        crate::valueset::scim_json_reflexive(&vs, data);
686
687        // Test that we can parse json values into a valueset.
688        crate::valueset::scim_json_put_reflexive::<ValueSetEmailAddress>(&vs, &[])
689    }
690
691    #[test]
692    fn test_scim_address() {
693        let vs: ValueSet = ValueSetAddress::new(Address {
694            formatted: "1 No Where Lane, Doesn't Exist, Brisbane, 0420, Australia".to_string(),
695            street_address: "1 No Where Lane".to_string(),
696            locality: "Doesn't Exist".to_string(),
697            region: "Brisbane".to_string(),
698            postal_code: "0420".to_string(),
699            country: "Australia".to_string(),
700        });
701
702        let data = r#"[
703          {
704            "country": "Australia",
705            "formatted": "1 No Where Lane, Doesn't Exist, Brisbane, 0420, Australia",
706            "locality": "Doesn't Exist",
707            "postalCode": "0420",
708            "region": "Brisbane",
709            "streetAddress": "1 No Where Lane"
710          }
711        ]"#;
712
713        crate::valueset::scim_json_reflexive(&vs, data);
714
715        // Test that we can parse json values into a valueset.
716        crate::valueset::scim_json_put_reflexive::<ValueSetAddress>(&vs, &[])
717    }
718}