Skip to main content

kanidmd_lib/valueset/
oauth.rs

1use crate::valueset::ScimResolveStatus;
2use std::collections::{btree_map::Entry as BTreeEntry, BTreeMap, BTreeSet};
3
4use crate::{
5    be::dbvalue::{DbValueOauthClaimMap, DbValueOauthScopeMapV1},
6    prelude::*,
7    schema::SchemaAttribute,
8    value::{OauthClaimMapJoin, OAUTHSCOPE_RE, OAUTH_CLAIMNAME_RE},
9    valueset::{
10        uuid_to_proto_string, DbValueSetV2, ResolvedValueSetOauth2ClaimMap,
11        ResolvedValueSetOauth2ScopeMap, ScimValueIntermediate, UnresolvedScimValueOauth2ClaimMap,
12        UnresolvedScimValueOauth2ScopeMap, UnresolvedValueSetOauth2ClaimMap,
13        UnresolvedValueSetOauth2ScopeMap, ValueSet, ValueSetIntermediate, ValueSetResolveStatus,
14        ValueSetScimPut,
15    },
16};
17use kanidm_proto::scim_v1::{
18    client::{
19        ScimOAuth2ClaimMap as ClientScimOAuth2ClaimMap,
20        ScimOAuth2ScopeMap as ClientScimOAuth2ScopeMap,
21    },
22    JsonValue,
23};
24
25#[derive(Debug, Clone)]
26pub struct ValueSetOauthScope {
27    set: BTreeSet<String>,
28}
29
30impl ValueSetOauthScope {
31    pub fn new(s: String) -> Box<Self> {
32        let mut set = BTreeSet::new();
33        set.insert(s);
34        Box::new(ValueSetOauthScope { set })
35    }
36
37    pub fn push(&mut self, s: String) -> bool {
38        self.set.insert(s)
39    }
40
41    pub fn from_dbvs2(data: Vec<String>) -> Result<ValueSet, OperationError> {
42        let set = data.into_iter().collect();
43        Ok(Box::new(ValueSetOauthScope { set }))
44    }
45
46    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
47    // types, and String is foreign.
48    #[allow(clippy::should_implement_trait)]
49    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
50    where
51        T: IntoIterator<Item = String>,
52    {
53        let set = iter.into_iter().collect();
54        Some(Box::new(ValueSetOauthScope { set }))
55    }
56}
57
58impl ValueSetScimPut for ValueSetOauthScope {
59    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
60        let set: BTreeSet<String> = serde_json::from_value(value).map_err(|err| {
61            error!(?err, "SCIM Oauth2Scope syntax invalid");
62            OperationError::SC0019Oauth2ScopeSyntaxInvalid
63        })?;
64
65        Ok(ValueSetResolveStatus::Resolved(Box::new(
66            ValueSetOauthScope { set },
67        )))
68    }
69}
70
71impl ValueSetT for ValueSetOauthScope {
72    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
73        match value {
74            Value::OauthScope(s) => Ok(self.set.insert(s)),
75            _ => {
76                debug_assert!(false);
77                Err(OperationError::InvalidValueState)
78            }
79        }
80    }
81
82    fn clear(&mut self) {
83        self.set.clear();
84    }
85
86    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
87        match pv {
88            PartialValue::OauthScope(s) => {
89                self.set.remove(s.as_str());
90            }
91            _ => {
92                debug_assert!(false);
93            }
94        };
95        self.set.is_empty()
96    }
97
98    fn contains(&self, pv: &PartialValue) -> bool {
99        match pv {
100            PartialValue::OauthScope(s) => self.set.contains(s.as_str()),
101            _ => false,
102        }
103    }
104
105    fn substring(&self, _pv: &PartialValue) -> bool {
106        false
107    }
108
109    fn startswith(&self, _pv: &PartialValue) -> bool {
110        false
111    }
112
113    fn endswith(&self, _pv: &PartialValue) -> bool {
114        false
115    }
116
117    fn lessthan(&self, _pv: &PartialValue) -> bool {
118        false
119    }
120
121    fn len(&self) -> usize {
122        self.set.len()
123    }
124
125    fn generate_idx_eq_keys(&self) -> Vec<String> {
126        self.set.iter().cloned().collect()
127    }
128
129    fn syntax(&self) -> SyntaxType {
130        SyntaxType::OauthScope
131    }
132
133    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
134        self.set.iter().all(|s| OAUTHSCOPE_RE.is_match(s))
135    }
136
137    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
138        Box::new(self.set.iter().cloned())
139    }
140
141    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
142        Some(ScimResolveStatus::Resolved(ScimValueKanidm::ArrayString(
143            self.set.iter().cloned().collect(),
144        )))
145    }
146
147    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
148        DbValueSetV2::OauthScope(self.set.iter().cloned().collect())
149    }
150
151    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
152        Box::new(self.set.iter().cloned().map(PartialValue::OauthScope))
153    }
154
155    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
156        Box::new(self.set.iter().cloned().map(Value::OauthScope))
157    }
158
159    fn equal(&self, other: &ValueSet) -> bool {
160        if let Some(other) = other.as_oauthscope_set() {
161            &self.set == other
162        } else {
163            debug_assert!(false);
164            false
165        }
166    }
167
168    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
169        if let Some(b) = other.as_oauthscope_set() {
170            mergesets!(self.set, b)
171        } else {
172            debug_assert!(false);
173            Err(OperationError::InvalidValueState)
174        }
175    }
176
177    /*
178    fn to_oauthscope_single(&self) -> Option<&str> {
179        if self.set.len() == 1 {
180            self.set.iter().take(1).next().map(|s| s.as_str())
181        } else {
182            None
183        }
184    }
185    */
186
187    fn as_oauthscope_set(&self) -> Option<&BTreeSet<String>> {
188        Some(&self.set)
189    }
190
191    fn as_oauthscope_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
192        Some(Box::new(self.set.iter().map(|s| s.as_str())))
193    }
194}
195
196#[derive(Debug, Clone)]
197pub struct ValueSetOauthScopeMap {
198    map: BTreeMap<Uuid, BTreeSet<String>>,
199}
200
201impl ValueSetOauthScopeMap {
202    pub fn new(u: Uuid, m: BTreeSet<String>) -> Box<Self> {
203        let mut map = BTreeMap::new();
204        map.insert(u, m);
205        Box::new(ValueSetOauthScopeMap { map })
206    }
207
208    pub fn push(&mut self, u: Uuid, m: BTreeSet<String>) -> bool {
209        self.map.insert(u, m).is_none()
210    }
211
212    pub fn from_dbvs2(data: Vec<DbValueOauthScopeMapV1>) -> Result<ValueSet, OperationError> {
213        let map = data
214            .into_iter()
215            .map(|DbValueOauthScopeMapV1 { refer, data }| (refer, data.into_iter().collect()))
216            .collect();
217        Ok(Box::new(ValueSetOauthScopeMap { map }))
218    }
219
220    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
221    // types, and tuples are always foreign.
222    #[allow(clippy::should_implement_trait)]
223    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
224    where
225        T: IntoIterator<Item = (Uuid, BTreeSet<String>)>,
226    {
227        let map = iter.into_iter().collect();
228        Some(Box::new(ValueSetOauthScopeMap { map }))
229    }
230
231    pub(crate) fn from_set(resolved: Vec<ResolvedValueSetOauth2ScopeMap>) -> ValueSet {
232        let map = resolved
233            .into_iter()
234            .map(|ResolvedValueSetOauth2ScopeMap { group_uuid, scopes }| (group_uuid, scopes))
235            .collect();
236
237        Box::new(ValueSetOauthScopeMap { map })
238    }
239}
240
241impl ValueSetScimPut for ValueSetOauthScopeMap {
242    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
243        let scope_maps: Vec<ClientScimOAuth2ScopeMap> =
244            serde_json::from_value(value).map_err(|err| {
245                error!(?err, "SCIM Oauth2ScopeMap syntax invalid");
246                OperationError::SC0020Oauth2ScopeMapSyntaxInvalid
247            })?;
248
249        // We make these both the same len as claim maps as during the resolve
250        // process we move everything from unresolved to resolved, and worst
251        // case is everything is unresolved.
252        let mut resolved = Vec::with_capacity(scope_maps.len());
253        let mut unresolved = Vec::with_capacity(scope_maps.len());
254
255        for ClientScimOAuth2ScopeMap {
256            group,
257            group_uuid,
258            scopes,
259        } in scope_maps.into_iter()
260        {
261            match (group_uuid, group) {
262                (None, None) => {
263                    error!("SCIM Oauth2ScopeMap a group name or uuid must be present");
264                    return Err(OperationError::SC0021Oauth2ScopeMapMissingGroupIdentifier);
265                }
266                (Some(group_uuid), _) => {
267                    resolved.push(ResolvedValueSetOauth2ScopeMap { group_uuid, scopes })
268                }
269                (None, Some(group_name)) => {
270                    unresolved.push(UnresolvedValueSetOauth2ScopeMap { group_name, scopes })
271                }
272            }
273        }
274
275        Ok(ValueSetResolveStatus::NeedsResolution(
276            ValueSetIntermediate::Oauth2ScopeMap {
277                resolved,
278                unresolved,
279            },
280        ))
281    }
282}
283
284impl ValueSetT for ValueSetOauthScopeMap {
285    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
286        match value {
287            Value::OauthScopeMap(u, m) => {
288                match self.map.entry(u) {
289                    // We are going to assume that a vacant entry will not be set to empty.
290                    BTreeEntry::Vacant(e) => {
291                        e.insert(m);
292                        Ok(true)
293                    }
294                    // In the case that the value already exists, we update it. This is a quirk
295                    // of the oauth2 scope map type where add_ava assumes that a value's entire state
296                    // will be reflected, but we were only checking the *uuid* existed, not it's
297                    // associated map state. So by always replacing on a present, we are true to
298                    // the intent of the api.
299                    BTreeEntry::Occupied(mut e) => {
300                        if m.is_empty() {
301                            e.remove();
302                        } else {
303                            e.insert(m);
304                        }
305
306                        Ok(true)
307                    }
308                }
309            }
310            _ => Err(OperationError::InvalidValueState),
311        }
312    }
313
314    fn clear(&mut self) {
315        self.map.clear();
316    }
317
318    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
319        if let PartialValue::Refer(u) = pv {
320            self.map.remove(u);
321        };
322        self.map.is_empty()
323    }
324
325    fn contains(&self, pv: &PartialValue) -> bool {
326        match pv {
327            PartialValue::Refer(u) => self.map.contains_key(u),
328            _ => false,
329        }
330    }
331
332    fn substring(&self, _pv: &PartialValue) -> bool {
333        false
334    }
335
336    fn startswith(&self, _pv: &PartialValue) -> bool {
337        false
338    }
339
340    fn endswith(&self, _pv: &PartialValue) -> bool {
341        false
342    }
343
344    fn lessthan(&self, _pv: &PartialValue) -> bool {
345        false
346    }
347
348    fn len(&self) -> usize {
349        self.map.len()
350    }
351
352    fn generate_idx_eq_keys(&self) -> Vec<String> {
353        self.map
354            .keys()
355            .map(|u| u.as_hyphenated().to_string())
356            .collect()
357    }
358
359    fn syntax(&self) -> SyntaxType {
360        SyntaxType::OauthScopeMap
361    }
362
363    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
364        self.map
365            .values()
366            .flat_map(|set| set.iter())
367            .all(|s| OAUTHSCOPE_RE.is_match(s))
368    }
369
370    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
371        Box::new(
372            self.map
373                .iter()
374                .map(|(u, m)| format!("{}: {:?}", uuid_to_proto_string(*u), m)),
375        )
376    }
377
378    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
379        let unresolved_maps = self
380            .map
381            .iter()
382            .map(|(group_uuid, scopes)| UnresolvedScimValueOauth2ScopeMap {
383                group_uuid: *group_uuid,
384                scopes: scopes.clone(),
385            })
386            .collect::<Vec<_>>();
387
388        Some(ScimResolveStatus::NeedsResolution(
389            ScimValueIntermediate::Oauth2ScopeMap(unresolved_maps),
390        ))
391    }
392
393    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
394        DbValueSetV2::OauthScopeMap(
395            self.map
396                .iter()
397                .map(|(u, m)| DbValueOauthScopeMapV1 {
398                    refer: *u,
399                    data: m.iter().cloned().collect(),
400                })
401                .collect(),
402        )
403    }
404
405    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
406        Box::new(self.map.keys().cloned().map(PartialValue::Refer))
407    }
408
409    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
410        Box::new(
411            self.map
412                .iter()
413                .map(|(u, m)| Value::OauthScopeMap(*u, m.clone())),
414        )
415    }
416
417    fn equal(&self, other: &ValueSet) -> bool {
418        if let Some(other) = other.as_oauthscopemap() {
419            &self.map == other
420        } else {
421            debug_assert!(false);
422            false
423        }
424    }
425
426    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
427        if let Some(b) = other.as_oauthscopemap() {
428            mergemaps!(self.map, b)
429        } else {
430            debug_assert!(false);
431            Err(OperationError::InvalidValueState)
432        }
433    }
434
435    fn as_oauthscopemap(&self) -> Option<&BTreeMap<Uuid, BTreeSet<String>>> {
436        Some(&self.map)
437    }
438
439    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
440        // This is what ties us as a type that can be refint checked.
441        Some(Box::new(self.map.keys().copied()))
442    }
443}
444
445#[derive(Debug, Clone, PartialEq)]
446pub struct OauthClaimMapping {
447    join: OauthClaimMapJoin,
448    values: BTreeMap<Uuid, BTreeSet<String>>,
449}
450
451impl OauthClaimMapping {
452    pub(crate) fn join(&self) -> OauthClaimMapJoin {
453        self.join
454    }
455
456    pub(crate) fn values(&self) -> &BTreeMap<Uuid, BTreeSet<String>> {
457        &self.values
458    }
459}
460
461#[derive(Debug, Clone)]
462pub struct ValueSetOauthClaimMap {
463    //            Claim Name
464    map: BTreeMap<String, OauthClaimMapping>,
465}
466
467impl ValueSetOauthClaimMap {
468    pub(crate) fn new(claim: String, join: OauthClaimMapJoin) -> Box<Self> {
469        let mapping = OauthClaimMapping {
470            join,
471            values: BTreeMap::default(),
472        };
473        let mut map = BTreeMap::new();
474        map.insert(claim, mapping);
475        Box::new(ValueSetOauthClaimMap { map })
476    }
477
478    pub(crate) fn new_value(claim: String, group: Uuid, claims: BTreeSet<String>) -> Box<Self> {
479        let mut values = BTreeMap::default();
480        values.insert(group, claims);
481
482        let mapping = OauthClaimMapping {
483            join: OauthClaimMapJoin::default(),
484            values,
485        };
486
487        let mut map = BTreeMap::new();
488        map.insert(claim, mapping);
489        Box::new(ValueSetOauthClaimMap { map })
490    }
491
492    pub(crate) fn from_dbvs2(data: Vec<DbValueOauthClaimMap>) -> Result<ValueSet, OperationError> {
493        let map = data
494            .into_iter()
495            .map(|db_claim_map| match db_claim_map {
496                DbValueOauthClaimMap::V1 { name, join, values } => (
497                    name.clone(),
498                    OauthClaimMapping {
499                        join: join.into(),
500                        values: values.clone(),
501                    },
502                ),
503            })
504            .collect();
505        Ok(Box::new(ValueSetOauthClaimMap { map }))
506    }
507
508    pub(crate) fn from_set(resolved: Vec<ResolvedValueSetOauth2ClaimMap>) -> ValueSet {
509        let mut map = BTreeMap::new();
510
511        for ResolvedValueSetOauth2ClaimMap {
512            group_uuid,
513            claim,
514            join_char,
515            claim_values,
516        } in resolved.into_iter()
517        {
518            match map.entry(claim) {
519                BTreeEntry::Vacant(e) => {
520                    let mut values = BTreeMap::default();
521                    values.insert(group_uuid, claim_values);
522
523                    let claim_map = OauthClaimMapping {
524                        join: join_char,
525                        values,
526                    };
527                    e.insert(claim_map);
528                }
529                BTreeEntry::Occupied(mut e) => {
530                    // Just add the uuid/value, this claim name already exists.
531                    let mapping_mut = e.get_mut();
532                    match mapping_mut.values.entry(group_uuid) {
533                        BTreeEntry::Vacant(e) => {
534                            e.insert(claim_values);
535                        }
536                        BTreeEntry::Occupied(mut e) => {
537                            e.insert(claim_values);
538                        }
539                    }
540                }
541            }
542        }
543
544        Box::new(ValueSetOauthClaimMap { map })
545    }
546
547    fn trim(&mut self) {
548        self.map
549            .values_mut()
550            .for_each(|mapping_mut| mapping_mut.values.retain(|_k, v| !v.is_empty()));
551
552        self.map.retain(|_k, v| !v.values.is_empty());
553    }
554}
555
556impl ValueSetScimPut for ValueSetOauthClaimMap {
557    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
558        let claim_maps: Vec<ClientScimOAuth2ClaimMap> =
559            serde_json::from_value(value).map_err(|err| {
560                error!(?err, "SCIM Oauth2ClaimMap syntax invalid");
561                OperationError::SC0022Oauth2ClaimMapSyntaxInvalid
562            })?;
563
564        // We make these both the same len as claim maps as during the resolve
565        // process we move everything from unresolved to resolved, and worst
566        // case is everything is unresolved.
567        let mut resolved = Vec::with_capacity(claim_maps.len());
568        let mut unresolved = Vec::with_capacity(claim_maps.len());
569
570        for ClientScimOAuth2ClaimMap {
571            group,
572            group_uuid,
573            claim,
574            join_char,
575            values: claim_values,
576        } in claim_maps.into_iter()
577        {
578            let join_char = OauthClaimMapJoin::from(join_char);
579
580            match (group_uuid, group) {
581                (None, None) => {
582                    error!("SCIM Oauth2ClaimMap a group name or uuid must be present");
583                    return Err(OperationError::SC0023Oauth2ClaimMapMissingGroupIdentifier);
584                }
585                (Some(group_uuid), _) => resolved.push(ResolvedValueSetOauth2ClaimMap {
586                    group_uuid,
587                    claim,
588                    join_char,
589                    claim_values,
590                }),
591                (None, Some(group_name)) => unresolved.push(UnresolvedValueSetOauth2ClaimMap {
592                    group_name,
593                    claim,
594                    join_char,
595                    claim_values,
596                }),
597            }
598        }
599
600        Ok(ValueSetResolveStatus::NeedsResolution(
601            ValueSetIntermediate::Oauth2ClaimMap {
602                resolved,
603                unresolved,
604            },
605        ))
606    }
607}
608
609impl ValueSetT for ValueSetOauthClaimMap {
610    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
611        match value {
612            Value::OauthClaimValue(name, uuid, claims) => {
613                // Add a value to this group associated to this claim.
614                match self.map.entry(name) {
615                    BTreeEntry::Vacant(e) => {
616                        // New map/value. Use a default joiner.
617                        let mut values = BTreeMap::default();
618                        values.insert(uuid, claims);
619
620                        let claim_map = OauthClaimMapping {
621                            join: OauthClaimMapJoin::default(),
622                            values,
623                        };
624                        e.insert(claim_map);
625                        Ok(true)
626                    }
627                    BTreeEntry::Occupied(mut e) => {
628                        // Just add the uuid/value, this claim name already exists.
629                        let mapping_mut = e.get_mut();
630                        match mapping_mut.values.entry(uuid) {
631                            BTreeEntry::Vacant(e) => {
632                                e.insert(claims);
633                                Ok(true)
634                            }
635                            BTreeEntry::Occupied(mut e) => {
636                                e.insert(claims);
637                                Ok(true)
638                            }
639                        }
640                    }
641                }
642            }
643            Value::OauthClaimMap(name, join) => {
644                match self.map.entry(name) {
645                    BTreeEntry::Vacant(e) => {
646                        // Create a new empty claim mapping.
647                        let claim_map = OauthClaimMapping {
648                            join,
649                            values: BTreeMap::default(),
650                        };
651                        e.insert(claim_map);
652                        Ok(true)
653                    }
654                    BTreeEntry::Occupied(mut e) => {
655                        // Just update the join strategy.
656                        e.get_mut().join = join;
657                        Ok(true)
658                    }
659                }
660            }
661            _ => Err(OperationError::InvalidValueState),
662        }
663    }
664
665    fn clear(&mut self) {
666        self.map.clear();
667    }
668
669    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
670        match pv {
671            // Remove this claim as a whole
672            PartialValue::Iutf8(s) => {
673                self.map.remove(s);
674            }
675            // Remove all references to this group from this claim map.
676            PartialValue::Refer(u) => {
677                for mapping_mut in self.map.values_mut() {
678                    mapping_mut.values.remove(u);
679                }
680            }
681            PartialValue::OauthClaim(s, u) => {
682                // Remove a uuid from this claim type.
683                if let Some(mapping_mut) = self.map.get_mut(s) {
684                    mapping_mut.values.remove(u);
685                }
686            }
687            PartialValue::OauthClaimValue(s, u, v) => {
688                // Remove a value from this uuid, associated to this claim name.
689                if let Some(mapping_mut) = self.map.get_mut(s) {
690                    if let Some(claim_mut) = mapping_mut.values.get_mut(u) {
691                        claim_mut.remove(v);
692                    }
693                }
694            }
695            _ => {}
696        };
697
698        // Trim anything that is now empty.
699        self.trim();
700
701        self.map.is_empty()
702    }
703
704    fn contains(&self, pv: &PartialValue) -> bool {
705        match pv {
706            PartialValue::Iutf8(s) => self.map.contains_key(s),
707            PartialValue::Refer(u) => {
708                let mut contained = false;
709                for mapping in self.map.values() {
710                    contained |= mapping.values.contains_key(u);
711                }
712                contained
713            }
714            _ => false,
715        }
716    }
717
718    fn substring(&self, _pv: &PartialValue) -> bool {
719        false
720    }
721
722    fn startswith(&self, _pv: &PartialValue) -> bool {
723        false
724    }
725
726    fn endswith(&self, _pv: &PartialValue) -> bool {
727        false
728    }
729
730    fn lessthan(&self, _pv: &PartialValue) -> bool {
731        false
732    }
733
734    fn len(&self) -> usize {
735        self.map.len()
736    }
737
738    fn generate_idx_eq_keys(&self) -> Vec<String> {
739        self.map
740            .keys()
741            .cloned()
742            .chain(
743                self.map.values().flat_map(|mapping| {
744                    mapping.values.keys().map(|u| u.as_hyphenated().to_string())
745                }),
746            )
747            .collect()
748    }
749
750    fn syntax(&self) -> SyntaxType {
751        SyntaxType::OauthClaimMap
752    }
753
754    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
755        self.map.keys().all(|s| OAUTH_CLAIMNAME_RE.is_match(s))
756            && self
757                .map
758                .values()
759                .flat_map(|mapping| {
760                    mapping
761                        .values
762                        .values()
763                        .map(|claim_values| claim_values.is_empty())
764                })
765                .all(|is_empty| !is_empty)
766            && self
767                .map
768                .values()
769                .flat_map(|mapping| {
770                    mapping
771                        .values
772                        .values()
773                        .flat_map(|claim_values| claim_values.iter())
774                })
775                .all(|s| OAUTH_CLAIMNAME_RE.is_match(s))
776    }
777
778    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
779        Box::new(self.map.iter().flat_map(|(name, mapping)| {
780            mapping.values.iter().map(move |(group, claims)| {
781                let join_str = mapping.join.to_str();
782
783                let joined = str_concat!(claims, join_str);
784
785                format!(
786                    "{}: {} \"{:?}\"",
787                    name,
788                    uuid_to_proto_string(*group),
789                    joined
790                )
791            })
792        }))
793    }
794
795    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
796        let unresolved_maps = self
797            .map
798            .iter()
799            .flat_map(|(claim_name, mappings)| {
800                mappings.values.iter().map(|(group_uuid, claim_values)| {
801                    UnresolvedScimValueOauth2ClaimMap {
802                        group_uuid: *group_uuid,
803                        claim: claim_name.to_string(),
804                        join_char: mappings.join.into(),
805                        values: claim_values.clone(),
806                    }
807                })
808            })
809            .collect::<Vec<_>>();
810
811        Some(ScimResolveStatus::NeedsResolution(
812            ScimValueIntermediate::Oauth2ClaimMap(unresolved_maps),
813        ))
814    }
815
816    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
817        DbValueSetV2::OauthClaimMap(
818            self.map
819                .iter()
820                .map(|(name, mapping)| DbValueOauthClaimMap::V1 {
821                    name: name.clone(),
822                    join: mapping.join.into(),
823                    values: mapping.values.clone(),
824                })
825                .collect(),
826        )
827    }
828
829    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
830        Box::new(self.map.keys().cloned().map(PartialValue::Iutf8))
831    }
832
833    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
834        debug_assert!(false);
835        Box::new(
836            std::iter::empty(), /*
837                                self.map
838                                    .iter()
839                                    .map(|(u, m)| Value::OauthScopeMap(*u, m.clone())),
840                                */
841        )
842    }
843
844    fn equal(&self, other: &ValueSet) -> bool {
845        if let Some(other) = other.as_oauthclaim_map() {
846            &self.map == other
847        } else {
848            debug_assert!(false);
849            false
850        }
851    }
852
853    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
854        if let Some(b) = other.as_oauthclaim_map() {
855            mergemaps!(self.map, b)
856        } else {
857            debug_assert!(false);
858            Err(OperationError::InvalidValueState)
859        }
860    }
861
862    fn as_oauthclaim_map(&self) -> Option<&BTreeMap<String, OauthClaimMapping>> {
863        Some(&self.map)
864    }
865
866    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
867        // This is what ties us as a type that can be refint checked.
868        Some(Box::new(
869            self.map
870                .values()
871                .flat_map(|mapping| mapping.values.keys())
872                .copied(),
873        ))
874    }
875}
876
877#[cfg(test)]
878mod tests {
879    use super::{ValueSetOauthClaimMap, ValueSetOauthScope, ValueSetOauthScopeMap};
880    use crate::prelude::*;
881    use std::collections::BTreeSet;
882
883    #[test]
884    fn test_oauth_claim_invalid_str_concat_when_empty() {
885        let group_uuid = uuid::uuid!("5a6b8783-3f67-4ebb-b6aa-77fd6e66589f");
886        let vs =
887            ValueSetOauthClaimMap::new_value("claim".to_string(), group_uuid, BTreeSet::default());
888
889        // Invalid handling of an empty claim map would cause a crash.
890        let proto_value = vs.to_proto_string_clone_iter().next().unwrap();
891
892        assert_eq!(
893            &proto_value,
894            "claim: 5a6b8783-3f67-4ebb-b6aa-77fd6e66589f \"\"\"\""
895        );
896    }
897
898    #[test]
899    fn test_scim_oauth2_scope() {
900        let vs: ValueSet = ValueSetOauthScope::new("fully_sick_scope_m8".to_string());
901        let data = r#"["fully_sick_scope_m8"]"#;
902        crate::valueset::scim_json_reflexive(&vs, data);
903
904        // Test that we can parse json values into a valueset.
905        crate::valueset::scim_json_put_reflexive::<ValueSetOauthScope>(&vs, &[])
906    }
907
908    #[qs_test]
909    async fn test_scim_oauth2_scope_map(server: &QueryServer) {
910        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
911
912        let g_uuid = uuid::uuid!("4d21d04a-dc0e-42eb-b850-34dd180b107f");
913        assert!(write_txn
914            .internal_create(vec![entry_init!(
915                (Attribute::Class, EntryClass::Object.to_value()),
916                (Attribute::Class, EntryClass::Group.to_value()),
917                (Attribute::Name, Value::new_iname("testgroup")),
918                (Attribute::Uuid, Value::Uuid(g_uuid))
919            ),])
920            .is_ok());
921
922        let set = ["read".to_string(), "write".to_string()].into();
923        let vs: ValueSet = ValueSetOauthScopeMap::new(g_uuid, set);
924
925        let data = r#"
926[
927  {
928    "scopes": ["read", "write"],
929    "group": "testgroup@example.com",
930    "groupUuid": "4d21d04a-dc0e-42eb-b850-34dd180b107f"
931  }
932]
933        "#;
934        crate::valueset::scim_json_reflexive_unresolved(&mut write_txn, &vs, data);
935
936        // Test that we can parse json values into a valueset.
937        crate::valueset::scim_json_put_reflexive_unresolved::<ValueSetOauthScopeMap>(
938            &mut write_txn,
939            &vs,
940            &[],
941        );
942
943        assert!(write_txn.commit().is_ok());
944    }
945
946    #[qs_test]
947    async fn test_scim_oauth2_claim_map(server: &QueryServer) {
948        let mut write_txn = server.write(duration_from_epoch_now()).await.unwrap();
949
950        let g_uuid = uuid::uuid!("4d21d04a-dc0e-42eb-b850-34dd180b107f");
951        assert!(write_txn
952            .internal_create(vec![entry_init!(
953                (Attribute::Class, EntryClass::Object.to_value()),
954                (Attribute::Class, EntryClass::Group.to_value()),
955                (Attribute::Name, Value::new_iname("testgroup")),
956                (Attribute::Uuid, Value::Uuid(g_uuid))
957            ),])
958            .is_ok());
959
960        let set = ["read".to_string(), "write".to_string()].into();
961        let vs: ValueSet = ValueSetOauthClaimMap::new_value("claim".to_string(), g_uuid, set);
962
963        let data = r#"
964[
965  {
966    "claim": "claim",
967    "group": "testgroup@example.com",
968    "groupUuid": "4d21d04a-dc0e-42eb-b850-34dd180b107f",
969    "joinChar": ";",
970    "values": ["read", "write"]
971  }
972]
973        "#;
974        crate::valueset::scim_json_reflexive_unresolved(&mut write_txn, &vs, data);
975
976        // Test that we can parse json values into a valueset.
977        crate::valueset::scim_json_put_reflexive_unresolved::<ValueSetOauthClaimMap>(
978            &mut write_txn,
979            &vs,
980            &[],
981        );
982
983        assert!(write_txn.commit().is_ok());
984    }
985}