Skip to main content

kanidmd_lib/server/
scim.rs

1use crate::{
2    prelude::*,
3    schema::{SchemaAttribute, SchemaTransaction},
4    server::{
5        assert::{AssertEvent, AssertOnce, EntryAssertion},
6        batch_modify::{BatchModifyEvent, ModSetValid},
7        ValueSetResolveStatus,
8    },
9    valueset::*,
10};
11use crypto_glue::s256::Sha256Output;
12use kanidm_proto::scim_v1::{
13    client::{ScimEntryAssertion, ScimEntryPostGeneric, ScimEntryPutGeneric},
14    JsonValue,
15};
16use std::collections::{
17    // BTreeSet,
18    BTreeMap,
19};
20
21#[derive(Debug)]
22pub struct ScimEntryPutEvent {
23    /// The identity performing the change.
24    pub(crate) ident: Identity,
25
26    // future - etags to detect version changes.
27    /// The target entry that will be changed
28    pub(crate) target: Uuid,
29    /// Update an attribute to contain the following value state.
30    /// If the attribute is None, it is removed.
31    pub(crate) attrs: BTreeMap<Attribute, Option<ValueSet>>,
32
33    /// If an effective access check should be carried out post modification
34    /// of the entries
35    pub(crate) effective_access_check: bool,
36}
37
38impl ScimEntryPutEvent {
39    pub fn try_from(
40        ident: Identity,
41        entry: ScimEntryPutGeneric,
42        qs: &mut QueryServerWriteTransaction,
43    ) -> Result<Self, OperationError> {
44        let target = entry.id;
45
46        let attrs = entry
47            .attrs
48            .into_iter()
49            .map(|(attr, json_value)| {
50                qs.resolve_scim_json_put(&attr, json_value)
51                    .map(|kani_value| (attr, kani_value))
52            })
53            .collect::<Result<_, _>>()?;
54
55        let query = entry.query;
56
57        Ok(ScimEntryPutEvent {
58            ident,
59            target,
60            attrs,
61            effective_access_check: query.ext_access_check,
62        })
63    }
64}
65
66#[derive(Debug)]
67pub struct ScimCreateEvent {
68    pub(crate) ident: Identity,
69    pub(crate) entry: EntryInitNew,
70}
71
72impl ScimCreateEvent {
73    pub fn try_from(
74        ident: Identity,
75        classes: &[EntryClass],
76        entry: ScimEntryPostGeneric,
77        qs: &mut QueryServerWriteTransaction,
78    ) -> Result<Self, OperationError> {
79        let mut entry = entry
80            .attrs
81            .into_iter()
82            .map(|(attr, json_value)| {
83                qs.resolve_scim_json_post(&attr, json_value)
84                    .map(|kani_value| (attr, kani_value))
85            })
86            .collect::<Result<EntryInitNew, _>>()?;
87
88        if !classes.is_empty() {
89            let classes = ValueSetIutf8N::from_iter(classes.iter().map(|cls| cls.as_ref()))
90                .ok_or(OperationError::SC0027ClassSetInvalid)?;
91            entry.set_ava_set(&Attribute::Class, classes);
92        } else {
93            return Err(OperationError::SC0027ClassSetInvalid);
94        }
95
96        Ok(ScimCreateEvent { ident, entry })
97    }
98}
99
100#[derive(Debug)]
101pub struct ScimDeleteEvent {
102    /// The identity performing the change.
103    pub(crate) ident: Identity,
104
105    // future - etags to detect version changes.
106    /// The target entry that will be changed
107    pub(crate) target: Uuid,
108
109    /// The class of the target entry.
110    pub(crate) class: EntryClass,
111}
112
113impl ScimDeleteEvent {
114    pub fn new(ident: Identity, target: Uuid, class: EntryClass) -> Self {
115        ScimDeleteEvent {
116            ident,
117            target,
118            class,
119        }
120    }
121}
122
123#[derive(Debug)]
124pub struct ScimAssertEvent {
125    /// The identity performing the change.
126    pub(crate) ident: Identity,
127
128    /// The set of assertions to be performed. These are applied in order.
129    pub(crate) asserts: Vec<ScimEntryAssertion>,
130
131    /// Tracking information about the assertion.
132    pub id: Uuid,
133
134    /// The nonce/checksum of the operation if we want to do this "at most once".
135    pub nonce: Option<Sha256Output>,
136}
137
138impl ScimAssertEvent {
139    pub fn new_migration(
140        asserts: Vec<ScimEntryAssertion>,
141        id: Uuid,
142        nonce: Option<Sha256Output>,
143    ) -> Self {
144        ScimAssertEvent {
145            ident: Identity::migration(),
146            asserts,
147            id,
148            nonce,
149        }
150    }
151}
152
153impl QueryServerWriteTransaction<'_> {
154    /// SCIM PUT is the handler where a single entry is updated. In a SCIM PUT request
155    /// the request defines the state of an attribute in entirety for the update. This
156    /// means if the caller wants to add one email address, they must PUT all existing
157    /// addresses in addition to the new one.
158    pub fn scim_put(
159        &mut self,
160        scim_entry_put: ScimEntryPutEvent,
161    ) -> Result<ScimEntryKanidm, OperationError> {
162        let ScimEntryPutEvent {
163            ident,
164            target,
165            attrs,
166            effective_access_check,
167        } = scim_entry_put;
168
169        // This function transforms the put event into a modify event.
170        let mods_invalid: ModifyList<ModifyInvalid> = attrs.into();
171
172        let mods_valid = mods_invalid
173            .validate(self.get_schema())
174            .map_err(OperationError::SchemaViolation)?;
175
176        let mut modset = ModSetValid::default();
177
178        modset.insert(target, mods_valid);
179
180        let modify_event = BatchModifyEvent {
181            ident: ident.clone(),
182            modset,
183        };
184
185        // dispatch to batch modify
186        self.batch_modify(&modify_event)?;
187
188        // Now get the entry. We handle a lot of the errors here nicely,
189        // but if we got to this point, they really can't happen.
190        let filter_intent = filter!(f_and!([f_eq(Attribute::Uuid, PartialValue::Uuid(target))]));
191
192        let f_intent_valid = filter_intent
193            .validate(self.get_schema())
194            .map_err(OperationError::SchemaViolation)?;
195
196        let f_valid = f_intent_valid.clone().into_ignore_hidden();
197
198        let se = SearchEvent {
199            ident,
200            filter: f_valid,
201            filter_orig: f_intent_valid,
202            // Return all attributes, even ones we didn't affect
203            attrs: None,
204            effective_access_check,
205        };
206
207        let mut vs = self.search_ext(&se)?;
208        match vs.pop() {
209            Some(entry) if vs.is_empty() => entry.to_scim_kanidm(self),
210            _ => {
211                if vs.is_empty() {
212                    Err(OperationError::NoMatchingEntries)
213                } else {
214                    // Multiple entries matched, should not be possible!
215                    Err(OperationError::UniqueConstraintViolation)
216                }
217            }
218        }
219    }
220
221    pub fn scim_create(
222        &mut self,
223        scim_create: ScimCreateEvent,
224    ) -> Result<ScimEntryKanidm, OperationError> {
225        let ScimCreateEvent { ident, entry } = scim_create;
226
227        let create_event = CreateEvent {
228            ident,
229            entries: vec![entry],
230            return_created_uuids: true,
231        };
232
233        let changed_uuids = self.create(&create_event)?;
234
235        let mut changed_uuids = changed_uuids.ok_or(OperationError::SC0028CreatedUuidsInvalid)?;
236
237        let target = if let Some(target) = changed_uuids.pop() {
238            if !changed_uuids.is_empty() {
239                // Too many results!
240                return Err(OperationError::UniqueConstraintViolation);
241            }
242
243            target
244        } else {
245            // No results!
246            return Err(OperationError::NoMatchingEntries);
247        };
248
249        // Now get the entry. We handle a lot of the errors here nicely,
250        // but if we got to this point, they really can't happen.
251        let filter_intent = filter!(f_and!([f_eq(Attribute::Uuid, PartialValue::Uuid(target))]));
252
253        let f_intent_valid = filter_intent
254            .validate(self.get_schema())
255            .map_err(OperationError::SchemaViolation)?;
256
257        let f_valid = f_intent_valid.clone().into_ignore_hidden();
258
259        let se = SearchEvent {
260            ident: create_event.ident,
261            filter: f_valid,
262            filter_orig: f_intent_valid,
263            // Return all attributes
264            attrs: None,
265            effective_access_check: false,
266        };
267
268        let mut vs = self.search_ext(&se)?;
269        match vs.pop() {
270            Some(entry) if vs.is_empty() => entry.to_scim_kanidm(self),
271            _ => {
272                if vs.is_empty() {
273                    Err(OperationError::NoMatchingEntries)
274                } else {
275                    // Multiple entries matched, should not be possible!
276                    Err(OperationError::UniqueConstraintViolation)
277                }
278            }
279        }
280    }
281
282    pub fn scim_delete(&mut self, scim_delete: ScimDeleteEvent) -> Result<(), OperationError> {
283        let ScimDeleteEvent {
284            ident,
285            target,
286            class,
287        } = scim_delete;
288
289        let filter_intent = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target)));
290        let f_intent_valid = filter_intent
291            .validate(self.get_schema())
292            .map_err(OperationError::SchemaViolation)?;
293
294        let filter = filter!(f_and!([
295            f_eq(Attribute::Uuid, PartialValue::Uuid(target)),
296            f_eq(Attribute::Class, class.into())
297        ]));
298        let f_valid = filter
299            .validate(self.get_schema())
300            .map_err(OperationError::SchemaViolation)?;
301
302        let de = DeleteEvent {
303            ident,
304            filter: f_valid,
305            filter_orig: f_intent_valid,
306        };
307
308        self.delete(&de)
309    }
310
311    pub fn scim_assert(&mut self, scim_assert: ScimAssertEvent) -> Result<(), OperationError> {
312        let ScimAssertEvent {
313            ident,
314            asserts,
315            id,
316            nonce,
317        } = scim_assert;
318
319        let once = match nonce {
320            None => AssertOnce::No,
321            Some(nonce) => AssertOnce::Yes { id, nonce },
322        };
323
324        // Before we can transform this, we have to resolve links that *may* exist
325        // within this assertion.
326
327        self.txn_name_to_uuid().extend(asserts.iter().filter_map(
328            |scim_assert| match scim_assert {
329                ScimEntryAssertion::Present { id, attrs } => {
330                    attrs
331                        .get(&Attribute::Name)
332                        .and_then(|value| match value {
333                            // If the name is present, and a valid string.
334                            Some(JsonValue::String(name)) => Some(name.clone()),
335                            _ => None,
336                        })
337                        .map(|name| (name, *id))
338                }
339                ScimEntryAssertion::Absent { .. } => None,
340            },
341        ));
342
343        // Transform from SCIM to Kanidm Internal representations.
344        let asserts = asserts
345            .into_iter()
346            .map(|scim_assert| match scim_assert {
347                ScimEntryAssertion::Present { id, attrs } => {
348                    let attrs = attrs
349                        .into_iter()
350                        .map(|(attr, json_value)| {
351                            self.resolve_scim_json_put(&attr, json_value)
352                                .map(|kani_value| (attr, kani_value))
353                        })
354                        .collect::<Result<_, _>>()?;
355
356                    Ok(EntryAssertion::Present { target: id, attrs })
357                }
358                ScimEntryAssertion::Absent { id } => Ok(EntryAssertion::Absent { target: id }),
359            })
360            .collect::<Result<Vec<_>, _>>()?;
361
362        let assert_event = AssertEvent {
363            ident,
364            asserts,
365            once,
366        };
367
368        self.assert(assert_event)
369    }
370
371    pub(crate) fn resolve_scim_json_put(
372        &mut self,
373        attr: &Attribute,
374        value: Option<JsonValue>,
375    ) -> Result<Option<ValueSet>, OperationError> {
376        let schema = self.get_schema();
377        // Lookup the attr
378        let Some(schema_a) = schema.get_attributes().get(attr) else {
379            // No attribute of this name exists - fail fast, there is no point to
380            // proceed, as nothing can be satisfied.
381            return Err(OperationError::InvalidAttributeName(attr.to_string()));
382        };
383
384        let Some(value) = value else {
385            // It's a none so the value needs to be unset, and the attr DOES exist in
386            // schema.
387            return Ok(None);
388        };
389
390        self.resolve_scim_json(schema_a, value).map(Some)
391    }
392
393    pub(crate) fn resolve_scim_json_post(
394        &mut self,
395        attr: &Attribute,
396        value: JsonValue,
397    ) -> Result<ValueSet, OperationError> {
398        let schema = self.get_schema();
399        // Lookup the attr
400        let Some(schema_a) = schema.get_attributes().get(attr) else {
401            // No attribute of this name exists - fail fast, there is no point to
402            // proceed, as nothing can be satisfied.
403            return Err(OperationError::InvalidAttributeName(attr.to_string()));
404        };
405
406        self.resolve_scim_json(schema_a, value)
407    }
408
409    fn resolve_scim_json(
410        &mut self,
411        schema_a: &SchemaAttribute,
412        value: JsonValue,
413    ) -> Result<ValueSet, OperationError> {
414        let resolve_status = match schema_a.syntax {
415            SyntaxType::Utf8String => ValueSetUtf8::from_scim_json_put(value),
416            SyntaxType::Uuid => ValueSetUuid::from_scim_json_put(value),
417            SyntaxType::UuidN => ValueSetUuidN::from_scim_json_put(value),
418            SyntaxType::Boolean => ValueSetBool::from_scim_json_put(value),
419            SyntaxType::SyntaxId => ValueSetSyntax::from_scim_json_put(value),
420            SyntaxType::IndexId => ValueSetIndex::from_scim_json_put(value),
421            SyntaxType::NsUniqueId => ValueSetNsUniqueId::from_scim_json_put(value),
422            SyntaxType::DateTime => ValueSetDateTime::from_scim_json_put(value),
423            SyntaxType::EmailAddress => ValueSetEmailAddress::from_scim_json_put(value),
424            SyntaxType::OauthScope => ValueSetOauthScope::from_scim_json_put(value),
425            SyntaxType::OauthScopeMap => ValueSetOauthScopeMap::from_scim_json_put(value),
426            SyntaxType::OauthClaimMap => ValueSetOauthClaimMap::from_scim_json_put(value),
427            SyntaxType::UiHint => ValueSetUiHint::from_scim_json_put(value),
428            SyntaxType::CredentialType => ValueSetCredentialType::from_scim_json_put(value),
429            SyntaxType::Certificate => ValueSetCertificate::from_scim_json_put(value),
430            SyntaxType::SshKey => ValueSetSshKey::from_scim_json_put(value),
431            SyntaxType::Uint32 => ValueSetUint32::from_scim_json_put(value),
432            SyntaxType::Int64 => ValueSetInt64::from_scim_json_put(value),
433            SyntaxType::Uint64 => ValueSetUint64::from_scim_json_put(value),
434            SyntaxType::Sha256 => ValueSetSha256::from_scim_json_put(value),
435
436            // Temporary - use the multi-value versions for compatibility.
437            SyntaxType::Url => ValueSetUrl::from_scim_json_put(value),
438            SyntaxType::UrlN => ValueSetUrlN::from_scim_json_put(value),
439            SyntaxType::ReferenceUuid => ValueSetRefer::from_scim_json_put(value),
440            SyntaxType::ReferenceUuidN => ValueSetReferN::from_scim_json_put(value),
441            SyntaxType::Utf8StringIname => ValueSetIname::from_scim_json_put(value),
442            SyntaxType::Utf8StringInameN => ValueSetInameN::from_scim_json_put(value),
443            SyntaxType::Utf8StringInsensitive => ValueSetIutf8::from_scim_json_put(value),
444            SyntaxType::Utf8StringInsensitiveN => ValueSetIutf8N::from_scim_json_put(value),
445
446            // Not Yet ... if ever
447            // SyntaxType::JsonFilter => ValueSetJsonFilter::from_scim_json_put(value),
448            SyntaxType::JsonFilter => Err(OperationError::InvalidAttribute(
449                "Json Filters are not able to be set.".to_string(),
450            )),
451            // Not Yet ... if ever.
452            SyntaxType::Json => Err(OperationError::InvalidAttribute(
453                "Json values are not able to be set.".to_string(),
454            )),
455            SyntaxType::Message => Err(OperationError::InvalidAttribute(
456                "Message values are not able to be set.".to_string(),
457            )),
458            // Can't be set currently as these are only internally generated for key-id's
459            // SyntaxType::HexString => ValueSetHexString::from_scim_json_put(value),
460            SyntaxType::HexString => Err(OperationError::InvalidAttribute(
461                "Hex strings are not able to be set.".to_string(),
462            )),
463
464            // Can't be set until we have better error handling in the set paths
465            // SyntaxType::Image => ValueSetImage::from_scim_json_put(value),
466            SyntaxType::Image => Err(OperationError::InvalidAttribute(
467                "Images are not able to be set.".to_string(),
468            )),
469
470            // Can't be set yet, mostly as I'm lazy
471            // SyntaxType::WebauthnAttestationCaList => {
472            //    ValueSetWebauthnAttestationCaList::from_scim_json_put(value)
473            // }
474            SyntaxType::WebauthnAttestationCaList => Err(OperationError::InvalidAttribute(
475                "Webauthn Attestation Ca Lists are not able to be set.".to_string(),
476            )),
477
478            // Syntax types that can not be submitted
479            SyntaxType::Credential => Err(OperationError::InvalidAttribute(
480                "Credentials are not able to be set.".to_string(),
481            )),
482            SyntaxType::SecretUtf8String => Err(OperationError::InvalidAttribute(
483                "Secrets are not able to be set.".to_string(),
484            )),
485            SyntaxType::SecurityPrincipalName => Err(OperationError::InvalidAttribute(
486                "SPNs are not able to be set.".to_string(),
487            )),
488            SyntaxType::Cid => Err(OperationError::InvalidAttribute(
489                "CIDs are not able to be set.".to_string(),
490            )),
491            SyntaxType::PrivateBinary => Err(OperationError::InvalidAttribute(
492                "Private Binaries are not able to be set.".to_string(),
493            )),
494            SyntaxType::IntentToken => Err(OperationError::InvalidAttribute(
495                "Intent Tokens are not able to be set.".to_string(),
496            )),
497            SyntaxType::Passkey => Err(OperationError::InvalidAttribute(
498                "Passkeys are not able to be set.".to_string(),
499            )),
500            SyntaxType::AttestedPasskey => Err(OperationError::InvalidAttribute(
501                "Attested Passkeys are not able to be set.".to_string(),
502            )),
503            SyntaxType::Session => Err(OperationError::InvalidAttribute(
504                "Sessions are not able to be set.".to_string(),
505            )),
506            SyntaxType::JwsKeyEs256 => Err(OperationError::InvalidAttribute(
507                "Jws ES256 Private Keys are not able to be set.".to_string(),
508            )),
509            SyntaxType::JwsKeyRs256 => Err(OperationError::InvalidAttribute(
510                "Jws RS256 Private Keys are not able to be set.".to_string(),
511            )),
512            SyntaxType::Oauth2Session => Err(OperationError::InvalidAttribute(
513                "Sessions are not able to be set.".to_string(),
514            )),
515            SyntaxType::TotpSecret => Err(OperationError::InvalidAttribute(
516                "TOTP Secrets are not able to be set.".to_string(),
517            )),
518            SyntaxType::ApiToken => Err(OperationError::InvalidAttribute(
519                "API Tokens are not able to be set.".to_string(),
520            )),
521            SyntaxType::AuditLogString => Err(OperationError::InvalidAttribute(
522                "Audit Strings are not able to be set.".to_string(),
523            )),
524            SyntaxType::EcKeyPrivate => Err(OperationError::InvalidAttribute(
525                "EC Private Keys are not able to be set.".to_string(),
526            )),
527            SyntaxType::KeyInternal => Err(OperationError::InvalidAttribute(
528                "Key Internal Structures are not able to be set.".to_string(),
529            )),
530            SyntaxType::ApplicationPassword => Err(OperationError::InvalidAttribute(
531                "Application Passwords are not able to be set.".to_string(),
532            )),
533        }?;
534
535        match resolve_status {
536            ValueSetResolveStatus::Resolved(vs) => Ok(vs),
537            ValueSetResolveStatus::NeedsResolution(vs_inter) => {
538                self.resolve_valueset_intermediate(vs_inter)
539            }
540        }
541    }
542}
543
544#[cfg(test)]
545mod tests {
546    use super::{ScimAssertEvent, ScimEntryPutEvent};
547    use crate::prelude::*;
548    use kanidm_proto::scim_v1::{
549        client::{ScimEntryAssertion, ScimEntryPutKanidm, ScimReference as ScimClientReference},
550        server::ScimReference,
551        ScimMail,
552    };
553    use std::collections::BTreeMap;
554
555    #[qs_test]
556    async fn scim_put_basic(server: &QueryServer) {
557        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
558
559        let idm_admin_entry = server_txn.internal_search_uuid(UUID_IDM_ADMIN).unwrap();
560
561        let idm_admin_ident = Identity::from_impersonate_entry_readwrite(idm_admin_entry);
562
563        // Make an entry.
564        let group_uuid = Uuid::new_v4();
565
566        // Add members to our groups to test reference handling in scim
567        let extra1_uuid = Uuid::new_v4();
568        let extra2_uuid = Uuid::new_v4();
569        let extra3_uuid = Uuid::new_v4();
570
571        let e1 = entry_init!(
572            (Attribute::Class, EntryClass::Object.to_value()),
573            (Attribute::Class, EntryClass::Group.to_value()),
574            (Attribute::Name, Value::new_iname("testgroup")),
575            (Attribute::Uuid, Value::Uuid(group_uuid))
576        );
577
578        let e2 = entry_init!(
579            (Attribute::Class, EntryClass::Object.to_value()),
580            (Attribute::Class, EntryClass::Group.to_value()),
581            (Attribute::Name, Value::new_iname("extra_1")),
582            (Attribute::Uuid, Value::Uuid(extra1_uuid))
583        );
584
585        let e3 = entry_init!(
586            (Attribute::Class, EntryClass::Object.to_value()),
587            (Attribute::Class, EntryClass::Group.to_value()),
588            (Attribute::Name, Value::new_iname("extra_2")),
589            (Attribute::Uuid, Value::Uuid(extra2_uuid))
590        );
591
592        let e4 = entry_init!(
593            (Attribute::Class, EntryClass::Object.to_value()),
594            (Attribute::Class, EntryClass::Group.to_value()),
595            (Attribute::Name, Value::new_iname("extra_3")),
596            (Attribute::Uuid, Value::Uuid(extra3_uuid))
597        );
598
599        assert!(server_txn.internal_create(vec![e1, e2, e3, e4]).is_ok());
600
601        // Set attrs
602        let test_mails = vec![
603            ScimMail {
604                primary: true,
605                value: "test@test.test".to_string(),
606            },
607            ScimMail {
608                primary: false,
609                value: "test2@test.test".to_string(),
610            },
611        ];
612        let put = ScimEntryPutKanidm {
613            id: group_uuid,
614            attrs: [
615                (Attribute::Description, Some("Group Description".into())),
616                (
617                    Attribute::Mail,
618                    Some(ScimValueKanidm::Mail(test_mails.clone())),
619                ),
620            ]
621            .into(),
622        };
623
624        let put_generic = put.try_into().unwrap();
625        let put_event =
626            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
627                .expect("Failed to resolve data type");
628
629        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
630        let desc = updated_entry.attrs.get(&Attribute::Description).unwrap();
631        let mails = updated_entry.attrs.get(&Attribute::Mail).unwrap();
632
633        match desc {
634            ScimValueKanidm::String(gdesc) if gdesc == "Group Description" => {}
635            _ => unreachable!("Expected a string"),
636        };
637
638        let ScimValueKanidm::Mail(mails) = mails else {
639            unreachable!("Expected an email")
640        };
641
642        // asserts emails ⊂ test_mails
643        assert!(mails.iter().all(|mail| test_mails.contains(mail)));
644
645        // null removes attr
646        let put = ScimEntryPutKanidm {
647            id: group_uuid,
648            attrs: [(Attribute::Description, None)].into(),
649        };
650
651        let put_generic = put.try_into().unwrap();
652        let put_event =
653            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
654                .expect("Failed to resolve data type");
655
656        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
657        assert!(!updated_entry.attrs.contains_key(&Attribute::Description));
658
659        // set one
660        let put = ScimEntryPutKanidm {
661            id: group_uuid,
662            attrs: [(
663                Attribute::Member,
664                Some(ScimValueKanidm::EntryReferences(vec![ScimReference {
665                    uuid: extra1_uuid,
666                    // Doesn't matter what this is, because there is a UUID, it's ignored
667                    value: String::default(),
668                }])),
669            )]
670            .into(),
671        };
672
673        let put_generic = put.try_into().unwrap();
674        let put_event =
675            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
676                .expect("Failed to resolve data type");
677
678        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
679        let members = updated_entry.attrs.get(&Attribute::Member).unwrap();
680
681        trace!(?members);
682
683        match members {
684            ScimValueKanidm::EntryReferences(member_set) if member_set.len() == 1 => {
685                assert!(member_set.contains(&ScimReference {
686                    uuid: extra1_uuid,
687                    value: "extra_1@example.com".to_string(),
688                }));
689            }
690            _ => unreachable!("Expected 1 member"),
691        };
692
693        // set many
694        let put = ScimEntryPutKanidm {
695            id: group_uuid,
696            attrs: [(
697                Attribute::Member,
698                Some(ScimValueKanidm::EntryReferences(vec![
699                    ScimReference {
700                        uuid: extra1_uuid,
701                        value: String::default(),
702                    },
703                    ScimReference {
704                        uuid: extra2_uuid,
705                        value: String::default(),
706                    },
707                    ScimReference {
708                        uuid: extra3_uuid,
709                        value: String::default(),
710                    },
711                ])),
712            )]
713            .into(),
714        };
715
716        let put_generic = put.try_into().unwrap();
717        let put_event =
718            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
719                .expect("Failed to resolve data type");
720
721        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
722        let members = updated_entry.attrs.get(&Attribute::Member).unwrap();
723
724        trace!(?members);
725
726        match members {
727            ScimValueKanidm::EntryReferences(member_set) if member_set.len() == 3 => {
728                assert!(member_set.contains(&ScimReference {
729                    uuid: extra1_uuid,
730                    value: "extra_1@example.com".to_string(),
731                }));
732                assert!(member_set.contains(&ScimReference {
733                    uuid: extra2_uuid,
734                    value: "extra_2@example.com".to_string(),
735                }));
736                assert!(member_set.contains(&ScimReference {
737                    uuid: extra3_uuid,
738                    value: "extra_3@example.com".to_string(),
739                }));
740            }
741            _ => unreachable!("Expected 3 members"),
742        };
743
744        // set many with a removal
745        let put = ScimEntryPutKanidm {
746            id: group_uuid,
747            attrs: [(
748                Attribute::Member,
749                Some(ScimValueKanidm::EntryReferences(vec![
750                    ScimReference {
751                        uuid: extra1_uuid,
752                        value: String::default(),
753                    },
754                    ScimReference {
755                        uuid: extra3_uuid,
756                        value: String::default(),
757                    },
758                ])),
759            )]
760            .into(),
761        };
762
763        let put_generic = put.try_into().unwrap();
764        let put_event =
765            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
766                .expect("Failed to resolve data type");
767
768        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
769        let members = updated_entry.attrs.get(&Attribute::Member).unwrap();
770
771        trace!(?members);
772
773        match members {
774            ScimValueKanidm::EntryReferences(member_set) if member_set.len() == 2 => {
775                assert!(member_set.contains(&ScimReference {
776                    uuid: extra1_uuid,
777                    value: "extra_1@example.com".to_string(),
778                }));
779                assert!(member_set.contains(&ScimReference {
780                    uuid: extra3_uuid,
781                    value: "extra_3@example.com".to_string(),
782                }));
783                // Member 2 is gone
784                assert!(!member_set.contains(&ScimReference {
785                    uuid: extra2_uuid,
786                    value: "extra_2@example.com".to_string(),
787                }));
788            }
789            _ => unreachable!("Expected 2 members"),
790        };
791
792        // empty set removes attr
793        let put = ScimEntryPutKanidm {
794            id: group_uuid,
795            attrs: [(Attribute::Member, None)].into(),
796        };
797
798        let put_generic = put.try_into().unwrap();
799        let put_event =
800            ScimEntryPutEvent::try_from(idm_admin_ident.clone(), put_generic, &mut server_txn)
801                .expect("Failed to resolve data type");
802
803        let updated_entry = server_txn.scim_put(put_event).expect("Failed to put");
804        assert!(!updated_entry.attrs.contains_key(&Attribute::Member));
805    }
806
807    #[qs_test]
808    async fn scim_assert_basic(server: &QueryServer) {
809        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
810
811        let ident = Identity::migration();
812
813        let uuid_group_1 = Uuid::new_v4();
814        let uuid_group_2 = Uuid::new_v4();
815
816        let asserts = vec![
817            ScimEntryAssertion::Present {
818                id: uuid_group_1,
819                attrs: BTreeMap::from([
820                    (Attribute::Name, Some(JsonValue::String("group_1".into()))),
821                    (
822                        Attribute::Class,
823                        Some(serde_json::to_value(vec!["group"]).unwrap()),
824                    ),
825                    (
826                        Attribute::Member,
827                        Some(serde_json::to_value(ScimClientReference::from("group_2")).unwrap()),
828                    ),
829                ]),
830            },
831            ScimEntryAssertion::Present {
832                id: uuid_group_2,
833                attrs: BTreeMap::from([
834                    (Attribute::Name, Some(JsonValue::String("group_2".into()))),
835                    (
836                        Attribute::Class,
837                        Some(serde_json::to_value(vec!["group"]).unwrap()),
838                    ),
839                    (
840                        Attribute::Member,
841                        Some(serde_json::to_value(ScimClientReference::from("group_1")).unwrap()),
842                    ),
843                ]),
844            },
845        ];
846
847        let scim_assert = ScimAssertEvent {
848            ident,
849            asserts,
850            id: Uuid::new_v4(),
851            nonce: None,
852        };
853
854        server_txn.scim_assert(scim_assert).expect("Must not fail!");
855    }
856}