Skip to main content

kanidmd_lib/valueset/
url.rs

1use crate::{
2    prelude::*,
3    schema::SchemaAttribute,
4    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
5};
6use kanidm_proto::scim_v1::{client::ScimUrls, JsonValue};
7use std::collections::BTreeSet;
8
9#[derive(Debug, Clone)]
10pub struct ValueSetUrlN {
11    set: BTreeSet<Url>,
12}
13
14impl ValueSetUrlN {
15    pub fn new(b: Url) -> Box<Self> {
16        let mut set = BTreeSet::new();
17        set.insert(b);
18        Box::new(ValueSetUrlN { set })
19    }
20
21    pub fn push(&mut self, b: Url) -> bool {
22        self.set.insert(b)
23    }
24
25    pub fn from_dbvs2(data: Vec<Url>) -> Result<ValueSet, OperationError> {
26        let set = data.into_iter().collect();
27        Ok(Box::new(ValueSetUrlN { set }))
28    }
29
30    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
31    // types, and Url is foreign.
32    #[allow(clippy::should_implement_trait)]
33    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
34    where
35        T: IntoIterator<Item = Url>,
36    {
37        let set = iter.into_iter().collect();
38        Some(Box::new(ValueSetUrlN { set }))
39    }
40}
41
42impl ValueSetScimPut for ValueSetUrlN {
43    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
44        let ScimUrls(url_set) = serde_json::from_value(value).map_err(|err| {
45            error!(?err, "SCIM URL syntax invalid");
46            OperationError::SC0007UrlSyntaxInvalid
47        })?;
48
49        let set = BTreeSet::from_iter(url_set);
50
51        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetUrlN {
52            set,
53        })))
54    }
55}
56
57impl ValueSetT for ValueSetUrlN {
58    fn migrate(&self) -> Result<Option<ValueSet>, OperationError> {
59        Ok(self.to_url_single().map(|value| {
60            Box::new(ValueSetUrl {
61                value: value.clone(),
62            }) as ValueSet
63        }))
64    }
65
66    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
67        match value {
68            Value::UrlN(u) => Ok(self.set.insert(u)),
69            _ => {
70                debug_assert!(false);
71                Err(OperationError::InvalidValueState)
72            }
73        }
74    }
75
76    fn clear(&mut self) {
77        self.set.clear();
78    }
79
80    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
81        if let PartialValue::Url(u) = pv {
82            self.set.remove(u);
83        };
84        self.set.is_empty()
85    }
86
87    fn contains(&self, pv: &PartialValue) -> bool {
88        match pv {
89            PartialValue::Url(u) => self.set.contains(u),
90            _ => false,
91        }
92    }
93
94    fn substring(&self, _pv: &PartialValue) -> bool {
95        false
96    }
97
98    fn startswith(&self, _pv: &PartialValue) -> bool {
99        false
100    }
101
102    fn endswith(&self, _pv: &PartialValue) -> bool {
103        false
104    }
105
106    fn lessthan(&self, _pv: &PartialValue) -> bool {
107        false
108    }
109
110    fn len(&self) -> usize {
111        self.set.len()
112    }
113
114    fn generate_idx_eq_keys(&self) -> Vec<String> {
115        self.set.iter().map(|u| u.to_string()).collect()
116    }
117
118    fn syntax(&self) -> SyntaxType {
119        SyntaxType::UrlN
120    }
121
122    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
123        true
124    }
125
126    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
127        Box::new(self.set.iter().map(|i| i.to_string()))
128    }
129
130    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
131        let arr = self
132            .set
133            .iter()
134            .map(|url| url.to_string())
135            .collect::<Vec<_>>();
136        Some(arr.into())
137    }
138
139    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
140        DbValueSetV2::Url(self.set.iter().cloned().collect())
141    }
142
143    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
144        Box::new(self.set.iter().cloned().map(PartialValue::Url))
145    }
146
147    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
148        Box::new(self.set.iter().cloned().map(Value::UrlN))
149    }
150
151    fn equal(&self, other: &ValueSet) -> bool {
152        if let Some(other) = other.as_url_set() {
153            &self.set == other
154        } else {
155            debug_assert!(false);
156            false
157        }
158    }
159
160    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
161        if let Some(b) = other.as_url_set() {
162            mergesets!(self.set, b)
163        } else {
164            debug_assert!(false);
165            Err(OperationError::InvalidValueState)
166        }
167    }
168
169    fn to_url_single(&self) -> Option<&Url> {
170        if self.set.len() == 1 {
171            self.set.iter().take(1).next()
172        } else {
173            None
174        }
175    }
176
177    fn as_url_set(&self) -> Option<&BTreeSet<Url>> {
178        Some(&self.set)
179    }
180}
181
182#[derive(Debug, Clone)]
183pub struct ValueSetUrl {
184    value: Url,
185}
186
187impl ValueSetUrl {
188    pub fn new(value: Url) -> Box<Self> {
189        Box::new(ValueSetUrl { value })
190    }
191
192    pub fn from_dbvs2(value: Url) -> Result<ValueSet, OperationError> {
193        Ok(Box::new(ValueSetUrl { value }))
194    }
195}
196
197impl ValueSetScimPut for ValueSetUrl {
198    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
199        let value: Url = serde_json::from_value(value).map_err(|err| {
200            error!(?err, "SCIM URL syntax invalid");
201            OperationError::SC0007UrlSyntaxInvalid
202        })?;
203
204        Ok(ValueSetResolveStatus::Resolved(Box::new(ValueSetUrl {
205            value,
206        })))
207    }
208}
209
210impl ValueSetT for ValueSetUrl {
211    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
212        match value {
213            Value::Url(u) => {
214                if u != self.value {
215                    self.value = u;
216                    Ok(true)
217                } else {
218                    Ok(false)
219                }
220            }
221            _ => {
222                debug_assert!(false);
223                Err(OperationError::InvalidValueState)
224            }
225        }
226    }
227
228    fn clear(&mut self) {}
229
230    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
231        match pv {
232            PartialValue::Url(u) => self.value == *u,
233            _ => false,
234        }
235    }
236
237    fn contains(&self, pv: &PartialValue) -> bool {
238        match pv {
239            PartialValue::Url(u) => self.value == *u,
240            _ => false,
241        }
242    }
243
244    fn substring(&self, _pv: &PartialValue) -> bool {
245        false
246    }
247
248    fn startswith(&self, _pv: &PartialValue) -> bool {
249        false
250    }
251
252    fn endswith(&self, _pv: &PartialValue) -> bool {
253        false
254    }
255
256    fn lessthan(&self, _pv: &PartialValue) -> bool {
257        false
258    }
259
260    fn len(&self) -> usize {
261        1
262    }
263
264    fn generate_idx_eq_keys(&self) -> Vec<String> {
265        std::iter::once(self.value.to_string()).collect()
266    }
267
268    fn syntax(&self) -> SyntaxType {
269        SyntaxType::Url
270    }
271
272    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
273        true
274    }
275
276    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
277        Box::new(std::iter::once(self.value.to_string()))
278    }
279
280    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
281        Some(self.value.to_string().into())
282    }
283
284    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
285        DbValueSetV2::UrlSingle(self.value.clone())
286    }
287
288    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
289        Box::new(std::iter::once(self.value.clone()).map(PartialValue::Url))
290    }
291
292    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
293        Box::new(std::iter::once(self.value.clone()).map(Value::Url))
294    }
295
296    fn equal(&self, other: &ValueSet) -> bool {
297        if let Some(other) = other.to_url_single() {
298            self.value == *other
299        } else {
300            debug_assert!(false);
301            false
302        }
303    }
304
305    fn merge(&mut self, _other: &ValueSet) -> Result<(), OperationError> {
306        debug_assert!(false);
307        Err(OperationError::InvalidValueState)
308    }
309
310    fn to_url_single(&self) -> Option<&Url> {
311        Some(&self.value)
312    }
313}
314
315#[cfg(test)]
316mod tests {
317    use super::{ValueSetUrl, ValueSetUrlN};
318    use crate::prelude::{Url, ValueSet};
319
320    #[test]
321    fn test_scim_url_single() {
322        let u = Url::parse("https://idm.example.com").unwrap();
323        let vs: ValueSet = ValueSetUrl::new(u);
324        crate::valueset::scim_json_reflexive(&vs, r#""https://idm.example.com/""#);
325
326        // Test that we can parse json values into a valueset.
327        crate::valueset::scim_json_put_reflexive::<ValueSetUrl>(&vs, &[]);
328    }
329
330    #[test]
331    fn test_scim_url_multi() {
332        let u = Url::parse("https://idm.example.com").unwrap();
333        let vs: ValueSet = ValueSetUrlN::new(u);
334        crate::valueset::scim_json_reflexive(&vs, r#"["https://idm.example.com/"]"#);
335
336        // Test that we can parse json values into a valueset.
337        crate::valueset::scim_json_put_reflexive::<ValueSetUrlN>(&vs, &[]);
338
339        // Check multivalued arrays.
340        let u1 = Url::parse("https://idm1.example.com").unwrap();
341        let u2 = Url::parse("https://idm2.example.com").unwrap();
342        let vs: ValueSet = ValueSetUrlN::from_iter([u1, u2]).expect("Unable to create ValueSet");
343        crate::valueset::scim_json_reflexive(
344            &vs,
345            r#"["https://idm1.example.com/", "https://idm2.example.com/"]"#,
346        );
347        crate::valueset::scim_json_put_reflexive::<ValueSetUrlN>(&vs, &[]);
348    }
349}