Skip to main content

kanidmd_lib/valueset/
mod.rs

1use crate::{
2    be::dbvalue::DbValueSetV2,
3    credential::{apppwd::ApplicationPassword, totp::Totp, Credential},
4    prelude::*,
5    repl::cid::Cid,
6    schema::SchemaAttribute,
7    server::keys::KeyId,
8    value::{
9        Address, ApiToken, CredentialType, IntentTokenState, Oauth2Session, OauthClaimMapJoin,
10        Session,
11    },
12};
13use compact_jwt::{crypto::JwsRs256Signer, JwsEs256Signer};
14use crypto_glue::{s256::Sha256Output, x509::Certificate};
15use dyn_clone::DynClone;
16use hashbrown::HashSet;
17use kanidm_proto::{
18    internal::{Filter as ProtoFilter, ImageValue, UiHint},
19    scim_v1::{JsonValue, ScimOauth2ClaimMapJoinChar},
20    v1::OutboundMessage,
21};
22use smolset::SmolSet;
23use sshkey_attest::proto::PublicKey as SshPublicKey;
24use std::{
25    cmp::Ordering,
26    collections::{BTreeMap, BTreeSet},
27};
28use time::OffsetDateTime;
29use webauthn_rs::prelude::{
30    AttestationCaList, AttestedPasskey as AttestedPasskeyV4, Passkey as PasskeyV4,
31};
32
33pub use self::{
34    address::{ValueSetAddress, ValueSetEmailAddress},
35    auditlogstring::{ValueSetAuditLogString, AUDIT_LOG_STRING_CAPACITY},
36    binary::{ValueSetPrivateBinary, ValueSetPublicBinary},
37    bool::ValueSetBool,
38    certificate::ValueSetCertificate,
39    cid::ValueSetCid,
40    cred::{
41        ValueSetAttestedPasskey, ValueSetCredential, ValueSetCredentialType, ValueSetIntentToken,
42        ValueSetPasskey, ValueSetWebauthnAttestationCaList,
43    },
44    datetime::ValueSetDateTime,
45    hexstring::ValueSetHexString,
46    iname::{ValueSetIname, ValueSetInameN},
47    index::ValueSetIndex,
48    int64::ValueSetInt64,
49    iutf8::{ValueSetIutf8, ValueSetIutf8N},
50    json::{ValueSetJson, ValueSetJsonFilter},
51    jws::{ValueSetJwsKeyEs256, ValueSetJwsKeyRs256},
52    key_internal::{KeyInternalData, ValueSetKeyInternal},
53    message::ValueSetMessage,
54    nsuniqueid::ValueSetNsUniqueId,
55    oauth::{OauthClaimMapping, ValueSetOauthClaimMap, ValueSetOauthScope, ValueSetOauthScopeMap},
56    s256::ValueSetSha256,
57    secret::ValueSetSecret,
58    session::{ValueSetApiTokenSet, ValueSetOauth2Session, ValueSetSession},
59    spn::ValueSetSpn,
60    ssh::ValueSetSshKey,
61    syntax::ValueSetSyntax,
62    totp::ValueSetTotpSecret,
63    uihint::ValueSetUiHint,
64    uint32::ValueSetUint32,
65    uint64::ValueSetUint64,
66    url::{ValueSetUrl, ValueSetUrlN},
67    utf8::ValueSetUtf8,
68    uuid::{ValueSetRefer, ValueSetReferN, ValueSetUuid, ValueSetUuidN},
69};
70use self::{apppwd::ValueSetApplicationPassword, image::ValueSetImage};
71
72mod address;
73mod apppwd;
74mod auditlogstring;
75mod binary;
76mod bool;
77mod certificate;
78mod cid;
79mod cred;
80mod datetime;
81mod hexstring;
82pub mod image;
83mod iname;
84mod index;
85mod int64;
86mod iutf8;
87mod json;
88mod jws;
89mod key_internal;
90mod message;
91mod nsuniqueid;
92mod oauth;
93mod s256;
94mod secret;
95mod session;
96mod spn;
97mod ssh;
98mod syntax;
99mod totp;
100mod uihint;
101mod uint32;
102mod uint64;
103mod url;
104mod utf8;
105mod uuid;
106
107pub type ValueSet = Box<dyn ValueSetT + Send + Sync + 'static>;
108
109dyn_clone::clone_trait_object!(ValueSetT);
110
111pub trait ValueSetT: std::fmt::Debug + DynClone {
112    /// Returns whether the value was newly inserted. That is:
113    /// * If the set did not previously contain an equal value, true is returned.
114    /// * If the set already contained an equal value, false is returned, and the entry is not updated.
115    ///
116    fn insert_checked(&mut self, value: Value) -> Result<bool, OperationError>;
117
118    fn clear(&mut self);
119
120    #[must_use]
121    fn remove(&mut self, _pv: &PartialValue, _cid: &Cid) -> bool;
122
123    #[must_use]
124    fn purge(&mut self, _cid: &Cid) -> bool {
125        // Default handling is true.
126        true
127    }
128
129    fn trim(&mut self, _trim_cid: &Cid) {
130        // default to a no-op
131    }
132
133    fn contains(&self, pv: &PartialValue) -> bool;
134
135    fn substring(&self, _pv: &crate::value::PartialValue) -> bool {
136        false
137    }
138
139    fn startswith(&self, _pv: &PartialValue) -> bool {
140        false
141    }
142
143    fn endswith(&self, _pv: &PartialValue) -> bool {
144        false
145    }
146
147    fn lessthan(&self, _pv: &crate::value::PartialValue) -> bool {
148        false
149    }
150
151    fn len(&self) -> usize;
152
153    fn generate_idx_eq_keys(&self) -> Vec<String> {
154        Vec::with_capacity(0)
155    }
156
157    fn generate_idx_sub_keys(&self) -> Vec<String> {
158        Vec::with_capacity(0)
159    }
160
161    fn generate_idx_ord_keys(&self) -> Vec<String> {
162        Vec::with_capacity(0)
163    }
164
165    fn syntax(&self) -> SyntaxType;
166
167    fn validate(&self, schema_attr: &SchemaAttribute) -> bool;
168
169    fn to_proto_string_clone_iter(&self) -> Box<dyn Iterator<Item = String> + '_>;
170
171    fn to_scim_value(&self) -> Option<ScimResolveStatus>;
172
173    fn to_db_valueset_v2(&self) -> DbValueSetV2;
174
175    fn to_partialvalue_iter(&self) -> Box<dyn Iterator<Item = PartialValue> + '_>;
176
177    fn to_value_iter(&self) -> Box<dyn Iterator<Item = Value> + '_>;
178
179    fn equal(&self, other: &ValueSet) -> bool;
180
181    fn cmp(&self, _other: &ValueSet) -> Ordering {
182        // IMPORTANT - in the case we attempt to compare the ordering of two value sets
183        // that are different syntaxs or types, the CORRECT and reliable thing to do is
184        // report them as equal such that any sorting function won't rearrange the values.
185        error!("cmp should not be called on {:?}", self.syntax());
186        debug_assert!(false);
187        Ordering::Equal
188    }
189
190    fn merge(&mut self, other: &ValueSet) -> Result<(), OperationError>;
191
192    fn is_empty(&self) -> bool {
193        self.len() == 0
194    }
195
196    fn migrate(&self) -> Result<Option<ValueSet>, OperationError> {
197        Ok(None)
198    }
199
200    fn get_ssh_tag(&self, _tag: &str) -> Option<&SshPublicKey> {
201        None
202    }
203
204    fn as_ref_uuid_iter(&self) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
205        None
206    }
207
208    fn as_utf8_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
209        error!("as_utf8_iter should not be called on {:?}", self.syntax());
210        debug_assert!(false);
211        None
212    }
213
214    fn as_iutf8_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
215        error!("as_iutf8_iter should not be called on {:?}", self.syntax());
216        debug_assert!(false);
217        None
218    }
219
220    fn as_iname_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
221        error!("as_iname_iter should not be called on {:?}", self.syntax());
222        debug_assert!(false);
223        None
224    }
225
226    fn as_indextype_iter(&self) -> Option<Box<dyn Iterator<Item = IndexType> + '_>> {
227        error!(
228            "as_indextype_set should not be called on {:?}",
229            self.syntax()
230        );
231        None
232    }
233
234    fn as_restricted_string_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
235        error!(
236            "as_restricted_string_iter should not be called on {:?}",
237            self.syntax()
238        );
239        None
240    }
241
242    fn as_oauthscope_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
243        error!(
244            "as_oauthscope_iter should not be called on {:?}",
245            self.syntax()
246        );
247        None
248    }
249
250    fn as_sshpubkey_string_iter(&self) -> Option<Box<dyn Iterator<Item = String> + '_>> {
251        None
252    }
253
254    fn as_email_str_iter(&self) -> Option<Box<dyn Iterator<Item = &str> + '_>> {
255        None
256    }
257
258    fn as_utf8_set(&self) -> Option<&BTreeSet<String>> {
259        debug_assert!(false);
260        None
261    }
262
263    fn as_iutf8_set(&self) -> Option<&BTreeSet<String>> {
264        debug_assert!(false);
265        None
266    }
267
268    fn as_iname_set(&self) -> Option<&BTreeSet<String>> {
269        debug_assert!(false);
270        None
271    }
272
273    fn as_uuid_set(&self) -> Option<&BTreeSet<Uuid>> {
274        None
275    }
276
277    fn as_refer_set(&self) -> Option<&BTreeSet<Uuid>> {
278        None
279    }
280
281    fn as_refer_set_mut(&mut self) -> Option<&mut BTreeSet<Uuid>> {
282        debug_assert!(false);
283        None
284    }
285
286    fn as_bool_set(&self) -> Option<&SmolSet<[bool; 1]>> {
287        debug_assert!(false);
288        None
289    }
290
291    fn as_uint32_set(&self) -> Option<&SmolSet<[u32; 1]>> {
292        debug_assert!(false);
293        None
294    }
295
296    fn as_int64_set(&self) -> Option<&SmolSet<[i64; 1]>> {
297        debug_assert!(false);
298        None
299    }
300
301    fn as_uint64_set(&self) -> Option<&SmolSet<[u64; 1]>> {
302        debug_assert!(false);
303        None
304    }
305
306    fn as_syntax_set(&self) -> Option<&SmolSet<[SyntaxType; 1]>> {
307        debug_assert!(false);
308        None
309    }
310
311    fn as_index_set(&self) -> Option<&SmolSet<[IndexType; 3]>> {
312        debug_assert!(false);
313        None
314    }
315
316    fn as_secret_set(&self) -> Option<&SmolSet<[String; 1]>> {
317        debug_assert!(false);
318        None
319    }
320
321    fn as_restricted_string_set(&self) -> Option<&BTreeSet<String>> {
322        debug_assert!(false);
323        None
324    }
325
326    fn as_spn_set(&self) -> Option<&SmolSet<[(String, String); 1]>> {
327        debug_assert!(false);
328        None
329    }
330
331    fn as_cid_set(&self) -> Option<&SmolSet<[Cid; 1]>> {
332        debug_assert!(false);
333        None
334    }
335
336    fn as_json_filter_set(&self) -> Option<&SmolSet<[ProtoFilter; 1]>> {
337        debug_assert!(false);
338        None
339    }
340
341    fn as_nsuniqueid_set(&self) -> Option<&SmolSet<[String; 1]>> {
342        debug_assert!(false);
343        None
344    }
345
346    fn as_url_set(&self) -> Option<&BTreeSet<Url>> {
347        debug_assert!(false);
348        None
349    }
350
351    fn as_datetime_set(&self) -> Option<&SmolSet<[OffsetDateTime; 1]>> {
352        debug_assert!(false);
353        None
354    }
355
356    fn as_private_binary_set(&self) -> Option<&SmolSet<[Vec<u8>; 1]>> {
357        debug_assert!(false);
358        None
359    }
360
361    fn as_oauthscope_set(&self) -> Option<&BTreeSet<String>> {
362        debug_assert!(false);
363        None
364    }
365
366    fn as_address_set(&self) -> Option<&SmolSet<[Address; 1]>> {
367        debug_assert!(false);
368        None
369    }
370
371    fn as_credential_map(&self) -> Option<&BTreeMap<String, Credential>> {
372        debug_assert!(false);
373        None
374    }
375
376    fn as_totp_map(&self) -> Option<&BTreeMap<String, Totp>> {
377        debug_assert!(false);
378        None
379    }
380
381    fn as_emailaddress_set(&self) -> Option<(&String, &BTreeSet<String>)> {
382        debug_assert!(false);
383        None
384    }
385
386    fn as_sshkey_map(&self) -> Option<&BTreeMap<String, SshPublicKey>> {
387        None
388    }
389
390    fn as_oauthscopemap(&self) -> Option<&BTreeMap<Uuid, BTreeSet<String>>> {
391        /*
392        error!(
393            "as_oauthscopemap should not be called on {:?}",
394            self.syntax()
395        );
396        */
397        None
398    }
399
400    fn as_publicbinary_map(&self) -> Option<&BTreeMap<String, Vec<u8>>> {
401        debug_assert!(false);
402        None
403    }
404
405    fn as_intenttoken_map(&self) -> Option<&BTreeMap<String, IntentTokenState>> {
406        debug_assert!(false);
407        None
408    }
409
410    fn as_passkey_map(&self) -> Option<&BTreeMap<Uuid, (String, PasskeyV4)>> {
411        debug_assert!(false);
412        None
413    }
414
415    fn as_attestedpasskey_map(&self) -> Option<&BTreeMap<Uuid, (String, AttestedPasskeyV4)>> {
416        debug_assert!(false);
417        None
418    }
419
420    fn as_webauthn_attestation_ca_list(&self) -> Option<&AttestationCaList> {
421        debug_assert!(false);
422        None
423    }
424
425    fn as_oauthclaim_map(&self) -> Option<&BTreeMap<String, OauthClaimMapping>> {
426        None
427    }
428
429    fn as_key_internal_map(&self) -> Option<&BTreeMap<KeyId, KeyInternalData>> {
430        debug_assert!(false);
431        None
432    }
433
434    fn as_hexstring_set(&self) -> Option<&BTreeSet<String>> {
435        debug_assert!(false);
436        None
437    }
438
439    fn as_application_password_map(&self) -> Option<&BTreeMap<Uuid, Vec<ApplicationPassword>>> {
440        debug_assert!(false);
441        None
442    }
443
444    fn to_value_single(&self) -> Option<Value> {
445        if self.len() != 1 {
446            None
447        } else {
448            self.to_value_iter().take(1).next()
449        }
450    }
451
452    fn to_proto_string_single(&self) -> Option<String> {
453        if self.len() != 1 {
454            None
455        } else {
456            self.to_proto_string_clone_iter().take(1).next()
457        }
458    }
459
460    fn to_uuid_single(&self) -> Option<Uuid> {
461        error!("to_uuid_single should not be called on {:?}", self.syntax());
462        None
463    }
464
465    fn to_cid_single(&self) -> Option<Cid> {
466        error!("to_cid_single should not be called on {:?}", self.syntax());
467        None
468    }
469
470    fn to_refer_single(&self) -> Option<Uuid> {
471        error!(
472            "to_refer_single should not be called on {:?}",
473            self.syntax()
474        );
475        debug_assert!(false);
476        None
477    }
478
479    fn to_bool_single(&self) -> Option<bool> {
480        error!("to_bool_single should not be called on {:?}", self.syntax());
481        None
482    }
483
484    fn to_uint32_single(&self) -> Option<u32> {
485        error!(
486            "to_uint32_single should not be called on {:?}",
487            self.syntax()
488        );
489        debug_assert!(false);
490        None
491    }
492
493    fn to_int64_single(&self) -> Option<i64> {
494        error!(
495            "to_int64_single should not be called on {:?}",
496            self.syntax()
497        );
498        debug_assert!(false);
499        None
500    }
501
502    fn to_uint64_single(&self) -> Option<u64> {
503        error!(
504            "to_uint64_single should not be called on {:?}",
505            self.syntax()
506        );
507        debug_assert!(false);
508        None
509    }
510
511    fn to_syntaxtype_single(&self) -> Option<SyntaxType> {
512        error!(
513            "to_syntaxtype_single should not be called on {:?}",
514            self.syntax()
515        );
516        None
517    }
518
519    fn to_credential_single(&self) -> Option<&Credential> {
520        error!(
521            "to_credential_single should not be called on {:?}",
522            self.syntax()
523        );
524        debug_assert!(false);
525        None
526    }
527
528    fn to_secret_single(&self) -> Option<&str> {
529        error!(
530            "to_secret_single should not be called on {:?}",
531            self.syntax()
532        );
533        debug_assert!(false);
534        None
535    }
536
537    fn to_restricted_string_single(&self) -> Option<&str> {
538        error!(
539            "to_restricted_string_single should not be called on {:?}",
540            self.syntax()
541        );
542        debug_assert!(false);
543        None
544    }
545
546    fn to_utf8_single(&self) -> Option<&str> {
547        error!("to_utf8_single should not be called on {:?}", self.syntax());
548        debug_assert!(false);
549        None
550    }
551
552    fn to_iutf8_single(&self) -> Option<&str> {
553        error!(
554            "to_iutf8_single should not be called on {:?}",
555            self.syntax()
556        );
557        debug_assert!(false);
558        None
559    }
560
561    fn to_iname_single(&self) -> Option<&str> {
562        error!(
563            "to_iname_single should not be called on {:?}",
564            self.syntax()
565        );
566        debug_assert!(false);
567        None
568    }
569
570    fn to_datetime_single(&self) -> Option<OffsetDateTime> {
571        error!(
572            "to_datetime_single should not be called on {:?}",
573            self.syntax()
574        );
575        debug_assert!(false);
576        None
577    }
578
579    fn to_url_single(&self) -> Option<&Url> {
580        error!("to_url_single should not be called on {:?}", self.syntax());
581        debug_assert!(false);
582        None
583    }
584
585    fn to_json_filter_single(&self) -> Option<&ProtoFilter> {
586        error!(
587            "to_json_filter_single should not be called on {:?}",
588            self.syntax()
589        );
590        // debug_assert!(false);
591        None
592    }
593
594    fn to_email_address_primary_str(&self) -> Option<&str> {
595        debug_assert!(false);
596        None
597    }
598
599    fn to_private_binary_single(&self) -> Option<&[u8]> {
600        debug_assert!(false);
601        None
602    }
603
604    fn to_passkey_single(&self) -> Option<&PasskeyV4> {
605        debug_assert!(false);
606        None
607    }
608
609    fn as_session_map(&self) -> Option<&BTreeMap<Uuid, Session>> {
610        debug_assert!(false);
611        None
612    }
613
614    fn as_apitoken_map(&self) -> Option<&BTreeMap<Uuid, ApiToken>> {
615        debug_assert!(false);
616        None
617    }
618
619    fn as_oauth2session_map(&self) -> Option<&BTreeMap<Uuid, Oauth2Session>> {
620        debug_assert!(false);
621        None
622    }
623
624    fn to_jws_key_es256_single(&self) -> Option<&JwsEs256Signer> {
625        debug_assert!(false);
626        None
627    }
628
629    fn as_jws_key_es256_set(&self) -> Option<&HashSet<JwsEs256Signer>> {
630        debug_assert!(false);
631        None
632    }
633
634    fn to_jws_key_rs256_single(&self) -> Option<&JwsRs256Signer> {
635        debug_assert!(false);
636        None
637    }
638
639    fn as_jws_key_rs256_set(&self) -> Option<&HashSet<JwsRs256Signer>> {
640        debug_assert!(false);
641        None
642    }
643
644    fn as_uihint_set(&self) -> Option<&BTreeSet<UiHint>> {
645        debug_assert!(false);
646        None
647    }
648
649    fn as_uihint_iter(&self) -> Option<Box<dyn Iterator<Item = UiHint> + '_>> {
650        debug_assert!(false);
651        None
652    }
653
654    fn as_audit_log_string(&self) -> Option<&BTreeMap<Cid, String>> {
655        debug_assert!(false);
656        None
657    }
658
659    fn as_imageset(&self) -> Option<&HashSet<ImageValue>> {
660        debug_assert!(false);
661        None
662    }
663
664    fn to_credentialtype_single(&self) -> Option<CredentialType> {
665        debug_assert!(false);
666        None
667    }
668
669    fn as_credentialtype_set(&self) -> Option<&SmolSet<[CredentialType; 1]>> {
670        debug_assert!(false);
671        None
672    }
673
674    fn to_certificate_single(&self) -> Option<&Certificate> {
675        debug_assert!(false);
676        None
677    }
678
679    fn as_certificate_set(&self) -> Option<&BTreeMap<Sha256Output, Box<Certificate>>> {
680        debug_assert!(false);
681        None
682    }
683
684    fn as_json_object(&self) -> Option<&JsonValue> {
685        debug_assert!(false);
686        None
687    }
688
689    fn as_message(&self) -> Option<&OutboundMessage> {
690        debug_assert!(false);
691        None
692    }
693
694    fn as_s256_set(&self) -> Option<&BTreeSet<Sha256Output>> {
695        debug_assert!(false);
696        None
697    }
698
699    fn as_s256_set_mut(&mut self) -> Option<&mut BTreeSet<Sha256Output>> {
700        debug_assert!(false);
701        None
702    }
703
704    fn repl_merge_valueset(
705        &self,
706        _older: &ValueSet,
707        _trim_cid: &Cid, // schema_attr: &SchemaAttribute
708    ) -> Option<ValueSet> {
709        // Self is the "latest" content. Older contains the earlier
710        // state of the attribute.
711        //
712        // In most cases we don't actually need a merge strategy. We just need the
713        // newer state of the attribute.
714        //
715        // However when we have a merge strategy that is required we return
716        // Some(new_state) if and only if merges were applied that need to be added
717        // to the change state.
718        //
719        // If no merge was required, we just return None.
720        //
721        // Examples where we need merging is session states. This has an internal
722        // attribute state machine that works similarly to tombstones to ensure that
723        // after a certain period that attributes are cleaned up.
724        None
725    }
726}
727
728pub trait ValueSetScimPut {
729    fn from_scim_json_put(value: JsonValue) -> Result<ValueSetResolveStatus, OperationError>;
730}
731
732impl PartialEq for ValueSet {
733    fn eq(&self, other: &ValueSet) -> bool {
734        self.equal(other)
735    }
736}
737
738pub struct UnresolvedScimValueOauth2ClaimMap {
739    pub group_uuid: Uuid,
740    pub claim: String,
741    pub join_char: ScimOauth2ClaimMapJoinChar,
742    pub values: BTreeSet<String>,
743}
744
745pub struct UnresolvedScimValueOauth2ScopeMap {
746    pub group_uuid: Uuid,
747    pub scopes: BTreeSet<String>,
748}
749
750#[derive(Debug)]
751pub enum UnresolvedReferenceState {
752    Uuid(Uuid),
753    Value(String),
754    Complete { uuid: Uuid, value: String },
755}
756
757pub enum ScimValueIntermediate {
758    Reference(Uuid),
759    References(Vec<Uuid>),
760    Oauth2ClaimMap(Vec<UnresolvedScimValueOauth2ClaimMap>),
761    Oauth2ScopeMap(Vec<UnresolvedScimValueOauth2ScopeMap>),
762}
763
764pub enum ScimResolveStatus {
765    Resolved(ScimValueKanidm),
766    NeedsResolution(ScimValueIntermediate),
767}
768
769impl<T> From<T> for ScimResolveStatus
770where
771    T: Into<ScimValueKanidm>,
772{
773    fn from(v: T) -> Self {
774        Self::Resolved(v.into())
775    }
776}
777
778#[cfg(test)]
779impl ScimResolveStatus {
780    pub fn assume_resolved(self) -> ScimValueKanidm {
781        match self {
782            ScimResolveStatus::Resolved(v) => v,
783            ScimResolveStatus::NeedsResolution(_) => {
784                panic!("assume_resolved called on NeedsResolution")
785            }
786        }
787    }
788
789    pub fn assume_unresolved(self) -> ScimValueIntermediate {
790        match self {
791            ScimResolveStatus::Resolved(_) => panic!("assume_unresolved called on Resolved"),
792            ScimResolveStatus::NeedsResolution(svi) => svi,
793        }
794    }
795}
796
797pub enum ValueSetResolveStatus {
798    Resolved(ValueSet),
799    NeedsResolution(ValueSetIntermediate),
800}
801
802#[cfg(test)]
803impl ValueSetResolveStatus {
804    pub fn assume_resolved(self) -> ValueSet {
805        match self {
806            ValueSetResolveStatus::Resolved(v) => v,
807            ValueSetResolveStatus::NeedsResolution(_) => {
808                panic!("assume_resolved called on NeedsResolution")
809            }
810        }
811    }
812
813    pub fn assume_unresolved(self) -> ValueSetIntermediate {
814        match self {
815            ValueSetResolveStatus::Resolved(_) => panic!("assume_unresolved called on Resolved"),
816            ValueSetResolveStatus::NeedsResolution(svi) => svi,
817        }
818    }
819}
820
821pub enum ValueSetIntermediate {
822    Reference(UnresolvedReferenceState),
823    References {
824        unresolved: Vec<UnresolvedReferenceState>,
825    },
826    Oauth2ClaimMap {
827        resolved: Vec<ResolvedValueSetOauth2ClaimMap>,
828        unresolved: Vec<UnresolvedValueSetOauth2ClaimMap>,
829    },
830    Oauth2ScopeMap {
831        resolved: Vec<ResolvedValueSetOauth2ScopeMap>,
832        unresolved: Vec<UnresolvedValueSetOauth2ScopeMap>,
833    },
834}
835
836pub struct UnresolvedValueSetOauth2ClaimMap {
837    pub group_name: String,
838    pub claim: String,
839    pub join_char: OauthClaimMapJoin,
840    pub claim_values: BTreeSet<String>,
841}
842
843pub struct ResolvedValueSetOauth2ClaimMap {
844    pub group_uuid: Uuid,
845    pub claim: String,
846    pub join_char: OauthClaimMapJoin,
847    pub claim_values: BTreeSet<String>,
848}
849
850pub struct UnresolvedValueSetOauth2ScopeMap {
851    pub group_name: String,
852    pub scopes: BTreeSet<String>,
853}
854
855pub struct ResolvedValueSetOauth2ScopeMap {
856    pub group_uuid: Uuid,
857    pub scopes: BTreeSet<String>,
858}
859
860pub fn uuid_to_proto_string(u: Uuid) -> String {
861    u.as_hyphenated().to_string()
862}
863
864pub fn from_result_value_iter(
865    mut iter: impl Iterator<Item = Result<Value, OperationError>>,
866) -> Result<ValueSet, OperationError> {
867    let Some(init) = iter.next() else {
868        trace!("Empty value iterator");
869        return Err(OperationError::InvalidValueState);
870    };
871
872    let init = init?;
873
874    let mut vs: ValueSet = match init {
875        Value::Utf8(s) => ValueSetUtf8::new(s),
876        Value::Iutf8(s) => ValueSetIutf8::new(&s),
877        Value::Iutf8N(s) => ValueSetIutf8N::new(&s),
878        Value::Iname(s) => ValueSetIname::new(&s),
879        Value::InameN(s) => ValueSetInameN::new(&s),
880        Value::Uuid(u) | Value::UuidN(u) => ValueSetUuid::new(u),
881        Value::Refer(u) => ValueSetRefer::new(u),
882        Value::ReferN(u) => ValueSetReferN::new(u),
883        Value::Bool(u) => ValueSetBool::new(u),
884        Value::Uint32(u) => ValueSetUint32::new(u),
885        Value::Int64(u) => ValueSetInt64::new(u),
886        Value::Uint64(u) => ValueSetUint64::new(u),
887        Value::Syntax(u) => ValueSetSyntax::new(u),
888        Value::Index(u) => ValueSetIndex::new(u),
889        Value::SecretValue(u) => ValueSetSecret::new(u),
890        Value::Spn(n, d) => ValueSetSpn::new((n, d)),
891        Value::Cid(u) => ValueSetCid::new(u),
892        Value::JsonFilt(u) => ValueSetJsonFilter::new(u),
893        Value::Nsuniqueid(u) => ValueSetNsUniqueId::new(u),
894        Value::Url(u) => ValueSetUrl::new(u),
895        Value::UrlN(u) => ValueSetUrlN::new(u),
896        Value::DateTime(u) => ValueSetDateTime::new(u),
897        Value::PrivateBinary(u) => ValueSetPrivateBinary::new(u),
898        Value::OauthScope(u) => ValueSetOauthScope::new(u),
899        Value::Address(u) => ValueSetAddress::new(u),
900        Value::Cred(t, c) => ValueSetCredential::new(t, c),
901        Value::SshKey(t, k) => ValueSetSshKey::new(t, k),
902        Value::OauthScopeMap(u, m) => ValueSetOauthScopeMap::new(u, m),
903        Value::PublicBinary(t, b) => ValueSetPublicBinary::new(t, b),
904        Value::IntentToken(u, s) => ValueSetIntentToken::new(u, s),
905        Value::EmailAddress(a, _) => ValueSetEmailAddress::new(a),
906        Value::UiHint(u) => ValueSetUiHint::new(u),
907        Value::AuditLogString(c, s) => ValueSetAuditLogString::new((c, s)),
908        Value::Image(imagevalue) => image::ValueSetImage::new(imagevalue),
909        Value::CredentialType(c) => ValueSetCredentialType::new(c),
910        Value::Certificate(c) => ValueSetCertificate::new(c)?,
911        Value::WebauthnAttestationCaList(_)
912        | Value::PhoneNumber(_, _)
913        | Value::ApplicationPassword(_)
914        | Value::Passkey(_, _, _)
915        | Value::AttestedPasskey(_, _, _)
916        | Value::TotpSecret(_, _)
917        | Value::Session(_, _)
918        | Value::ApiToken(_, _)
919        | Value::Oauth2Session(_, _)
920        | Value::OauthClaimMap(_, _)
921        | Value::OauthClaimValue(_, _, _)
922        | Value::JwsKeyEs256(_)
923        | Value::JwsKeyRs256(_)
924        | Value::HexString(_)
925        | Value::Json(_)
926        | Value::Sha256(_)
927        | Value::KeyInternal { .. } => {
928            debug_assert!(false);
929            return Err(OperationError::InvalidValueState);
930        }
931    };
932
933    for maybe_v in iter {
934        let v = maybe_v?;
935        // Need to error if wrong type (but shouldn't be due to the way qs works)
936        vs.insert_checked(v)?;
937    }
938    Ok(vs)
939}
940
941pub fn from_value_iter(mut iter: impl Iterator<Item = Value>) -> Result<ValueSet, OperationError> {
942    let Some(init) = iter.next() else {
943        trace!("Empty value iterator");
944        return Err(OperationError::InvalidValueState);
945    };
946
947    let mut vs: ValueSet = match init {
948        Value::Utf8(s) => ValueSetUtf8::new(s),
949        Value::Iutf8(s) => ValueSetIutf8::new(&s),
950        Value::Iutf8N(s) => ValueSetIutf8N::new(&s),
951        Value::Iname(s) => ValueSetIname::new(&s),
952        Value::InameN(s) => ValueSetInameN::new(&s),
953        Value::Uuid(u) | Value::UuidN(u) => ValueSetUuid::new(u),
954        Value::Refer(u) => ValueSetRefer::new(u),
955        Value::ReferN(u) => ValueSetReferN::new(u),
956        Value::Bool(u) => ValueSetBool::new(u),
957        Value::Uint32(u) => ValueSetUint32::new(u),
958        Value::Int64(u) => ValueSetInt64::new(u),
959        Value::Uint64(u) => ValueSetUint64::new(u),
960        Value::Syntax(u) => ValueSetSyntax::new(u),
961        Value::Index(u) => ValueSetIndex::new(u),
962        Value::SecretValue(u) => ValueSetSecret::new(u),
963        Value::Spn(n, d) => ValueSetSpn::new((n, d)),
964        Value::Cid(u) => ValueSetCid::new(u),
965        Value::JsonFilt(u) => ValueSetJsonFilter::new(u),
966        Value::Nsuniqueid(u) => ValueSetNsUniqueId::new(u),
967        Value::Url(u) => ValueSetUrl::new(u),
968        Value::UrlN(u) => ValueSetUrlN::new(u),
969        Value::DateTime(u) => ValueSetDateTime::new(u),
970        Value::PrivateBinary(u) => ValueSetPrivateBinary::new(u),
971        Value::OauthScope(u) => ValueSetOauthScope::new(u),
972        Value::Address(u) => ValueSetAddress::new(u),
973        Value::Cred(t, c) => ValueSetCredential::new(t, c),
974        Value::SshKey(t, k) => ValueSetSshKey::new(t, k),
975        Value::OauthScopeMap(u, m) => ValueSetOauthScopeMap::new(u, m),
976        Value::PublicBinary(t, b) => ValueSetPublicBinary::new(t, b),
977        Value::IntentToken(u, s) => ValueSetIntentToken::new(u, s),
978        Value::EmailAddress(a, _) => ValueSetEmailAddress::new(a),
979        Value::Passkey(u, t, k) => ValueSetPasskey::new(u, t, k),
980        Value::AttestedPasskey(u, t, k) => ValueSetAttestedPasskey::new(u, t, k),
981        Value::JwsKeyEs256(k) => ValueSetJwsKeyEs256::new(k),
982        Value::JwsKeyRs256(k) => ValueSetJwsKeyRs256::new(k),
983        Value::Session(u, m) => ValueSetSession::new(u, m),
984        Value::ApiToken(u, m) => ValueSetApiTokenSet::new(u, m),
985        Value::Oauth2Session(u, m) => ValueSetOauth2Session::new(u, m),
986        Value::UiHint(u) => ValueSetUiHint::new(u),
987        Value::TotpSecret(l, t) => ValueSetTotpSecret::new(l, t),
988        Value::AuditLogString(c, s) => ValueSetAuditLogString::new((c, s)),
989        Value::Image(imagevalue) => image::ValueSetImage::new(imagevalue),
990        Value::CredentialType(c) => ValueSetCredentialType::new(c),
991        Value::WebauthnAttestationCaList(ca_list) => {
992            ValueSetWebauthnAttestationCaList::new(ca_list)
993        }
994        Value::OauthClaimMap(name, join) => ValueSetOauthClaimMap::new(name, join),
995        Value::OauthClaimValue(name, group, claims) => {
996            ValueSetOauthClaimMap::new_value(name, group, claims)
997        }
998        Value::HexString(s) => ValueSetHexString::new(s),
999
1000        Value::KeyInternal {
1001            id,
1002            usage,
1003            valid_from,
1004            status,
1005            status_cid,
1006            der,
1007        } => ValueSetKeyInternal::new(id, usage, valid_from, status, status_cid, der),
1008        Value::Certificate(certificate) => ValueSetCertificate::new(certificate)?,
1009        Value::PhoneNumber(_, _) => {
1010            debug_assert!(false);
1011            return Err(OperationError::InvalidValueState);
1012        }
1013        Value::ApplicationPassword(ap) => ValueSetApplicationPassword::new(ap),
1014        Value::Sha256(_) => {
1015            debug_assert!(false);
1016            return Err(OperationError::InvalidValueState);
1017        }
1018        Value::Json(_) => {
1019            debug_assert!(false);
1020            return Err(OperationError::InvalidValueState);
1021        }
1022    };
1023
1024    for v in iter {
1025        vs.insert_checked(v)?;
1026    }
1027    Ok(vs)
1028}
1029
1030pub fn from_db_valueset_v2(dbvs: DbValueSetV2) -> Result<ValueSet, OperationError> {
1031    match dbvs {
1032        DbValueSetV2::Utf8(set) => ValueSetUtf8::from_dbvs2(set),
1033        DbValueSetV2::Iutf8(set) => ValueSetIutf8N::from_dbvs2(set),
1034        DbValueSetV2::Iutf8Single(set) => ValueSetIutf8::from_dbvs2(set),
1035        DbValueSetV2::Iname(set) => ValueSetInameN::from_dbvs2(set),
1036        DbValueSetV2::InameSingle(set) => ValueSetIname::from_dbvs2(set),
1037        DbValueSetV2::Uuid(set) => ValueSetUuidN::from_dbvs2(set),
1038        DbValueSetV2::UuidSingle(uuid) => ValueSetUuid::from_dbvs2(uuid),
1039
1040        DbValueSetV2::Reference(set) => ValueSetReferN::from_dbvs2(set),
1041        DbValueSetV2::ReferenceSingle(set) => ValueSetRefer::from_dbvs2(set),
1042        DbValueSetV2::Bool(set) => ValueSetBool::from_dbvs2(set),
1043        DbValueSetV2::Uint32(set) => ValueSetUint32::from_dbvs2(set),
1044        DbValueSetV2::Int64(set) => ValueSetInt64::from_dbvs2(set),
1045        DbValueSetV2::Uint64(set) => ValueSetUint64::from_dbvs2(set),
1046        DbValueSetV2::SyntaxType(set) => ValueSetSyntax::from_dbvs2(set),
1047        DbValueSetV2::IndexType(set) => ValueSetIndex::from_dbvs2(set),
1048        DbValueSetV2::SecretValue(set) => ValueSetSecret::from_dbvs2(set),
1049        DbValueSetV2::Spn(set) => ValueSetSpn::from_dbvs2(set),
1050        DbValueSetV2::Cid(set) => ValueSetCid::from_dbvs2(set),
1051        DbValueSetV2::JsonFilter(set) => ValueSetJsonFilter::from_dbvs2(&set),
1052        DbValueSetV2::NsUniqueId(set) => ValueSetNsUniqueId::from_dbvs2(set),
1053        DbValueSetV2::Url(set) => ValueSetUrlN::from_dbvs2(set),
1054        DbValueSetV2::UrlSingle(set) => ValueSetUrl::from_dbvs2(set),
1055        DbValueSetV2::DateTime(set) => ValueSetDateTime::from_dbvs2(set),
1056        DbValueSetV2::PrivateBinary(set) => ValueSetPrivateBinary::from_dbvs2(set),
1057        DbValueSetV2::OauthScope(set) => ValueSetOauthScope::from_dbvs2(set),
1058        DbValueSetV2::Address(set) => ValueSetAddress::from_dbvs2(set),
1059        DbValueSetV2::Credential(set) => ValueSetCredential::from_dbvs2(set),
1060        DbValueSetV2::SshKey(set) => ValueSetSshKey::from_dbvs2(set),
1061        DbValueSetV2::OauthScopeMap(set) => ValueSetOauthScopeMap::from_dbvs2(set),
1062        DbValueSetV2::PublicBinary(set) => ValueSetPublicBinary::from_dbvs2(set),
1063        DbValueSetV2::IntentToken(set) => ValueSetIntentToken::from_dbvs2(set),
1064        DbValueSetV2::EmailAddress(primary, set) => ValueSetEmailAddress::from_dbvs2(primary, set),
1065        DbValueSetV2::Passkey(set) => ValueSetPasskey::from_dbvs2(set),
1066        DbValueSetV2::AttestedPasskey(set) => ValueSetAttestedPasskey::from_dbvs2(set),
1067        DbValueSetV2::Session(set) => ValueSetSession::from_dbvs2(&set),
1068        DbValueSetV2::ApiTokenSet(set) => ValueSetApiTokenSet::from_dbvs2(set),
1069        DbValueSetV2::Oauth2Session(set) => ValueSetOauth2Session::from_dbvs2(set),
1070        DbValueSetV2::JwsKeyEs256(set) => ValueSetJwsKeyEs256::from_dbvs2(&set),
1071        DbValueSetV2::JwsKeyRs256(set) => ValueSetJwsKeyEs256::from_dbvs2(&set),
1072        DbValueSetV2::UiHint(set) => ValueSetUiHint::from_dbvs2(set),
1073        DbValueSetV2::TotpSecret(set) => ValueSetTotpSecret::from_dbvs2(set),
1074        DbValueSetV2::AuditLogString(set) => ValueSetAuditLogString::from_dbvs2(set),
1075        DbValueSetV2::PhoneNumber(_, _) | DbValueSetV2::TrustedDeviceEnrollment(_) => {
1076            debug_assert!(false);
1077            Err(OperationError::InvalidValueState)
1078        }
1079        DbValueSetV2::Image(set) => ValueSetImage::from_dbvs2(&set),
1080        DbValueSetV2::CredentialType(set) => ValueSetCredentialType::from_dbvs2(set),
1081        DbValueSetV2::WebauthnAttestationCaList { ca_list } => {
1082            ValueSetWebauthnAttestationCaList::from_dbvs2(ca_list)
1083        }
1084        DbValueSetV2::OauthClaimMap(set) => ValueSetOauthClaimMap::from_dbvs2(set),
1085        DbValueSetV2::KeyInternal(set) => ValueSetKeyInternal::from_dbvs2(set),
1086        DbValueSetV2::HexString(set) => ValueSetHexString::from_dbvs2(set),
1087        DbValueSetV2::Certificate(set) => ValueSetCertificate::from_dbvs2(set),
1088        DbValueSetV2::ApplicationPassword(set) => ValueSetApplicationPassword::from_dbvs2(set),
1089        DbValueSetV2::Json(object) => Ok(ValueSetJson::new(object)),
1090        DbValueSetV2::Sha256(set) => ValueSetSha256::from_dbvs2(set),
1091        DbValueSetV2::Message(object) => Ok(ValueSetMessage::new(object)),
1092        DbValueSetV2::EcKeyPrivate(_) | DbValueSetV2::RestrictedString(_) => {
1093            error!("Use of a deprecated database type");
1094            debug_assert!(false);
1095            Err(OperationError::InvalidState)
1096        }
1097    }
1098}
1099
1100#[cfg(test)]
1101pub(crate) fn scim_json_reflexive(vs: &ValueSet, data: &str) {
1102    let scim_value = vs.to_scim_value().unwrap().assume_resolved();
1103
1104    let strout = serde_json::to_string_pretty(&scim_value).unwrap();
1105    eprintln!("{strout}");
1106
1107    let json_value: serde_json::Value = serde_json::to_value(&scim_value).unwrap();
1108
1109    eprintln!("{data}");
1110    let expect: serde_json::Value = serde_json::from_str(data).unwrap();
1111
1112    assert_eq!(json_value, expect);
1113}
1114
1115#[cfg(test)]
1116pub(crate) fn scim_json_reflexive_unresolved(
1117    write_txn: &mut QueryServerWriteTransaction,
1118    vs: &ValueSet,
1119    data: &str,
1120) {
1121    let scim_int_value = vs.to_scim_value().unwrap().assume_unresolved();
1122    let scim_value = write_txn.resolve_scim_interim(scim_int_value).unwrap();
1123
1124    let strout = serde_json::to_string_pretty(&scim_value).expect("Failed to serialize");
1125    eprintln!("{strout}");
1126
1127    let json_value: serde_json::Value =
1128        serde_json::to_value(&scim_value).expect("Failed to convert to JSON");
1129
1130    let expect: serde_json::Value =
1131        serde_json::from_str(data).expect("Failed to parse expected JSON");
1132
1133    assert_eq!(json_value, expect);
1134}
1135
1136#[cfg(test)]
1137pub(crate) fn scim_json_put_reflexive<T: ValueSetScimPut>(
1138    expect_vs: &ValueSet,
1139    additional_tests: &[(JsonValue, ValueSet)],
1140) {
1141    let scim_value = expect_vs.to_scim_value().unwrap().assume_resolved();
1142
1143    let strout = serde_json::to_string_pretty(&scim_value).unwrap();
1144    eprintln!("{strout}");
1145
1146    let generic = serde_json::to_value(scim_value).unwrap();
1147    // Check that we can turn back into a vs from the generic version.
1148    let vs = T::from_scim_json_put(generic).unwrap().assume_resolved();
1149    assert_eq!(&vs, expect_vs);
1150
1151    // For each additional check, assert they work as expected.
1152    for (jv, expect_vs) in additional_tests {
1153        let vs = T::from_scim_json_put(jv.clone()).unwrap().assume_resolved();
1154        assert_eq!(&vs, expect_vs);
1155    }
1156}
1157
1158#[cfg(test)]
1159pub(crate) fn scim_json_put_reflexive_unresolved<T: ValueSetScimPut>(
1160    write_txn: &mut QueryServerWriteTransaction,
1161    expect_vs: &ValueSet,
1162    additional_tests: &[(JsonValue, ValueSet)],
1163) {
1164    let scim_int_value = expect_vs.to_scim_value().unwrap().assume_unresolved();
1165    let scim_value = write_txn.resolve_scim_interim(scim_int_value).unwrap();
1166
1167    let generic = serde_json::to_value(scim_value).unwrap();
1168    // Check that we can turn back into a vs from the generic version.
1169    let vs_inter = T::from_scim_json_put(generic).unwrap().assume_unresolved();
1170    let vs = write_txn.resolve_valueset_intermediate(vs_inter).unwrap();
1171    assert_eq!(&vs, expect_vs);
1172
1173    // For each additional check, assert they work as expected.
1174    for (jv, expect_vs) in additional_tests {
1175        let vs_inter = T::from_scim_json_put(jv.clone())
1176            .unwrap()
1177            .assume_unresolved();
1178        let vs = write_txn.resolve_valueset_intermediate(vs_inter).unwrap();
1179        assert_eq!(&vs, expect_vs);
1180    }
1181}