Skip to main content

kanidmd_lib/valueset/
cred.rs

1use crate::{
2    be::dbvalue::{
3        DbValueAttestedPasskeyV1, DbValueCredV1, DbValueIntentTokenStateV1, DbValuePasskeyV1,
4    },
5    credential::Credential,
6    prelude::*,
7    schema::SchemaAttribute,
8    utils::trigraph_iter,
9    value::{CredUpdateSessionPerms, CredentialType, IntentTokenState},
10    valueset::{DbValueSetV2, ScimResolveStatus, ValueSet, ValueSetResolveStatus, ValueSetScimPut},
11};
12use kanidm_proto::scim_v1::{
13    server::{ScimIntentToken, ScimIntentTokenState},
14    JsonValue,
15};
16use smolset::SmolSet;
17use std::collections::{btree_map::Entry as BTreeEntry, BTreeMap};
18use time::OffsetDateTime;
19use webauthn_rs::prelude::{
20    AttestationCaList, AttestedPasskey as AttestedPasskeyV4, Passkey as PasskeyV4,
21};
22
23#[derive(Debug, Clone)]
24pub struct ValueSetCredential {
25    map: BTreeMap<String, Credential>,
26}
27
28impl ValueSetCredential {
29    pub fn new(t: String, c: Credential) -> Box<Self> {
30        let mut map = BTreeMap::new();
31        map.insert(t, c);
32        Box::new(ValueSetCredential { map })
33    }
34
35    pub fn push(&mut self, t: String, c: Credential) -> bool {
36        self.map.insert(t, c).is_none()
37    }
38
39    pub fn from_dbvs2(data: Vec<DbValueCredV1>) -> Result<ValueSet, OperationError> {
40        let map = data
41            .into_iter()
42            .map(|dc| {
43                let t = dc.tag.clone();
44                Credential::try_from(dc.data)
45                    .map_err(|()| OperationError::InvalidValueState)
46                    .map(|c| (t, c))
47            })
48            .collect::<Result<_, _>>()?;
49        Ok(Box::new(ValueSetCredential { map }))
50    }
51
52    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
53    // types, and tuples are always foreign.
54    #[allow(clippy::should_implement_trait)]
55    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
56    where
57        T: IntoIterator<Item = (String, Credential)>,
58    {
59        let map = iter.into_iter().collect();
60        Some(Box::new(ValueSetCredential { map }))
61    }
62}
63
64impl ValueSetT for ValueSetCredential {
65    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
66        match value {
67            Value::Cred(t, c) => {
68                if let BTreeEntry::Vacant(e) = self.map.entry(t) {
69                    e.insert(c);
70                    Ok(true)
71                } else {
72                    Ok(false)
73                }
74            }
75            _ => Err(OperationError::InvalidValueState),
76        }
77    }
78
79    fn clear(&mut self) {
80        self.map.clear();
81    }
82
83    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
84        if let PartialValue::Cred(t) = pv {
85            self.map.remove(t.as_str());
86        };
87        self.map.is_empty()
88    }
89
90    fn contains(&self, pv: &PartialValue) -> bool {
91        match pv {
92            PartialValue::Cred(t) => self.map.contains_key(t.as_str()),
93            _ => false,
94        }
95    }
96
97    fn substring(&self, _pv: &PartialValue) -> bool {
98        false
99    }
100
101    fn startswith(&self, _pv: &PartialValue) -> bool {
102        false
103    }
104
105    fn endswith(&self, _pv: &PartialValue) -> bool {
106        false
107    }
108
109    fn lessthan(&self, _pv: &PartialValue) -> bool {
110        false
111    }
112
113    fn len(&self) -> usize {
114        self.map.len()
115    }
116
117    fn generate_idx_eq_keys(&self) -> Vec<String> {
118        self.map.keys().cloned().collect()
119    }
120
121    fn generate_idx_sub_keys(&self) -> Vec<String> {
122        let lower: Vec<_> = self.map.keys().map(|s| s.to_lowercase()).collect();
123        let mut trigraphs: Vec<_> = lower.iter().flat_map(|v| trigraph_iter(v)).collect();
124
125        trigraphs.sort_unstable();
126        trigraphs.dedup();
127
128        trigraphs.into_iter().map(String::from).collect()
129    }
130
131    fn syntax(&self) -> SyntaxType {
132        SyntaxType::Credential
133    }
134
135    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
136        self.map
137            .iter()
138            .all(|(s, _)| Value::validate_str_escapes(s) && Value::validate_singleline(s))
139    }
140
141    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
142        Box::new(self.map.keys().cloned())
143    }
144
145    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
146        // Currently I think we don't need to yield cred info as that's part of the
147        // cred update session instead.
148        None
149    }
150
151    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
152        DbValueSetV2::Credential(
153            self.map
154                .iter()
155                .map(|(tag, cred)| DbValueCredV1 {
156                    tag: tag.clone(),
157                    data: cred.to_db_valuev1(),
158                })
159                .collect(),
160        )
161    }
162
163    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
164        Box::new(self.map.keys().cloned().map(PartialValue::Cred))
165    }
166
167    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
168        Box::new(
169            self.map
170                .iter()
171                .map(|(t, c)| Value::Cred(t.clone(), c.clone())),
172        )
173    }
174
175    fn equal(&self, other: &ValueSet) -> bool {
176        // Looks like we may not need this?
177        if let Some(other) = other.as_credential_map() {
178            &self.map == other
179        } else {
180            // debug_assert!(false);
181            false
182        }
183    }
184
185    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
186        if let Some(b) = other.as_credential_map() {
187            mergemaps!(self.map, b)
188        } else {
189            debug_assert!(false);
190            Err(OperationError::InvalidValueState)
191        }
192    }
193
194    fn to_credential_single(&self) -> Option<&Credential> {
195        if self.map.len() == 1 {
196            self.map.values().take(1).next()
197        } else {
198            None
199        }
200    }
201
202    fn as_credential_map(&self) -> Option<&BTreeMap<String, Credential>> {
203        Some(&self.map)
204    }
205}
206
207#[derive(Debug, Clone)]
208pub struct ValueSetIntentToken {
209    map: BTreeMap<String, IntentTokenState>,
210}
211
212impl ValueSetIntentToken {
213    pub fn new(t: String, s: IntentTokenState) -> Box<Self> {
214        let mut map = BTreeMap::new();
215        map.insert(t, s);
216        Box::new(ValueSetIntentToken { map })
217    }
218
219    pub fn push(&mut self, t: String, s: IntentTokenState) -> bool {
220        self.map.insert(t, s).is_none()
221    }
222
223    pub fn from_dbvs2(
224        data: Vec<(String, DbValueIntentTokenStateV1)>,
225    ) -> Result<ValueSet, OperationError> {
226        let map = data
227            .into_iter()
228            .map(|(s, dits)| {
229                let ts = match dits {
230                    DbValueIntentTokenStateV1::Valid {
231                        max_ttl,
232                        ext_cred_portal_can_view,
233                        primary_can_edit,
234                        passkeys_can_edit,
235                        attested_passkeys_can_edit,
236                        unixcred_can_edit,
237                        sshpubkey_can_edit,
238                    } => IntentTokenState::Valid {
239                        max_ttl,
240                        perms: CredUpdateSessionPerms {
241                            ext_cred_portal_can_view,
242                            primary_can_edit,
243                            passkeys_can_edit,
244                            attested_passkeys_can_edit,
245                            unixcred_can_edit,
246                            sshpubkey_can_edit,
247                        },
248                    },
249                    DbValueIntentTokenStateV1::InProgress {
250                        max_ttl,
251                        session_id,
252                        session_ttl,
253                        ext_cred_portal_can_view,
254                        primary_can_edit,
255                        passkeys_can_edit,
256                        attested_passkeys_can_edit,
257                        unixcred_can_edit,
258                        sshpubkey_can_edit,
259                    } => IntentTokenState::InProgress {
260                        max_ttl,
261                        session_id,
262                        session_ttl,
263                        perms: CredUpdateSessionPerms {
264                            ext_cred_portal_can_view,
265                            primary_can_edit,
266                            passkeys_can_edit,
267                            attested_passkeys_can_edit,
268                            unixcred_can_edit,
269                            sshpubkey_can_edit,
270                        },
271                    },
272                    DbValueIntentTokenStateV1::Consumed { max_ttl } => {
273                        IntentTokenState::Consumed { max_ttl }
274                    }
275                };
276                (s, ts)
277            })
278            .collect();
279        Ok(Box::new(ValueSetIntentToken { map }))
280    }
281
282    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
283    // types, and tuples are always foreign.
284    #[allow(clippy::should_implement_trait)]
285    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
286    where
287        T: IntoIterator<Item = (String, IntentTokenState)>,
288    {
289        let map = iter.into_iter().collect();
290        Some(Box::new(ValueSetIntentToken { map }))
291    }
292}
293
294impl ValueSetT for ValueSetIntentToken {
295    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
296        match value {
297            Value::IntentToken(u, s) => {
298                if let BTreeEntry::Vacant(e) = self.map.entry(u) {
299                    e.insert(s);
300                    Ok(true)
301                } else {
302                    Ok(false)
303                }
304            }
305            _ => Err(OperationError::InvalidValueState),
306        }
307    }
308
309    fn clear(&mut self) {
310        self.map.clear();
311    }
312
313    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
314        if let PartialValue::IntentToken(u) = pv {
315            self.map.remove(u);
316        };
317        self.map.is_empty()
318    }
319
320    fn purge(&mut self, _cid: &Cid) -> bool {
321        // Could consider making this a TS capable entry.
322        true
323    }
324
325    fn contains(&self, pv: &PartialValue) -> bool {
326        match pv {
327            PartialValue::IntentToken(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.keys().cloned().collect()
354    }
355
356    fn syntax(&self) -> SyntaxType {
357        SyntaxType::IntentToken
358    }
359
360    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
361        self.map
362            .iter()
363            .all(|(s, _)| Value::validate_str_escapes(s) && Value::validate_singleline(s))
364    }
365
366    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
367        Box::new(self.map.keys().cloned())
368    }
369
370    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
371        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
372            self.map
373                .iter()
374                .map(|(token_id, intent_token_state)| {
375                    let (state, max_ttl) = match intent_token_state {
376                        IntentTokenState::Valid { max_ttl, .. } => {
377                            (ScimIntentTokenState::Valid, *max_ttl)
378                        }
379                        IntentTokenState::InProgress { max_ttl, .. } => {
380                            (ScimIntentTokenState::InProgress, *max_ttl)
381                        }
382                        IntentTokenState::Consumed { max_ttl } => {
383                            (ScimIntentTokenState::Consumed, *max_ttl)
384                        }
385                    };
386
387                    let odt: OffsetDateTime = OffsetDateTime::UNIX_EPOCH + max_ttl;
388
389                    ScimIntentToken {
390                        token_id: token_id.clone(),
391                        state,
392                        expires: odt,
393                    }
394                })
395                .collect::<Vec<_>>(),
396        )))
397    }
398
399    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
400        DbValueSetV2::IntentToken(
401            self.map
402                .iter()
403                .map(|(u, s)| {
404                    (
405                        u.clone(),
406                        match s {
407                            IntentTokenState::Valid {
408                                max_ttl,
409                                perms:
410                                    CredUpdateSessionPerms {
411                                        ext_cred_portal_can_view,
412                                        primary_can_edit,
413                                        passkeys_can_edit,
414                                        attested_passkeys_can_edit,
415                                        unixcred_can_edit,
416                                        sshpubkey_can_edit,
417                                    },
418                            } => DbValueIntentTokenStateV1::Valid {
419                                max_ttl: *max_ttl,
420                                ext_cred_portal_can_view: *ext_cred_portal_can_view,
421                                primary_can_edit: *primary_can_edit,
422                                passkeys_can_edit: *passkeys_can_edit,
423                                attested_passkeys_can_edit: *attested_passkeys_can_edit,
424                                unixcred_can_edit: *unixcred_can_edit,
425                                sshpubkey_can_edit: *sshpubkey_can_edit,
426                            },
427                            IntentTokenState::InProgress {
428                                max_ttl,
429                                session_id,
430                                session_ttl,
431                                perms:
432                                    CredUpdateSessionPerms {
433                                        ext_cred_portal_can_view,
434                                        primary_can_edit,
435                                        passkeys_can_edit,
436                                        attested_passkeys_can_edit,
437                                        unixcred_can_edit,
438                                        sshpubkey_can_edit,
439                                    },
440                            } => DbValueIntentTokenStateV1::InProgress {
441                                max_ttl: *max_ttl,
442                                session_id: *session_id,
443                                session_ttl: *session_ttl,
444                                ext_cred_portal_can_view: *ext_cred_portal_can_view,
445                                primary_can_edit: *primary_can_edit,
446                                passkeys_can_edit: *passkeys_can_edit,
447                                attested_passkeys_can_edit: *attested_passkeys_can_edit,
448                                unixcred_can_edit: *unixcred_can_edit,
449                                sshpubkey_can_edit: *sshpubkey_can_edit,
450                            },
451                            IntentTokenState::Consumed { max_ttl } => {
452                                DbValueIntentTokenStateV1::Consumed { max_ttl: *max_ttl }
453                            }
454                        },
455                    )
456                })
457                .collect(),
458        )
459    }
460
461    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
462        Box::new(self.map.keys().cloned().map(PartialValue::IntentToken))
463    }
464
465    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
466        Box::new(
467            self.map
468                .iter()
469                .map(|(u, s)| Value::IntentToken(u.clone(), s.clone())),
470        )
471    }
472
473    fn equal(&self, other: &ValueSet) -> bool {
474        if let Some(other) = other.as_intenttoken_map() {
475            &self.map == other
476        } else {
477            debug_assert!(false);
478            false
479        }
480    }
481
482    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
483        if let Some(b) = other.as_intenttoken_map() {
484            mergemaps!(self.map, b)
485        } else {
486            debug_assert!(false);
487            Err(OperationError::InvalidValueState)
488        }
489    }
490
491    fn repl_merge_valueset(&self, _older: &ValueSet, _trim_cid: &Cid) -> Option<ValueSet> {
492        // Im not sure this actually needs repl handling ...
493        None
494    }
495
496    fn as_intenttoken_map(&self) -> Option<&BTreeMap<String, IntentTokenState>> {
497        Some(&self.map)
498    }
499}
500
501#[derive(Debug, Clone)]
502pub struct ValueSetPasskey {
503    map: BTreeMap<Uuid, (String, PasskeyV4)>,
504}
505
506impl ValueSetPasskey {
507    pub fn new(u: Uuid, t: String, k: PasskeyV4) -> Box<Self> {
508        let mut map = BTreeMap::new();
509        map.insert(u, (t, k));
510        Box::new(ValueSetPasskey { map })
511    }
512
513    pub fn push(&mut self, u: Uuid, t: String, k: PasskeyV4) -> bool {
514        self.map.insert(u, (t, k)).is_none()
515    }
516
517    pub fn from_dbvs2(data: Vec<DbValuePasskeyV1>) -> Result<ValueSet, OperationError> {
518        let map = data
519            .into_iter()
520            .map(|k| match k {
521                DbValuePasskeyV1::V4 { u, t, k } => Ok((u, (t, k))),
522            })
523            .collect::<Result<_, _>>()?;
524        Ok(Box::new(ValueSetPasskey { map }))
525    }
526
527    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
528    // types, and tuples are always foreign.
529    #[allow(clippy::should_implement_trait)]
530    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
531    where
532        T: IntoIterator<Item = (Uuid, String, PasskeyV4)>,
533    {
534        let map = iter.into_iter().map(|(u, t, k)| (u, (t, k))).collect();
535        Some(Box::new(ValueSetPasskey { map }))
536    }
537}
538
539impl ValueSetT for ValueSetPasskey {
540    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
541        match value {
542            Value::Passkey(u, t, k) => {
543                if let BTreeEntry::Vacant(e) = self.map.entry(u) {
544                    e.insert((t, k));
545                    Ok(true)
546                } else {
547                    Ok(false)
548                }
549            }
550            _ => Err(OperationError::InvalidValueState),
551        }
552    }
553
554    fn clear(&mut self) {
555        self.map.clear();
556    }
557
558    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
559        if let PartialValue::Passkey(u) = pv {
560            self.map.remove(u);
561        };
562        self.map.is_empty()
563    }
564
565    fn contains(&self, pv: &PartialValue) -> bool {
566        match pv {
567            PartialValue::Passkey(u) => self.map.contains_key(u),
568            _ => false,
569        }
570    }
571
572    fn substring(&self, _pv: &PartialValue) -> bool {
573        false
574    }
575
576    fn startswith(&self, _pv: &PartialValue) -> bool {
577        false
578    }
579
580    fn endswith(&self, _pv: &PartialValue) -> bool {
581        false
582    }
583
584    fn lessthan(&self, _pv: &PartialValue) -> bool {
585        false
586    }
587
588    fn len(&self) -> usize {
589        self.map.len()
590    }
591
592    fn generate_idx_eq_keys(&self) -> Vec<String> {
593        self.map
594            .keys()
595            .map(|u| u.as_hyphenated().to_string())
596            .collect()
597    }
598
599    fn syntax(&self) -> SyntaxType {
600        SyntaxType::Passkey
601    }
602
603    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
604        self.map
605            .iter()
606            .all(|(_, (s, _))| Value::validate_str_escapes(s) && Value::validate_singleline(s))
607    }
608
609    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
610        Box::new(self.map.values().map(|(t, _)| t).cloned())
611    }
612
613    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
614        None
615    }
616
617    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
618        DbValueSetV2::Passkey(
619            self.map
620                .iter()
621                .map(|(u, (t, k))| DbValuePasskeyV1::V4 {
622                    u: *u,
623                    t: t.clone(),
624                    k: k.clone(),
625                })
626                .collect(),
627        )
628    }
629
630    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
631        Box::new(self.map.keys().cloned().map(PartialValue::Passkey))
632    }
633
634    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
635        Box::new(
636            self.map
637                .iter()
638                .map(|(u, (t, k))| Value::Passkey(*u, t.clone(), k.clone())),
639        )
640    }
641
642    fn equal(&self, other: &ValueSet) -> bool {
643        // Looks like we may not need this?
644        if let Some(other) = other.as_passkey_map() {
645            &self.map == other
646        } else {
647            // debug_assert!(false);
648            false
649        }
650    }
651
652    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
653        if let Some(b) = other.as_passkey_map() {
654            mergemaps!(self.map, b)
655        } else {
656            debug_assert!(false);
657            Err(OperationError::InvalidValueState)
658        }
659    }
660
661    fn to_passkey_single(&self) -> Option<&PasskeyV4> {
662        if self.map.len() == 1 {
663            self.map.values().take(1).next().map(|(_, k)| k)
664        } else {
665            None
666        }
667    }
668
669    fn as_passkey_map(&self) -> Option<&BTreeMap<Uuid, (String, PasskeyV4)>> {
670        Some(&self.map)
671    }
672}
673
674#[derive(Debug, Clone)]
675pub struct ValueSetAttestedPasskey {
676    map: BTreeMap<Uuid, (String, AttestedPasskeyV4)>,
677}
678
679impl ValueSetAttestedPasskey {
680    pub fn new(u: Uuid, t: String, k: AttestedPasskeyV4) -> Box<Self> {
681        let mut map = BTreeMap::new();
682        map.insert(u, (t, k));
683        Box::new(ValueSetAttestedPasskey { map })
684    }
685
686    pub fn push(&mut self, u: Uuid, t: String, k: AttestedPasskeyV4) -> bool {
687        self.map.insert(u, (t, k)).is_none()
688    }
689
690    pub fn from_dbvs2(data: Vec<DbValueAttestedPasskeyV1>) -> Result<ValueSet, OperationError> {
691        let map = data
692            .into_iter()
693            .map(|k| match k {
694                DbValueAttestedPasskeyV1::V4 { u, t, k } => Ok((u, (t, k))),
695            })
696            .collect::<Result<_, _>>()?;
697        Ok(Box::new(ValueSetAttestedPasskey { map }))
698    }
699
700    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
701    // types, and tuples are always foreign.
702    #[allow(clippy::should_implement_trait)]
703    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
704    where
705        T: IntoIterator<Item = (Uuid, String, AttestedPasskeyV4)>,
706    {
707        let map = iter.into_iter().map(|(u, t, k)| (u, (t, k))).collect();
708        Some(Box::new(ValueSetAttestedPasskey { map }))
709    }
710}
711
712impl ValueSetT for ValueSetAttestedPasskey {
713    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
714        match value {
715            Value::AttestedPasskey(u, t, k) => {
716                if let BTreeEntry::Vacant(e) = self.map.entry(u) {
717                    e.insert((t, k));
718                    Ok(true)
719                } else {
720                    Ok(false)
721                }
722            }
723            _ => Err(OperationError::InvalidValueState),
724        }
725    }
726
727    fn clear(&mut self) {
728        self.map.clear();
729    }
730
731    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
732        if let PartialValue::AttestedPasskey(u) = pv {
733            self.map.remove(u);
734        };
735        self.map.is_empty()
736    }
737
738    fn contains(&self, pv: &PartialValue) -> bool {
739        match pv {
740            PartialValue::AttestedPasskey(u) => self.map.contains_key(u),
741            _ => false,
742        }
743    }
744
745    fn substring(&self, _pv: &PartialValue) -> bool {
746        false
747    }
748
749    fn startswith(&self, _pv: &PartialValue) -> bool {
750        false
751    }
752
753    fn endswith(&self, _pv: &PartialValue) -> bool {
754        false
755    }
756
757    fn lessthan(&self, _pv: &PartialValue) -> bool {
758        false
759    }
760
761    fn len(&self) -> usize {
762        self.map.len()
763    }
764
765    fn generate_idx_eq_keys(&self) -> Vec<String> {
766        self.map
767            .keys()
768            .map(|u| u.as_hyphenated().to_string())
769            .collect()
770    }
771
772    fn syntax(&self) -> SyntaxType {
773        SyntaxType::AttestedPasskey
774    }
775
776    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
777        self.map
778            .iter()
779            .all(|(_, (s, _))| Value::validate_str_escapes(s) && Value::validate_singleline(s))
780    }
781
782    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
783        Box::new(self.map.values().map(|(t, _)| t).cloned())
784    }
785
786    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
787        None
788    }
789
790    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
791        DbValueSetV2::AttestedPasskey(
792            self.map
793                .iter()
794                .map(|(u, (t, k))| DbValueAttestedPasskeyV1::V4 {
795                    u: *u,
796                    t: t.clone(),
797                    k: k.clone(),
798                })
799                .collect(),
800        )
801    }
802
803    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
804        Box::new(self.map.keys().copied().map(PartialValue::AttestedPasskey))
805    }
806
807    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
808        Box::new(
809            self.map
810                .iter()
811                .map(|(u, (t, k))| Value::AttestedPasskey(*u, t.clone(), k.clone())),
812        )
813    }
814
815    fn equal(&self, other: &ValueSet) -> bool {
816        // Looks like we may not need this?
817        if let Some(other) = other.as_attestedpasskey_map() {
818            &self.map == other
819        } else {
820            // debug_assert!(false);
821            false
822        }
823    }
824
825    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
826        if let Some(b) = other.as_attestedpasskey_map() {
827            mergemaps!(self.map, b)
828        } else {
829            debug_assert!(false);
830            Err(OperationError::InvalidValueState)
831        }
832    }
833
834    /*
835    fn to_attestedpasskey_single(&self) -> Option<&AttestedPasskeyV4> {
836        if self.map.len() == 1 {
837            self.map.values().take(1).next().map(|(_, k)| k)
838        } else {
839            None
840        }
841    }
842    */
843
844    fn as_attestedpasskey_map(&self) -> Option<&BTreeMap<Uuid, (String, AttestedPasskeyV4)>> {
845        Some(&self.map)
846    }
847}
848
849#[derive(Debug, Clone)]
850pub struct ValueSetCredentialType {
851    set: SmolSet<[CredentialType; 1]>,
852}
853
854impl ValueSetCredentialType {
855    pub fn new(u: CredentialType) -> Box<Self> {
856        let mut set = SmolSet::new();
857        set.insert(u);
858        Box::new(ValueSetCredentialType { set })
859    }
860
861    pub fn push(&mut self, u: CredentialType) -> bool {
862        self.set.insert(u)
863    }
864
865    pub fn from_dbvs2(data: Vec<u16>) -> Result<ValueSet, OperationError> {
866        let set: Result<_, _> = data.into_iter().map(CredentialType::try_from).collect();
867        let set = set.map_err(|_| OperationError::InvalidValueState)?;
868        Ok(Box::new(ValueSetCredentialType { set }))
869    }
870
871    // We need to allow this, because rust doesn't allow us to impl FromIterator on foreign
872    // types, and uuid is foreign.
873    #[allow(clippy::should_implement_trait)]
874    pub fn from_iter<T>(iter: T) -> Option<Box<Self>>
875    where
876        T: IntoIterator<Item = CredentialType>,
877    {
878        let set = iter.into_iter().collect();
879        Some(Box::new(ValueSetCredentialType { set }))
880    }
881}
882
883impl ValueSetScimPut for ValueSetCredentialType {
884    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError> {
885        let value = serde_json::from_value::<String>(value)
886            .map_err(|err| {
887                error!(?err, "SCIM CredentialType syntax invalid");
888                OperationError::SC0015CredentialTypeSyntaxInvalid
889            })
890            .and_then(|value| {
891                CredentialType::try_from(value.as_str()).map_err(|()| {
892                    error!("SCIM CredentialType syntax invalid - value");
893                    OperationError::SC0015CredentialTypeSyntaxInvalid
894                })
895            })?;
896
897        let mut set = SmolSet::new();
898        set.insert(value);
899
900        Ok(ValueSetResolveStatus::Resolved(Box::new(
901            ValueSetCredentialType { set },
902        )))
903    }
904}
905
906impl ValueSetT for ValueSetCredentialType {
907    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
908        match value {
909            Value::CredentialType(u) => Ok(self.set.insert(u)),
910            _ => {
911                debug_assert!(false);
912                Err(OperationError::InvalidValueState)
913            }
914        }
915    }
916
917    fn clear(&mut self) {
918        self.set.clear();
919    }
920
921    fn remove(&mut self, pv: &PartialValue, _cid: &Cid) -> bool {
922        match pv {
923            PartialValue::CredentialType(u) => {
924                self.set.remove(u);
925            }
926            _ => {
927                debug_assert!(false);
928            }
929        };
930        self.set.is_empty()
931    }
932
933    fn contains(&self, pv: &PartialValue) -> bool {
934        match pv {
935            PartialValue::CredentialType(u) => self.set.contains(u),
936            _ => false,
937        }
938    }
939
940    fn substring(&self, _pv: &PartialValue) -> bool {
941        false
942    }
943
944    fn startswith(&self, _pv: &PartialValue) -> bool {
945        false
946    }
947
948    fn endswith(&self, _pv: &PartialValue) -> bool {
949        false
950    }
951
952    fn lessthan(&self, _pv: &PartialValue) -> bool {
953        false
954    }
955
956    fn len(&self) -> usize {
957        self.set.len()
958    }
959
960    fn generate_idx_eq_keys(&self) -> Vec<String> {
961        self.set.iter().map(|u| u.to_string()).collect()
962    }
963
964    fn syntax(&self) -> SyntaxType {
965        SyntaxType::CredentialType
966    }
967
968    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
969        true
970    }
971
972    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
973        Box::new(self.set.iter().map(|ct| ct.to_string()))
974    }
975
976    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
977        self.set
978            .iter()
979            .next()
980            .map(|ct| ScimResolveStatus::Resolved(ScimValueKanidm::from(ct.to_string())))
981    }
982
983    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
984        DbValueSetV2::CredentialType(self.set.iter().map(|s| *s as u16).collect())
985    }
986
987    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
988        Box::new(self.set.iter().copied().map(PartialValue::CredentialType))
989    }
990
991    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
992        Box::new(self.set.iter().copied().map(Value::CredentialType))
993    }
994
995    fn equal(&self, other: &ValueSet) -> bool {
996        if let Some(other) = other.as_credentialtype_set() {
997            &self.set == other
998        } else {
999            debug_assert!(false);
1000            false
1001        }
1002    }
1003
1004    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
1005        if let Some(b) = other.as_credentialtype_set() {
1006            mergesets!(self.set, b)
1007        } else {
1008            debug_assert!(false);
1009            Err(OperationError::InvalidValueState)
1010        }
1011    }
1012
1013    fn to_credentialtype_single(&self) -> Option<CredentialType> {
1014        if self.set.len() == 1 {
1015            self.set.iter().copied().take(1).next()
1016        } else {
1017            None
1018        }
1019    }
1020
1021    fn as_credentialtype_set(&self) -> Option<&SmolSet<[CredentialType; 1]>> {
1022        Some(&self.set)
1023    }
1024}
1025
1026#[derive(Debug, Clone)]
1027pub struct ValueSetWebauthnAttestationCaList {
1028    ca_list: AttestationCaList,
1029}
1030
1031impl ValueSetWebauthnAttestationCaList {
1032    pub fn new(ca_list: AttestationCaList) -> Box<Self> {
1033        Box::new(ValueSetWebauthnAttestationCaList { ca_list })
1034    }
1035
1036    pub fn from_dbvs2(ca_list: AttestationCaList) -> Result<ValueSet, OperationError> {
1037        Ok(Box::new(ValueSetWebauthnAttestationCaList { ca_list }))
1038    }
1039}
1040
1041impl ValueSetT for ValueSetWebauthnAttestationCaList {
1042    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError> {
1043        match value {
1044            Value::WebauthnAttestationCaList(u) => {
1045                self.ca_list.union(&u);
1046                Ok(true)
1047            }
1048            _ => {
1049                debug_assert!(false);
1050                Err(OperationError::InvalidValueState)
1051            }
1052        }
1053    }
1054
1055    fn clear(&mut self) {
1056        self.ca_list.clear();
1057    }
1058
1059    fn remove(&mut self, _pv: &PartialValue, _cid: &Cid) -> bool {
1060        debug_assert!(false);
1061        true
1062    }
1063
1064    fn contains(&self, _pv: &PartialValue) -> bool {
1065        false
1066    }
1067
1068    fn substring(&self, _pv: &PartialValue) -> bool {
1069        false
1070    }
1071
1072    fn startswith(&self, _pv: &PartialValue) -> bool {
1073        false
1074    }
1075
1076    fn endswith(&self, _pv: &PartialValue) -> bool {
1077        false
1078    }
1079
1080    fn lessthan(&self, _pv: &PartialValue) -> bool {
1081        false
1082    }
1083
1084    fn len(&self) -> usize {
1085        self.ca_list.len()
1086    }
1087
1088    fn generate_idx_eq_keys(&self) -> Vec<String> {
1089        // self.set.iter().map(|u| u.to_string()).collect()
1090        Vec::with_capacity(0)
1091    }
1092
1093    fn syntax(&self) -> SyntaxType {
1094        SyntaxType::WebauthnAttestationCaList
1095    }
1096
1097    fn validate(&self, _schema_attr: &SchemaAttribute) -> bool {
1098        // Should we actually be looking through the ca-list as given and eliminate
1099        // known vuln devices?
1100        true
1101    }
1102
1103    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_> {
1104        Box::new(
1105            self.ca_list
1106                .cas()
1107                .values()
1108                .flat_map(|att_ca| att_ca.aaguids().values())
1109                .map(|device| device.description_en().to_string()),
1110        )
1111    }
1112
1113    fn to_db_valueset_v2(&self) -> DbValueSetV2 {
1114        DbValueSetV2::WebauthnAttestationCaList {
1115            ca_list: self.ca_list.clone(),
1116        }
1117    }
1118
1119    fn to_scim_value(&self) -> Option<ScimResolveStatus> {
1120        Some(ScimResolveStatus::Resolved(ScimValueKanidm::from(
1121            self.ca_list
1122                .cas()
1123                .values()
1124                .flat_map(|att_ca| att_ca.aaguids().values())
1125                .map(|device| device.description_en().to_string())
1126                .collect::<Vec<_>>(),
1127        )))
1128    }
1129
1130    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_> {
1131        Box::new(std::iter::empty::<PartialValue>())
1132    }
1133
1134    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_> {
1135        Box::new(std::iter::once(Value::WebauthnAttestationCaList(
1136            self.ca_list.clone(),
1137        )))
1138    }
1139
1140    fn equal(&self, other: &ValueSet) -> bool {
1141        if let Some(other) = other.as_webauthn_attestation_ca_list() {
1142            &self.ca_list == other
1143        } else {
1144            debug_assert!(false);
1145            false
1146        }
1147    }
1148
1149    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError> {
1150        if let Some(b) = other.as_webauthn_attestation_ca_list() {
1151            self.ca_list.union(b);
1152            Ok(())
1153        } else {
1154            debug_assert!(false);
1155            Err(OperationError::InvalidValueState)
1156        }
1157    }
1158
1159    fn as_webauthn_attestation_ca_list(&self) -> Option<&AttestationCaList> {
1160        Some(&self.ca_list)
1161    }
1162}
1163
1164#[cfg(test)]
1165mod tests {
1166    use super::{CredentialType, IntentTokenState, ValueSetCredentialType, ValueSetIntentToken};
1167    use crate::prelude::ValueSet;
1168    use std::time::Duration;
1169
1170    #[test]
1171    fn test_scim_intent_token() {
1172        // I seem to recall this shouldn't have a value returned?
1173        let vs: ValueSet = ValueSetIntentToken::new(
1174            "ca6f29d1-034b-41fb-abc1-4bb9f0548e67".to_string(),
1175            IntentTokenState::Consumed {
1176                max_ttl: Duration::from_secs(300),
1177            },
1178        );
1179
1180        let data = r#"
1181[
1182  {
1183    "expires": "1970-01-01T00:05:00Z",
1184    "state": "consumed",
1185    "tokenId": "ca6f29d1-034b-41fb-abc1-4bb9f0548e67"
1186  }
1187]
1188        "#;
1189        crate::valueset::scim_json_reflexive(&vs, data);
1190    }
1191
1192    #[test]
1193    fn test_scim_credential_type() {
1194        let vs: ValueSet = ValueSetCredentialType::new(CredentialType::Mfa);
1195        crate::valueset::scim_json_reflexive(&vs, r#""mfa""#);
1196
1197        // Test that we can parse json values into a valueset.
1198        crate::valueset::scim_json_put_reflexive::<ValueSetCredentialType>(&vs, &[])
1199    }
1200}