Skip to main content

kanidmd_lib/valueset/
iname.rs

1use crate::{
2    prelude::*,
3    schema::SchemaAttribute,
4    utils::trigraph_iter,
5    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
6};
7use kanidm_proto::scim_v1::{client::ScimStrings, JsonValue};
8use std::cmp::Ordering;
9
10use std::collections::BTreeSet;
11
12#[derive(Debug, Clone)]
13pub struct ValueSetIname {
14    value: String,
15}
16
17impl ValueSetIname {
18    #[allow(clippy::new_ret_no_self)]
19    pub fn new(s: &str) -> ValueSet {
20        Box::new(ValueSetIname {
21            value: s.to_lowercase(),
22        })
23    }
24
25    pub fn from_dbvs2(value: String) -> Result<ValueSet, OperationError> {
26        Ok(Box::new(ValueSetIname { value }))
27    }
28}
29
30impl ValueSetScimPut for ValueSetIname {
31    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
32        let value = serde_json::from_value::<String>(value).map_err(|err| {
33            error!(?err, "SCIM Iname Syntax Invalid");
34            OperationError::SC0016InameSyntaxInvalid
35        })?;
36
37        let value = value.to_lowercase();
38
39        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetIname {
40            value,
41        })))
42    }
43}
44
45impl ValueSetT for ValueSetIname {
46    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
47        match value {
48            Value::Iname(s) => {
49                if s != self.value {
50                    self.value = s;
51                    Ok(true)
52                } else {
53                    Ok(false)
54                }
55            }
56            _ => {
57                debug_assert!(false);
58                Err(OperationError::InvalidValueState)
59            }
60        }
61    }
62
63    fn clear(&mut self) {}
64
65    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
66        match pv {
67            PartialValue::Iname(s) => *s == self.value,
68            _ => {
69                debug_assert!(false);
70                false
71            }
72        }
73    }
74
75    fn contains(&self, pv: &PartialValue) -> bool {
76        match pv {
77            PartialValue::Iname(s) => *s == self.value,
78            _ => false,
79        }
80    }
81
82    fn substring(&self, pv: &PartialValue) -> bool {
83        match pv {
84            PartialValue::Iname(s2) => self.value.contains(s2),
85            _ => {
86                debug_assert!(false);
87                false
88            }
89        }
90    }
91
92    fn startswith(&self, pv: &PartialValue) -> bool {
93        match pv {
94            PartialValue::Iname(s2) => self.value.starts_with(s2),
95            _ => {
96                debug_assert!(false);
97                false
98            }
99        }
100    }
101
102    fn endswith(&self, pv: &PartialValue) -> bool {
103        match pv {
104            PartialValue::Iname(s2) => self.value.ends_with(s2),
105            _ => {
106                debug_assert!(false);
107                false
108            }
109        }
110    }
111
112    fn lessthan(&self, _pv: &PartialValue) -> bool {
113        false
114    }
115
116    fn len(&self) -> usize {
117        1
118    }
119
120    fn generate_idx_eq_keys(&self) -> Vec<String> {
121        std::iter::once(self.value.clone()).collect()
122    }
123
124    fn generate_idx_sub_keys(&self) -> Vec<String> {
125        debug_assert!(self.value == self.value.to_lowercase());
126
127        let mut trigraphs: Vec<_> = trigraph_iter(&self.value).collect();
128
129        trigraphs.sort_unstable();
130        trigraphs.dedup();
131
132        trigraphs.into_iter().map(String::from).collect()
133    }
134
135    fn syntax(&self) -> SyntaxType {
136        SyntaxType::Utf8StringIname
137    }
138
139    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
140        Value::validate_str_escapes(&self.value)
141            && Value::validate_singleline(&self.value)
142            && Value::validate_iname(&self.value)
143    }
144
145    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
146        Box::new(std::iter::once(self.value.clone()))
147    }
148
149    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
150        Some(self.value.clone().into())
151    }
152
153    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
154        DbValueSetV2::InameSingle(self.value.clone())
155    }
156
157    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
158        Box::new(std::iter::once(PartialValue::Iname(self.value.clone())))
159    }
160
161    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
162        Box::new(std::iter::once(Value::Iname(self.value.clone())))
163    }
164
165    fn equal(&self, other: &ValueSet) -> bool {
166        if let Some(other) = other.to_iname_single() {
167            self.value == other
168        } else {
169            debug_assert!(false);
170            false
171        }
172    }
173
174    fn cmp(&self, other: &ValueSet) -> Ordering {
175        if let Some(other) = other.to_iname_single() {
176            self.value.as_str().cmp(other)
177        } else {
178            debug_assert!(false);
179            Ordering::Equal
180        }
181    }
182
183    fn merge(&mut self, _other: &ValueSet) -> Result<(), OperationError> {
184        debug_assert!(false);
185        Err(OperationError::InvalidValueState)
186    }
187
188    fn to_iname_single(&self) -> Option<&str> {
189        Some(self.value.as_str())
190    }
191
192    /*
193    fn migrate_iutf8_iname(&self) -> Result<Option<ValueSet>, OperationError> {
194        Ok(None)
195    }
196    */
197}
198
199#[derive(Debug, Clone)]
200pub struct ValueSetInameN {
201    set: BTreeSet<String>,
202}
203
204impl ValueSetInameN {
205    pub fn new(s: &str) -> Box<Self> {
206        let mut set = BTreeSet::new();
207        set.insert(s.to_lowercase());
208        Box::new(ValueSetInameN { set })
209    }
210
211    pub fn push(&mut self, s: &str) -> bool {
212        self.set.insert(s.to_lowercase())
213    }
214
215    pub fn from_dbvs2(data: Vec<String>) -> Result<ValueSet, OperationError> {
216        let set = data.into_iter().collect();
217        Ok(Box::new(ValueSetInameN { set }))
218    }
219
220    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
221    // types, and str is foreign
222    #[allow(clippy::should_implement_trait)]
223    pub fn from_iter<'a, T>(iter: T) -> Option<Box<Self>>
224    where
225        T: IntoIterator<Item = &'a str>,
226    {
227        let set = iter.into_iter().map(str::to_string).collect();
228        Some(Box::new(ValueSetInameN { set }))
229    }
230}
231
232impl ValueSetScimPut for ValueSetInameN {
233    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
234        let ScimStrings(values) = serde_json::from_value(value).map_err(|err| {
235            error!(?err, "SCIM Iname Syntax Invalid");
236            OperationError::SC0016InameSyntaxInvalid
237        })?;
238
239        let set = values
240            .into_iter()
241            .map(|value| value.to_lowercase())
242            .collect();
243
244        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetInameN {
245            set,
246        })))
247    }
248}
249
250impl ValueSetT for ValueSetInameN {
251    fn migrate(&self) -> Result<Option<ValueSet>, OperationError> {
252        Ok(self.to_iname_single().map(|value| {
253            Box::new(ValueSetIname {
254                value: value.to_string(),
255            }) as ValueSet
256        }))
257    }
258
259    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
260        match value {
261            Value::InameN(s) => Ok(self.set.insert(s)),
262            _ => {
263                debug_assert!(false);
264                Err(OperationError::InvalidValueState)
265            }
266        }
267    }
268
269    fn clear(&mut self) {
270        self.set.clear();
271    }
272
273    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
274        match pv {
275            PartialValue::Iname(s) => {
276                self.set.remove(s);
277            }
278            _ => {
279                debug_assert!(false);
280            }
281        };
282        self.set.is_empty()
283    }
284
285    fn contains(&self, pv: &PartialValue) -> bool {
286        match pv {
287            PartialValue::Iname(s) => self.set.contains(s.as_str()),
288            _ => false,
289        }
290    }
291
292    fn substring(&self, pv: &PartialValue) -> bool {
293        match pv {
294            PartialValue::Iname(s2) => self.set.iter().any(|s1| s1.contains(s2)),
295            _ => {
296                debug_assert!(false);
297                false
298            }
299        }
300    }
301
302    fn startswith(&self, pv: &PartialValue) -> bool {
303        match pv {
304            PartialValue::Iname(s2) => self.set.iter().any(|s1| s1.starts_with(s2)),
305            _ => {
306                debug_assert!(false);
307                false
308            }
309        }
310    }
311
312    fn endswith(&self, pv: &PartialValue) -> bool {
313        match pv {
314            PartialValue::Iname(s2) => self.set.iter().any(|s1| s1.ends_with(s2)),
315            _ => {
316                debug_assert!(false);
317                false
318            }
319        }
320    }
321
322    fn lessthan(&self, _pv: &PartialValue) -> bool {
323        false
324    }
325
326    fn len(&self) -> usize {
327        self.set.len()
328    }
329
330    fn generate_idx_eq_keys(&self) -> Vec<String> {
331        self.set.iter().cloned().collect()
332    }
333
334    fn generate_idx_sub_keys(&self) -> Vec<String> {
335        let lower: Vec<_> = self.set.iter().map(|s| s.to_lowercase()).collect();
336        let mut trigraphs: Vec<_> = lower.iter().flat_map(|v| trigraph_iter(v)).collect();
337
338        trigraphs.sort_unstable();
339        trigraphs.dedup();
340
341        trigraphs.into_iter().map(String::from).collect()
342    }
343
344    fn syntax(&self) -> SyntaxType {
345        SyntaxType::Utf8StringInameN
346    }
347
348    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
349        self.set.iter().all(|s| {
350            Value::validate_str_escapes(s)
351                && Value::validate_singleline(s)
352                && Value::validate_iname(s.as_str())
353        })
354    }
355
356    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
357        Box::new(self.set.iter().cloned())
358    }
359
360    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
361        // In future we'll make this array only in the response.
362        /*
363        let arr = self.set.iter().cloned().collect::<Vec<_>>();
364        Some(arr.into())
365        */
366        let mut iter = self.set.iter().cloned();
367        if self.len() == 1 {
368            let v = iter.next().unwrap_or_default();
369            Some(v.into())
370        } else {
371            let arr = iter.collect::<Vec<_>>();
372            Some(arr.into())
373        }
374    }
375
376    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
377        DbValueSetV2::Iname(self.set.iter().cloned().collect())
378    }
379
380    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
381        Box::new(self.set.iter().map(|i| PartialValue::new_iname(i.as_str())))
382    }
383
384    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
385        Box::new(self.set.iter().cloned().map(Value::InameN))
386    }
387
388    fn equal(&self, other: &ValueSet) -> bool {
389        if let Some(other) = other.as_iname_set() {
390            &self.set == other
391        } else {
392            debug_assert!(false);
393            false
394        }
395    }
396
397    fn cmp(&self, other: &ValueSet) -> Ordering {
398        if let Some(other) = other.as_iname_set() {
399            self.set.cmp(other)
400        } else {
401            debug_assert!(false);
402            Ordering::Equal
403        }
404    }
405
406    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
407        if let Some(b) = other.as_iname_set() {
408            mergesets!(self.set, b)
409        } else {
410            debug_assert!(false);
411            Err(OperationError::InvalidValueState)
412        }
413    }
414
415    fn to_iname_single(&self) -> Option<&str> {
416        if self.set.len() == 1 {
417            self.set.iter().take(1).next().map(|s| s.as_str())
418        } else {
419            None
420        }
421    }
422
423    fn as_iname_set(&self) -> Option<&BTreeSet<String>> {
424        Some(&self.set)
425    }
426
427    fn as_iname_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
428        Some(Box::new(self.set.iter().map(|s| s.as_str())))
429    }
430
431    /*
432    fn migrate_iutf8_iname(&self) -> Result<Option<ValueSet>, OperationError> {
433        Ok(None)
434    }
435    */
436}
437
438#[cfg(test)]
439mod tests {
440    use super::{ValueSetIname, ValueSetInameN};
441    use crate::prelude::ValueSet;
442
443    #[test]
444    fn test_scim_iname_single() {
445        let vs: ValueSet = ValueSetIname::new("stevo");
446        crate::valueset::scim_json_reflexive(&vs, r#""stevo""#);
447
448        // Test that we can parse json values into a valueset.
449        crate::valueset::scim_json_put_reflexive::<ValueSetIname>(&vs, &[])
450    }
451
452    #[test]
453    fn test_scim_iname_multi() {
454        let vs: ValueSet = ValueSetInameN::from_iter(["stevo", "davo"]).unwrap();
455        crate::valueset::scim_json_reflexive(&vs, r#"["davo", "stevo"]"#);
456
457        // Test that we can parse json values into a valueset.
458        crate::valueset::scim_json_put_reflexive::<ValueSetInameN>(&vs, &[])
459    }
460}