Skip to main content

kanidmd_lib/idm/
scim.rs

1use crate::{
2    credential::totp::{Totp, TotpAlgo, TotpDigits},
3    idm::server::{IdmServerProxyReadTransaction, IdmServerProxyWriteTransaction},
4    prelude::*,
5    schema::{SchemaClass, SchemaTransaction},
6    value::ApiToken,
7    valueset::ValueSetDateTime,
8};
9use base64::{
10    engine::general_purpose::{STANDARD, URL_SAFE},
11    Engine as _,
12};
13use compact_jwt::{Jws, JwsCompact};
14use kanidm_proto::{
15    internal::{ApiTokenPurpose, ScimSyncToken},
16    scim_v1::*,
17    v1::OutboundMessage,
18};
19use sshkey_attest::proto::PublicKey as SshPublicKey;
20use std::{
21    collections::{BTreeMap, BTreeSet},
22    time::Duration,
23};
24use time::OffsetDateTime;
25
26// Internals of a Scim Sync token
27
28#[allow(dead_code)]
29pub(crate) struct SyncAccount {
30    pub name: String,
31    pub uuid: Uuid,
32    pub sync_tokens: BTreeMap<Uuid, ApiToken>,
33}
34
35macro_rules! try_from_entry {
36    ($value:expr) => {{
37        // Check the classes
38        if !$value.attribute_equality(Attribute::Class, &EntryClass::SyncAccount.into()) {
39            return Err(OperationError::MissingClass(ENTRYCLASS_SYNC_ACCOUNT.into()));
40        }
41
42        let name = $value
43            .get_ava_single_iname(Attribute::Name)
44            .map(|s| s.to_string())
45            .ok_or(OperationError::MissingAttribute(Attribute::Name))?;
46
47        let sync_tokens = $value
48            .get_ava_as_apitoken_map(Attribute::SyncTokenSession)
49            .cloned()
50            .unwrap_or_default();
51
52        let uuid = $value.get_uuid().clone();
53
54        Ok(SyncAccount {
55            name,
56            uuid,
57            sync_tokens,
58        })
59    }};
60}
61
62impl SyncAccount {
63    #[instrument(level = "debug", skip_all)]
64    pub(crate) fn try_from_entry_rw(
65        value: &Entry<EntrySealed, EntryCommitted>,
66        // qs: &mut QueryServerWriteTransaction,
67    ) -> Result<Self, OperationError> {
68        // let groups = Group::try_from_account_entry_rw(value, qs)?;
69        try_from_entry!(value)
70    }
71
72    pub(crate) fn check_sync_token_valid(
73        _ct: Duration,
74        sst: &ScimSyncToken,
75        entry: &Entry<EntrySealed, EntryCommitted>,
76    ) -> bool {
77        let valid_purpose = matches!(sst.purpose, ApiTokenPurpose::Synchronise);
78
79        // Get the sessions. There are no gracewindows on sync, we are much stricter.
80        let session_present = entry
81            .get_ava_as_apitoken_map(Attribute::SyncTokenSession)
82            .map(|session_map| session_map.get(&sst.token_id).is_some())
83            .unwrap_or(false);
84
85        debug!(?session_present, valid_purpose);
86
87        session_present && valid_purpose
88    }
89}
90
91// Need to create a Sync input source
92//
93
94pub struct GenerateScimSyncTokenEvent {
95    // Who initiated this?
96    pub ident: Identity,
97    // Who is it targeting?
98    pub target: Uuid,
99    // The label
100    pub label: String,
101}
102
103impl GenerateScimSyncTokenEvent {
104    #[cfg(test)]
105    pub fn new_internal(target: Uuid, label: &str) -> Self {
106        GenerateScimSyncTokenEvent {
107            ident: Identity::from_internal(),
108            target,
109            label: label.to_string(),
110        }
111    }
112}
113
114impl IdmServerProxyWriteTransaction<'_> {
115    pub fn scim_sync_generate_token(
116        &mut self,
117        gte: &GenerateScimSyncTokenEvent,
118        ct: Duration,
119    ) -> Result<JwsCompact, OperationError> {
120        let session_id = Uuid::new_v4();
121        let issued_at = time::OffsetDateTime::UNIX_EPOCH + ct;
122
123        let scope = ApiTokenScope::Synchronise;
124        let purpose = scope.try_into()?;
125
126        let session = Value::ApiToken(
127            session_id,
128            ApiToken {
129                label: gte.label.clone(),
130                expiry: None,
131                // Need the other inner bits?
132                // for the gracewindow.
133                issued_at,
134                // Who actually created this?
135                issued_by: gte.ident.get_event_origin_id(),
136                // What is the access scope of this session? This is
137                // for auditing purposes.
138                scope,
139            },
140        );
141
142        let scim_sync_token = ScimSyncToken {
143            token_id: session_id,
144            issued_at,
145            purpose,
146        };
147
148        let token = Jws::into_json(&scim_sync_token).map_err(|err| {
149            error!(?err, "Unable to serialise JWS");
150            OperationError::SerdeJsonError
151        })?;
152
153        let modlist =
154            ModifyList::new_list(vec![Modify::Present(Attribute::SyncTokenSession, session)]);
155
156        self.qs_write
157            .impersonate_modify(
158                // Filter as executed
159                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(gte.target))),
160                // Filter as intended (acp)
161                &filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(gte.target))),
162                &modlist,
163                // Provide the event to impersonate
164                &gte.ident,
165            )
166            .map_err(|err| {
167                error!(?err, "Failed to generate sync token");
168                err
169            })?;
170
171        // The modify succeeded and was allowed, now sign the token for return.
172        self.qs_write
173            .get_domain_key_object_handle()?
174            .jws_es256_sign(&token, ct)
175        // Done!
176    }
177
178    pub fn sync_account_destroy_token(
179        &mut self,
180        ident: &Identity,
181        target: Uuid,
182        _ct: Duration,
183    ) -> Result<(), OperationError> {
184        let modlist = ModifyList::new_list(vec![Modify::Purged(Attribute::SyncTokenSession)]);
185
186        self.qs_write
187            .impersonate_modify(
188                // Filter as executed
189                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
190                // Filter as intended (acp)
191                &filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(target))),
192                &modlist,
193                // Provide the event to impersonate
194                ident,
195            )
196            .map_err(|e| {
197                admin_error!("Failed to destroy api token {:?}", e);
198                e
199            })
200    }
201
202    pub fn scim_person_message_send_test(
203        &mut self,
204        ident: &Identity,
205        target: Uuid,
206    ) -> Result<Uuid, OperationError> {
207        // Get the target entry.
208        let target_entry = self.qs_write.impersonate_search_uuid(target, ident)?;
209
210        let display_name = target_entry
211            .get_ava_single_utf8(Attribute::DisplayName)
212            .map(String::from)
213            .ok_or(OperationError::MissingAttribute(Attribute::DisplayName))?;
214
215        let mail_primary = target_entry
216            .get_ava_mail_primary(Attribute::Mail)
217            .map(String::from)
218            .ok_or(OperationError::MissingAttribute(Attribute::Mail))?;
219
220        // Create a message to send.
221        self.qs_write.queue_message(
222            ident,
223            OutboundMessage::TestMessageV1 { display_name },
224            mail_primary,
225        )
226    }
227
228    pub fn scim_message_mark_sent(
229        &mut self,
230        ident: &Identity,
231        message_id: Uuid,
232    ) -> Result<(), OperationError> {
233        let curtime_odt = self.qs_write.get_curtime_odt();
234
235        let filter = filter_all!(f_and(vec![
236            f_eq(Attribute::Uuid, PartialValue::Uuid(message_id)),
237            f_eq(Attribute::Class, EntryClass::OutboundMessage.into())
238        ]));
239
240        let modlist = ModifyList::new_set(Attribute::SentAt, ValueSetDateTime::new(curtime_odt));
241        let modify_event =
242            ModifyEvent::from_internal_parts(ident.clone(), &modlist, &filter, &self.qs_write)?;
243
244        self.qs_write.modify(&modify_event)
245    }
246
247    pub fn scim_message_mark_resend(
248        &mut self,
249        ident: &Identity,
250        message_id: Uuid,
251    ) -> Result<(), OperationError> {
252        let filter = filter_all!(f_and(vec![
253            f_eq(Attribute::Uuid, PartialValue::Uuid(message_id)),
254            f_eq(Attribute::Class, EntryClass::OutboundMessage.into())
255        ]));
256
257        let modlist = ModifyList::new_purge(Attribute::SentAt);
258        let modify_event =
259            ModifyEvent::from_internal_parts(ident.clone(), &modlist, &filter, &self.qs_write)?;
260
261        self.qs_write.modify(&modify_event)
262    }
263
264    pub fn scim_feature_enable(
265        &mut self,
266        ident: &Identity,
267        feature_id: Uuid,
268        enabled: bool,
269    ) -> Result<(), OperationError> {
270        let filter = filter_all!(f_and(vec![
271            f_eq(Attribute::Uuid, PartialValue::Uuid(feature_id)),
272            f_eq(Attribute::Class, EntryClass::Feature.into())
273        ]));
274
275        let modlist = ModifyList::new_set(Attribute::Enabled, ValueSetBool::new(enabled));
276        let modify_event =
277            ModifyEvent::from_internal_parts(ident.clone(), &modlist, &filter, &self.qs_write)?;
278
279        self.qs_write.modify(&modify_event)
280    }
281}
282
283pub struct ScimSyncFinaliseEvent {
284    pub ident: Identity,
285    pub target: Uuid,
286}
287
288impl IdmServerProxyWriteTransaction<'_> {
289    pub fn scim_sync_finalise(
290        &mut self,
291        sfe: &ScimSyncFinaliseEvent,
292    ) -> Result<(), OperationError> {
293        // Get the target and ensure it's really a sync account
294        let entry = self
295            .qs_write
296            .internal_search_uuid(sfe.target)
297            .map_err(|e| {
298                admin_error!(?e, "Failed to search sync account");
299                e
300            })?;
301
302        let sync_account = SyncAccount::try_from_entry_rw(&entry).map_err(|e| {
303            admin_error!(?e, "Failed to convert sync account");
304            e
305        })?;
306        let sync_uuid = sync_account.uuid;
307
308        // Do we have permission to delete it?
309        let effective_perms = self
310            .qs_write
311            .get_accesscontrols()
312            .effective_permission_check(&sfe.ident, Some(BTreeSet::default()), &[entry])?;
313
314        let eperm = effective_perms.first().ok_or_else(|| {
315            admin_error!("Effective Permission check returned no results");
316            OperationError::InvalidState
317        })?;
318
319        if eperm.target != sync_account.uuid {
320            admin_error!("Effective Permission check target differs from requested entry uuid");
321            return Err(OperationError::InvalidEntryState);
322        }
323
324        // ⚠️  Assume that anything before this line is unauthorised, and after this line IS
325        // authorised!
326        //
327        // We do this check via effective permissions because a lot of the operations that
328        // follow will require permissions beyond what system admins have.
329
330        if !eperm.delete {
331            security_info!(
332                "Requester {} does not have permission to delete sync account {}",
333                sfe.ident,
334                sync_account.name
335            );
336            return Err(OperationError::NotAuthorised);
337        }
338
339        // Referential integrity tries to assert that the reference to sync_parent_uuid is valid
340        // from within the recycle bin. To prevent this, we have to "finalise" first, transfer
341        // authority to kanidm, THEN we do the delete which breaks the reference requirement.
342        //
343        // Importantly, we have to do this for items that are in the recycle bin!
344
345        // First, get the set of uuids that exist. We need this so we have the set of uuids we'll
346        // be deleting *at the end*.
347        let f_all_sync = filter_all!(f_and!([
348            f_eq(Attribute::Class, EntryClass::SyncObject.into()),
349            f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid))
350        ]));
351
352        // TODO: This could benefit from a search that only grabs uuids?
353        let existing_entries = self
354            .qs_write
355            .internal_exists(&f_all_sync)
356            .inspect_err(|_e| {
357                error!("Failed to determine existing entries set");
358            })?;
359
360        /*
361        let filter_or: Vec<_> = existing_entries
362            .iter()
363            .map(|e| f_eq(Attribute::Uuid, PartialValue::Uuid(e.get_uuid())))
364            .collect();
365        */
366
367        // We only need to delete the sync account itself.
368        let delete_filter = filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(sync_uuid)));
369
370        if existing_entries {
371            // Now modify these to remove their sync related attributes.
372            let schema = self.qs_write.get_schema();
373            let sync_class = schema
374                .get_classes()
375                .get(EntryClass::SyncObject.into())
376                .ok_or_else(|| {
377                    error!(
378                        "Failed to access {} class, schema corrupt",
379                        EntryClass::SyncObject
380                    );
381                    OperationError::InvalidState
382                })?;
383
384            let modlist = std::iter::once(Modify::Removed(
385                Attribute::Class,
386                EntryClass::SyncObject.into(),
387            ))
388            .chain(
389                sync_class
390                    .may_iter()
391                    .map(|aname| Modify::Purged(aname.clone())),
392            )
393            .collect();
394
395            let mods = ModifyList::new_list(modlist);
396
397            self.qs_write
398                .internal_modify(&f_all_sync, &mods)
399                .inspect_err(|_e| {
400                    error!("Failed to modify sync objects to grant authority to kanidm");
401                })?;
402        };
403
404        self.qs_write
405            .internal_delete(&delete_filter)
406            .inspect_err(|e| {
407                error!(?e, "Failed to terminate sync account");
408            })
409    }
410}
411
412pub struct ScimSyncTerminateEvent {
413    pub ident: Identity,
414    pub target: Uuid,
415}
416
417impl IdmServerProxyWriteTransaction<'_> {
418    pub fn scim_sync_terminate(
419        &mut self,
420        ste: &ScimSyncTerminateEvent,
421    ) -> Result<(), OperationError> {
422        // Get the target and ensure it's really a sync account
423        let entry = self
424            .qs_write
425            .internal_search_uuid(ste.target)
426            .inspect_err(|e| {
427                admin_error!(?e, "Failed to search sync account");
428            })?;
429
430        let sync_account = SyncAccount::try_from_entry_rw(&entry).map_err(|e| {
431            admin_error!(?e, "Failed to convert sync account");
432            e
433        })?;
434        let sync_uuid = sync_account.uuid;
435
436        // Do we have permission to delete it?
437        let effective_perms = self
438            .qs_write
439            .get_accesscontrols()
440            .effective_permission_check(&ste.ident, Some(BTreeSet::default()), &[entry])?;
441
442        let eperm = effective_perms.first().ok_or_else(|| {
443            admin_error!("Effective Permission check returned no results");
444            OperationError::InvalidState
445        })?;
446
447        if eperm.target != sync_account.uuid {
448            admin_error!("Effective Permission check target differs from requested entry uuid");
449            return Err(OperationError::InvalidEntryState);
450        }
451
452        // ⚠️  Assume that anything before this line is unauthorised, and after this line IS
453        // authorised!
454        //
455        // We do this check via effective permissions because a lot of the operations that
456        // follow will require permissions beyond what system admins have.
457
458        if !eperm.delete {
459            security_info!(
460                "Requester {} does not have permission to delete sync account {}",
461                ste.ident,
462                sync_account.name
463            );
464            return Err(OperationError::NotAuthorised);
465        }
466
467        // Referential integrity tries to assert that the reference to sync_parent_uuid is valid
468        // from within the recycle bin. To prevent this, we have to "finalise" first, transfer
469        // authority to kanidm, THEN we do the delete which breaks the reference requirement.
470        //
471        // Importantly, we have to do this for items that are in the recycle bin!
472
473        // First, get the set of uuids that exist. We need this so we have the set of uuids we'll
474        // be deleting *at the end*.
475        let f_all_sync = filter_all!(f_and!([
476            f_eq(Attribute::Class, EntryClass::SyncObject.into()),
477            f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid))
478        ]));
479
480        // TODO: This could benefit from a search that only grabs uuids?
481        let existing_entries = self
482            .qs_write
483            .internal_search(f_all_sync.clone())
484            .inspect_err(|err| {
485                error!(?err, "Failed to determine existing entries set");
486            })?;
487
488        let delete_filter = if existing_entries.is_empty() {
489            // We only need to delete the sync account itself.
490            filter!(f_eq(Attribute::Uuid, PartialValue::Uuid(sync_uuid)))
491        } else {
492            // This is the delete filter we need later.
493            let filter_or: Vec<_> = existing_entries
494                .iter()
495                .map(|e| f_eq(Attribute::Uuid, PartialValue::Uuid(e.get_uuid())))
496                .collect();
497
498            // Now modify these to remove their sync related attributes.
499            let schema = self.qs_write.get_schema();
500            let sync_class = schema
501                .get_classes()
502                .get(EntryClass::SyncObject.into())
503                .ok_or_else(|| {
504                    error!(
505                        "Failed to access {} class, schema corrupt",
506                        EntryClass::SyncObject
507                    );
508                    OperationError::InvalidState
509                })?;
510
511            let modlist = std::iter::once(Modify::Removed(
512                Attribute::Class,
513                EntryClass::SyncObject.into(),
514            ))
515            .chain(
516                sync_class
517                    .may_iter()
518                    .map(|aname| Modify::Purged(aname.clone())),
519            )
520            .collect();
521
522            let mods = ModifyList::new_list(modlist);
523
524            self.qs_write
525                .internal_modify(&f_all_sync, &mods)
526                .inspect_err(|err| {
527                    error!(
528                        ?err,
529                        "Failed to modify sync objects to grant authority to Kanidm"
530                    );
531                })?;
532
533            filter!(f_or!([
534                f_eq(Attribute::Uuid, PartialValue::Uuid(sync_uuid)),
535                f_or(filter_or)
536            ]))
537        };
538
539        self.qs_write.internal_delete(&delete_filter).map_err(|e| {
540            error!(?e, "Failed to terminate sync account");
541            e
542        })
543    }
544}
545
546pub struct ScimSyncUpdateEvent {
547    pub ident: Identity,
548}
549
550impl IdmServerProxyWriteTransaction<'_> {
551    #[instrument(level = "info", skip_all)]
552    pub fn scim_sync_apply(
553        &mut self,
554        sse: &ScimSyncUpdateEvent,
555        changes: &ScimSyncRequest,
556        _ct: Duration,
557    ) -> Result<(), OperationError> {
558        let (sync_uuid, sync_authority_set, change_entries, sync_refresh) =
559            self.scim_sync_apply_phase_1(sse, changes)?;
560
561        // TODO: If the from_state is refresh and the to_state is active, then we need to
562        // do delete all entries NOT present in the refresh set.
563        // This accounts for the state of:
564        //      active -> refresh -> active
565        // which can occur when ldap asks us to do a refresh. Because of this entries may have
566        // been removed, and will NOT be present in a delete_uuids phase. We can't just blanket
567        // delete here as some entries may have been modified by users with authority over the
568        // attributes.
569
570        self.scim_sync_apply_phase_2(&change_entries, sync_uuid)?;
571
572        // Remove dangling entries if this is a refresh operation.
573        if sync_refresh {
574            self.scim_sync_apply_phase_refresh_cleanup(&change_entries, sync_uuid)?;
575        }
576
577        // All stubs are now set-up. We can proceed to assert entry content.
578        self.scim_sync_apply_phase_3(&change_entries, sync_uuid, &sync_authority_set)?;
579
580        // Remove entries that now need deletion, We do this post assert in case an
581        // entry was mistakenly ALSO in the assert set.
582        self.scim_sync_apply_phase_4(&changes.retain, sync_uuid)?;
583
584        // Final house keeping. Commit the new sync state.
585        self.scim_sync_apply_phase_5(sync_uuid, &changes.to_state)?;
586
587        info!("success");
588
589        Ok(())
590    }
591
592    #[instrument(level = "info", skip_all)]
593    fn scim_sync_apply_phase_1<'b>(
594        &mut self,
595        sse: &'b ScimSyncUpdateEvent,
596        changes: &'b ScimSyncRequest,
597    ) -> Result<
598        (
599            Uuid,
600            BTreeSet<Attribute>,
601            BTreeMap<Uuid, &'b ScimEntry>,
602            bool,
603        ),
604        OperationError,
605    > {
606        // Assert the token is valid.
607        let sync_uuid = match &sse.ident.origin {
608            IdentType::User(_) | IdentType::Internal(_) => {
609                warn!("Ident type is not synchronise");
610                return Err(OperationError::AccessDenied);
611            }
612            IdentType::Synch(u) => {
613                // Ok!
614                *u
615            }
616        };
617
618        match sse.ident.access_scope() {
619            AccessScope::ReadOnly | AccessScope::ReadWrite => {
620                warn!("Ident access scope is not synchronise");
621                return Err(OperationError::AccessDenied);
622            }
623            AccessScope::Synchronise => {
624                // As you were
625            }
626        };
627
628        // Retrieve the related sync entry.
629        let sync_entry = self
630            .qs_write
631            .internal_search_uuid(sync_uuid)
632            .inspect_err(|err| {
633                error!(
634                    ?err,
635                    "Failed to located sync entry related to {}", sync_uuid
636                );
637            })?;
638
639        // Assert that the requested "from" state is consistent to this entry.
640        // OperationError::InvalidSyncState
641
642        match (
643            &changes.from_state,
644            sync_entry.get_ava_single_private_binary(Attribute::SyncCookie),
645        ) {
646            (ScimSyncState::Refresh, _) => {
647                // valid
648                info!("Refresh Sync");
649            }
650            (ScimSyncState::Active { cookie }, Some(sync_cookie)) => {
651                // Check cookies.
652                if cookie != sync_cookie {
653                    // Invalid
654                    error!(
655                        "Invalid Sync State - Active, but agreement has divegent external cookie."
656                    );
657                    return Err(OperationError::InvalidSyncState);
658                } else {
659                    // Valid
660                    info!("Active Sync with valid cookie");
661                }
662            }
663            (ScimSyncState::Active { cookie: _ }, None) => {
664                error!("Invalid Sync State - Sync Tool Reports Active, but agreement has Refresh Required. You can resync the agreement with `kanidm system sync force-refresh`");
665                return Err(OperationError::InvalidSyncState);
666            }
667        };
668
669        let sync_refresh = matches!(&changes.from_state, ScimSyncState::Refresh);
670
671        // Get the sync authority set from the entry.
672        let sync_authority_set: BTreeSet<Attribute> = sync_entry
673            .get_ava_as_iutf8(Attribute::SyncYieldAuthority)
674            .map(|set| set.iter().map(|s| Attribute::from(s.as_str())).collect())
675            .unwrap_or_default();
676
677        // Transform the changes into something that supports lookups.
678        let change_entries: BTreeMap<Uuid, &ScimEntry> = changes
679            .entries
680            .iter()
681            .map(|scim_entry| (scim_entry.id, scim_entry))
682            .collect();
683
684        Ok((sync_uuid, sync_authority_set, change_entries, sync_refresh))
685    }
686
687    #[instrument(level = "info", skip_all)]
688    pub(crate) fn scim_sync_apply_phase_2(
689        &mut self,
690        change_entries: &BTreeMap<Uuid, &ScimEntry>,
691        sync_uuid: Uuid,
692    ) -> Result<(), OperationError> {
693        if change_entries.is_empty() {
694            info!("No change_entries requested");
695            return Ok(());
696        }
697
698        // First, search for all uuids present in the change set.
699        // Note - we don't check the delete_uuids set here, that's done later. We use that
700        // differently as we are somewhat more forgiving about reqs to delete uuids that are
701        // already delete/tombstoned, or outside of the scope of this sync agreement.
702        let filter_or = change_entries
703            .keys()
704            .copied()
705            .map(|u| f_eq(Attribute::Uuid, PartialValue::Uuid(u)))
706            .collect();
707
708        // NOTE: We bypass recycled/ts here because we WANT to know if we are in that
709        // state so we can AVOID updates to these entries!
710        let existing_entries = self
711            .qs_write
712            .internal_search(filter_all!(f_or(filter_or)))
713            .inspect_err(|err| {
714                error!(?err, "Failed to determine existing entries set");
715            })?;
716
717        // Refuse to proceed if any entries are in the recycled or tombstone state, since subsequent
718        // operations WOULD fail.
719        //
720        // I'm still a bit not sure what to do here though, because if we have uuid reuse from the
721        // external system, that would be a pain, but I think we have to do this. This would be an
722        // exceedingly rare situation though since 389-ds doesn't allow external uuid to be set, nor
723        // does openldap. It would break both of their replication models for it to occur.
724        //
725        // Still we cover the possibility
726        let mut fail = false;
727        existing_entries.iter().for_each(|e| {
728            if e.mask_recycled_ts().is_none() {
729                error!("Unable to proceed: entry uuid {} ({}) is masked. You must re-map this entries uuid in the sync connector to proceed.", e.get_uuid(), e.get_display_id());
730                fail = true;
731            }
732        });
733        if fail {
734            return Err(OperationError::InvalidEntryState);
735        }
736        // From that set of entries, partition to entries that exist and are
737        // present, and entries that do not yet exist.
738        //
739        // We can't easily parititon here because we need to iterate over the
740        // existing entry set to work out what we need, so what we do is copy
741        // the change_entries set, then remove what we already have.
742        let mut missing_scim = change_entries.clone();
743        existing_entries.iter().for_each(|entry| {
744            missing_scim.remove(&entry.get_uuid());
745        });
746
747        // For entries that do not exist, create stub entries. We don't create the external ID here
748        // yet, because we need to ensure that it's unique.
749        let create_stubs: Vec<EntryInitNew> = missing_scim
750            .keys()
751            .copied()
752            .map(|u| {
753                entry_init!(
754                    (Attribute::Class, EntryClass::Object.to_value()),
755                    (Attribute::Class, EntryClass::SyncObject.to_value()),
756                    (Attribute::SyncParentUuid, Value::Refer(sync_uuid)),
757                    (Attribute::Uuid, Value::Uuid(u))
758                )
759            })
760            .collect();
761
762        // We use internal create here to ensure that the values of these entries are all setup correctly.
763        // We know that uuid won't conflict because it didn't exist in the previous search, so if we error
764        // it has to be something bad.
765        if !create_stubs.is_empty() {
766            self.qs_write
767                .internal_create(create_stubs)
768                .inspect_err(|err| {
769                    error!(?err, "Unable to create stub entries");
770                })?;
771        }
772
773        // We have to search again now, this way we can do the internal mod process for
774        // updating the external_id.
775        //
776        // For entries that do exist, mod their external_id
777        //
778        // Basically we just set this up as a batch modify and submit it.
779        self.qs_write
780            .internal_batch_modify(change_entries.iter().filter_map(|(u, scim_ent)| {
781                // If the entry has an external id
782                scim_ent.external_id.as_ref().map(|ext_id| {
783                    // Add it to the mod request.
784                    (
785                        *u,
786                        ModifyList::new_list(vec![
787                            Modify::Assert(
788                                Attribute::SyncParentUuid,
789                                PartialValue::Refer(sync_uuid),
790                            ),
791                            Modify::Purged(Attribute::SyncExternalId),
792                            Modify::Present(Attribute::SyncExternalId, Value::new_iutf8(ext_id)),
793                        ]),
794                    )
795                })
796            }))
797            .inspect_err(|err| {
798                error!(?err, "Unable to setup external ids from sync entries");
799            })?;
800
801        // Ready to go.
802
803        Ok(())
804    }
805
806    #[instrument(level = "info", skip_all)]
807    pub(crate) fn scim_sync_apply_phase_refresh_cleanup(
808        &mut self,
809        change_entries: &BTreeMap<Uuid, &ScimEntry>,
810        sync_uuid: Uuid,
811    ) -> Result<(), OperationError> {
812        // If this is a refresh, then the providing server is sending a full state of entries
813        // and what state they should be in. This means that a situation can exist where on the
814        // supplier you have:
815        //
816        //    Supplier           Kanidm
817        //    Add X
818        //    Sync X   ---------> X
819        //    Delete X
820        //    Refresh  --------->
821        //
822        // Since the delete uuid event wouldn't be sent, we need to ensure that Kanidm will clean
823        // up entries that are *not* present in the change set here.
824        //
825        // To achieve this we do a delete where the condition is sync parent and not in the change
826        // entry set.
827        let filter_or = change_entries
828            .keys()
829            .copied()
830            .map(|u| f_eq(Attribute::Uuid, PartialValue::Uuid(u)))
831            .collect::<Vec<_>>();
832
833        let delete_filter = if filter_or.is_empty() {
834            filter!(f_and!([
835                // Must be part of this sync agreement.
836                f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid))
837            ]))
838        } else {
839            filter!(f_and!([
840                // Must be part of this sync agreement.
841                f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid)),
842                // Must not be an entry in the change set.
843                f_andnot(f_or(filter_or))
844            ]))
845        };
846
847        self.qs_write
848            .internal_delete(&delete_filter)
849            .or_else(|err| {
850                // Skip if there is nothing to do
851                if err == OperationError::NoMatchingEntries {
852                    Ok(())
853                } else {
854                    Err(err)
855                }
856            })
857            .map_err(|e| {
858                error!(?e, "Failed to delete dangling uuids");
859                e
860            })
861    }
862
863    fn scim_attr_to_values(
864        &mut self,
865        scim_attr_name: &Attribute,
866        scim_attr: &ScimValue,
867    ) -> Result<ValueSet, OperationError> {
868        let schema = self.qs_write.get_schema();
869
870        let attr_schema = schema.get_attributes().get(scim_attr_name).ok_or_else(|| {
871            OperationError::InvalidAttribute(format!(
872                "No such attribute in schema - {scim_attr_name}"
873            ))
874        })?;
875
876        match (attr_schema.syntax, attr_schema.multivalue, scim_attr) {
877            (
878                SyntaxType::Utf8StringIname,
879                false,
880                ScimValue::Simple(ScimAttr::String(value)),
881            ) => Ok(ValueSetIname::new(value) as _),
882            (
883                SyntaxType::Utf8String,
884                false,
885                ScimValue::Simple(ScimAttr::String(value)),
886            ) => Ok(ValueSetUtf8::new(value.clone())),
887            (
888                SyntaxType::Utf8StringInsensitive,
889                false,
890                ScimValue::Simple(ScimAttr::String(value)),
891            ) => Ok(ValueSetIutf8::new(value)),
892            (
893                SyntaxType::Uint32,
894                false,
895                ScimValue::Simple(ScimAttr::Integer(int_value)),
896            ) => u32::try_from(*int_value).map_err(|_| {
897                    error!("Invalid value - not within the bounds of a u32");
898                    OperationError::InvalidAttribute(format!(
899                        "Out of bounds unsigned integer - {scim_attr_name}"
900                    ))
901                })
902                .map(|v| ValueSetUint32::new(v) as ValueSet),
903            (SyntaxType::ReferenceUuid, false,
904                ScimValue::Simple(ScimAttr::String(value)),
905            ) => {
906                let maybe_uuid =
907                    self.qs_write.sync_external_id_to_uuid(value).map_err(|e| {
908                        error!(?e, "Unable to resolve external_id to uuid");
909                        e
910                    })?;
911
912                if let Some(uuid) = maybe_uuid {
913                    Ok(ValueSetRefer::new(uuid) as ValueSet)
914                } else {
915                    debug!("Could not convert external_id to reference - {}", value);
916                    Err(OperationError::InvalidAttribute(format!(
917                        "Reference uuid must a uuid or external_id - {scim_attr_name}"
918                    )))
919                }
920            }
921            (SyntaxType::ReferenceUuidN, true, ScimValue::MultiComplex(values)) => {
922                // In this case, because it's a reference uuid only, despite the multicomplex structure, it's a list of
923                // "external_id" to external_ids. These *might* also be uuids. So we need to use sync_external_id_to_uuid
924                // here to resolve things.
925                //
926                // This is why in phase 2 we "precreate" all objects to make sure they resolve.
927                //
928                // If an id does NOT resolve, we warn and SKIP since it's possible it may have been filtered.
929
930                let mut vs = Vec::with_capacity(values.len());
931                for complex in values.iter() {
932                    let external_id = complex.get("external_id").ok_or_else(|| {
933                        error!("Invalid scim complex attr - missing required key external_id");
934                        OperationError::InvalidAttribute(format!(
935                            "missing required key external_id - {scim_attr_name}"
936                        ))
937                    })?;
938
939                    let value = match external_id {
940                        ScimAttr::String(value) => Ok(value.as_str()),
941                        _ => {
942                            error!("Invalid external_id attribute - must be scim simple string");
943                            Err(OperationError::InvalidAttribute(format!(
944                                "external_id must be scim simple string - {scim_attr_name}"
945                            )))
946                        }
947                    }?;
948
949                    let maybe_uuid =
950                        self.qs_write.sync_external_id_to_uuid(value).map_err(|e| {
951                            error!(?e, "Unable to resolve external_id to uuid");
952                            e
953                        })?;
954
955                    if let Some(uuid) = maybe_uuid {
956                        vs.push(uuid)
957                    } else {
958                        debug!("Could not convert external_id to reference - {}", value);
959                    }
960                }
961
962                ValueSetReferN::from_iter(vs)
963                    .map(|vs| vs as ValueSet)
964                    .ok_or_else(|| {
965                                error!("Unable to convert to valueset");
966                                OperationError::InvalidAttribute(format!(
967                                    "invalid reference set - {scim_attr_name}"
968                                ))
969                    })
970
971            }
972            (SyntaxType::TotpSecret, true, ScimValue::MultiComplex(values)) => {
973                // We have to break down each complex value into a totp.
974                let mut vs = Vec::with_capacity(values.len());
975                for complex in values.iter() {
976                    let external_id = complex
977                        .get("external_id")
978                        .ok_or_else(|| {
979                            error!("Invalid scim complex attr - missing required key external_id");
980                            OperationError::InvalidAttribute(format!(
981                                "missing required key external_id - {scim_attr_name}"
982                            ))
983                        })
984                        .and_then(|external_id| match external_id {
985                            ScimAttr::String(value) => Ok(value.clone()),
986                            _ => {
987                                error!(
988                                    "Invalid external_id attribute - must be scim simple string"
989                                );
990                                Err(OperationError::InvalidAttribute(format!(
991                                    "external_id must be scim simple string - {scim_attr_name}"
992                                )))
993                            }
994                        })?;
995
996                    let secret = complex
997                        .get(SCIM_SECRET)
998                        .ok_or_else(|| {
999                            error!("Invalid SCIM complex attr - missing required key secret");
1000                            OperationError::InvalidAttribute(format!(
1001                                "missing required key secret - {scim_attr_name}"
1002                            ))
1003                        })
1004                        .and_then(|secret| match secret {
1005                            ScimAttr::String(value) => {
1006                                URL_SAFE.decode(value.as_str()).or_else(
1007                                    |_| STANDARD.decode(value.as_str())
1008                                )
1009                                    .map_err(|_| {
1010                                        error!("Invalid secret attribute - must be base64 string");
1011                                        OperationError::InvalidAttribute(format!(
1012                                            "secret must be base64 string - {scim_attr_name}"
1013                                        ))
1014                                    })
1015                            }
1016                            _ => {
1017                                error!("Invalid secret attribute - must be scim simple string");
1018                                Err(OperationError::InvalidAttribute(format!(
1019                                    "secret must be scim simple string - {scim_attr_name}"
1020                                )))
1021                            }
1022                        })?;
1023
1024                    let algo = complex.get(SCIM_ALGO)
1025                        .ok_or_else(|| {
1026                            error!("Invalid scim complex attr - missing required key algo");
1027                            OperationError::InvalidAttribute(format!(
1028                                "missing required key algo - {scim_attr_name}"
1029                            ))
1030                        })
1031                        .and_then(|algo_str| {
1032                            match algo_str {
1033                                ScimAttr::String(value) => {
1034                                    match value.as_str() {
1035                                        "sha1" => Ok(TotpAlgo::Sha1),
1036                                        "sha256" => Ok(TotpAlgo::Sha256),
1037                                        "sha512" => Ok(TotpAlgo::Sha512),
1038                                        _ => {
1039                                            error!("Invalid algo attribute - must be one of sha1, sha256 or sha512");
1040                                            Err(OperationError::InvalidAttribute(format!(
1041                                                "algo must be one of sha1, sha256 or sha512 - {scim_attr_name}"
1042                                            )))
1043                                        }
1044                                    }
1045                                }
1046                                _ => {
1047                                    error!("Invalid algo attribute - must be scim simple string");
1048                                    Err(OperationError::InvalidAttribute(format!(
1049                                        "algo must be scim simple string - {scim_attr_name}"
1050                                    )))
1051                                }
1052                            }
1053                        })?;
1054
1055                    let step = complex.get(SCIM_STEP).ok_or_else(|| {
1056                        error!("Invalid scim complex attr - missing required key step");
1057                        OperationError::InvalidAttribute(format!(
1058                            "missing required key step - {scim_attr_name}"
1059                        ))
1060                    }).and_then(|step| {
1061                        match step {
1062                            ScimAttr::Integer(s) if *s >= 30 => Ok(*s as u64),
1063                            _ =>
1064                                Err(OperationError::InvalidAttribute(format!(
1065                                    "step must be a positive integer value equal to or greater than 30 - {scim_attr_name}"
1066                                ))),
1067                        }
1068                    })?;
1069
1070                    let digits = complex
1071                        .get(SCIM_DIGITS)
1072                        .ok_or_else(|| {
1073                            error!("Invalid scim complex attr - missing required key digits");
1074                            OperationError::InvalidAttribute(format!(
1075                                "missing required key digits - {scim_attr_name}"
1076                            ))
1077                        })
1078                        .and_then(|digits| match digits {
1079                            ScimAttr::Integer(6) => Ok(TotpDigits::Six),
1080                            ScimAttr::Integer(8) => Ok(TotpDigits::Eight),
1081                            _ => {
1082                                error!("Invalid digits attribute - must be scim simple integer with the value 6 or 8");
1083                                Err(OperationError::InvalidAttribute(format!(
1084                                    "digits must be a positive integer value of 6 OR 8 - {scim_attr_name}"
1085                                )))
1086                            }
1087                        })?;
1088
1089                    let totp = Totp::new(secret, step, algo, digits);
1090                    vs.push((external_id, totp))
1091                }
1092
1093                ValueSetTotpSecret::from_iter(vs)
1094                    .map(|vs| vs as ValueSet )
1095                    .ok_or_else(|| {
1096                                error!("Unable to convert to valueset");
1097                                OperationError::InvalidAttribute(format!(
1098                                    "invalid totp set - {scim_attr_name}"
1099                                ))
1100                    })
1101
1102            }
1103            (SyntaxType::EmailAddress, true, ScimValue::MultiComplex(values)) => {
1104                let mut vs = Vec::with_capacity(values.len());
1105                for complex in values.iter() {
1106                    let mail_addr = complex
1107                        .get("value")
1108                        .ok_or_else(|| {
1109                            error!("Invalid scim complex attr - missing required key value");
1110                            OperationError::InvalidAttribute(format!(
1111                                "missing required key value - {scim_attr_name}"
1112                            ))
1113                        })
1114                        .and_then(|external_id| match external_id {
1115                            ScimAttr::String(value) => Ok(value.clone()),
1116                            _ => {
1117                                error!("Invalid value attribute - must be scim simple string");
1118                                Err(OperationError::InvalidAttribute(format!(
1119                                    "value must be scim simple string - {scim_attr_name}"
1120                                )))
1121                            }
1122                        })?;
1123
1124                    let primary = if let Some(primary) = complex.get("primary") {
1125                        match primary {
1126                            ScimAttr::Bool(value) => Ok(*value),
1127                            _ => {
1128                                error!("Invalid primary attribute - must be scim simple bool");
1129                                Err(OperationError::InvalidAttribute(format!(
1130                                    "primary must be scim simple bool - {scim_attr_name}"
1131                                )))
1132                            }
1133                        }?
1134                    } else {
1135                        false
1136                    };
1137
1138                    vs.push((mail_addr, primary))
1139                }
1140
1141                ValueSetEmailAddress::from_iter(vs)
1142                    .map(|vs| vs as ValueSet)
1143                    .ok_or_else(|| {
1144                                error!("Unable to convert to valueset");
1145                                OperationError::InvalidAttribute(format!(
1146                                    "invalid email set - {scim_attr_name}"
1147                                ))
1148                    })
1149            }
1150            (SyntaxType::SshKey, true, ScimValue::MultiComplex(values)) => {
1151                let mut vs = Vec::with_capacity(values.len());
1152                for complex in values.iter() {
1153                    let label = complex
1154                        .get("label")
1155                        .ok_or_else(|| {
1156                            error!("Invalid scim complex attr - missing required key label");
1157                            OperationError::InvalidAttribute(format!(
1158                                "missing required key label - {scim_attr_name}"
1159                            ))
1160                        })
1161                        .and_then(|external_id| match external_id {
1162                            ScimAttr::String(value) => Ok(value.clone()),
1163                            _ => {
1164                                error!("Invalid value attribute - must be scim simple string");
1165                                Err(OperationError::InvalidAttribute(format!(
1166                                    "value must be scim simple string - {scim_attr_name}"
1167                                )))
1168                            }
1169                        })?;
1170
1171                    let value = complex
1172                        .get("value")
1173                        .ok_or_else(|| {
1174                            error!("Invalid scim complex attr - missing required key value");
1175                            OperationError::InvalidAttribute(format!(
1176                                "missing required key value - {scim_attr_name}"
1177                            ))
1178                        })
1179                        .and_then(|external_id| match external_id {
1180                            ScimAttr::String(value) => SshPublicKey::from_string(value)
1181                                .map_err(|err| {
1182                                    error!(?err, "Invalid ssh key provided via scim");
1183                                    OperationError::SC0001IncomingSshPublicKey
1184                                }),
1185                            _ => {
1186                                error!("Invalid value attribute - must be scim simple string");
1187                                Err(OperationError::InvalidAttribute(format!(
1188                                    "value must be scim simple string - {scim_attr_name}"
1189                                )))
1190                            }
1191                        })?;
1192
1193                    vs.push((label, value))
1194                }
1195
1196                ValueSetSshKey::from_iter(vs)
1197                    .map(|vs| vs as ValueSet)
1198                    .ok_or_else(|| {
1199                        error!("Unable to convert to valueset");
1200                        OperationError::InvalidAttribute(format!(
1201                            "value must be scim simple string - {scim_attr_name}"
1202                        ))
1203                    })
1204            }
1205            (
1206                SyntaxType::DateTime,
1207                false,
1208                ScimValue::Simple(ScimAttr::String(value)),
1209            ) => {
1210                OffsetDateTime::parse(value, &Rfc3339)
1211                    .ok()
1212                    .map(|odt| odt.to_offset(time::UtcOffset::UTC))
1213                    .map(ValueSetDateTime::new)
1214                    .map(|vs| vs as ValueSet)
1215                    .ok_or_else(|| {
1216                        error!("Invalid value attribute - must be scim simple string with rfc3339 formatted datetime");
1217                        OperationError::InvalidAttribute(format!(
1218                            "value must be scim simple string with rfc3339 formatted datetime - {scim_attr_name}"
1219                        ))
1220                    })
1221            }
1222            (syn, mv, sa) => {
1223                error!(?syn, ?mv, ?sa, "Unsupported scim attribute conversion. This may be a syntax error in your import, or a missing feature in Kanidm.");
1224                Err(OperationError::InvalidAttribute(format!(
1225                    "Unsupported attribute conversion - {scim_attr_name}"
1226                )))
1227            }
1228        }
1229    }
1230
1231    fn scim_entry_to_mod(
1232        &mut self,
1233        scim_ent: &ScimEntry,
1234        sync_uuid: Uuid,
1235        sync_allow_class_set: &BTreeMap<String, SchemaClass>,
1236        sync_allow_attr_set: &BTreeSet<Attribute>,
1237        phantom_attr_set: &BTreeSet<Attribute>,
1238    ) -> Result<ModifyList<ModifyInvalid>, OperationError> {
1239        // What classes did they request for this entry to sync?
1240        let requested_classes = scim_ent.schemas.iter()
1241            .map(|schema| {
1242                schema.as_str().strip_prefix(SCIM_SCHEMA_SYNC_1)
1243                    .ok_or_else(|| {
1244                        error!(?schema, "Invalid requested schema - Not a kanidm sync schema.");
1245                        OperationError::InvalidEntryState
1246                    })
1247                    // Now look up if it's satisfiable.
1248                    .and_then(|cls_name| {
1249                        sync_allow_class_set.get_key_value(cls_name)
1250                        .ok_or_else(|| {
1251                            error!(?cls_name, "Invalid requested schema - Class does not exist in Kanidm or is not a sync_allowed class");
1252                            OperationError::InvalidEntryState
1253                        })
1254                    })
1255            })
1256            .collect::<Result<BTreeMap<&String, &SchemaClass>, _>>()?;
1257
1258        // Get all the classes.
1259        debug!("Schemas valid - Proceeding with entry {}", scim_ent.id);
1260
1261        #[allow(clippy::vec_init_then_push)]
1262        let mut mods = Vec::with_capacity(4);
1263
1264        mods.push(Modify::Assert(
1265            Attribute::SyncParentUuid,
1266            PartialValue::Refer(sync_uuid),
1267        ));
1268
1269        for req_class in requested_classes.keys() {
1270            mods.push(Modify::Present(
1271                Attribute::SyncClass,
1272                Value::new_iutf8n(req_class),
1273            ));
1274            mods.push(Modify::Present(
1275                Attribute::Class,
1276                Value::new_iutf8n(req_class),
1277            ));
1278        }
1279
1280        // Clean up from removed classes. NEED THE OLD ENTRY FOR THIS.
1281        // Technically this is an EDGE case because in 99% of cases people aren't going to rug pull and REMOVE values on
1282        // ldap entries because of how it works.
1283        //
1284        // If we do decide to add this we use the sync_class attr to determine what was *previously* added to the object
1285        // rather than what we as kanidm added.
1286        //
1287        // We can then diff the sync_class from the set of req classes to work out what to remove.
1288        //
1289        // Cleaning up old attributes is weirder though. I'm not sure it's trivial or easy. Because we need to know if some attr X
1290        // is solely owned by that sync_class before we remove it, but it may not be. There could be two classes that allow it
1291        // and the other supporting class remains, so we shouldn't touch it. But then it has to be asked, where did it come from?
1292        // who owned it? Was it the sync side or kani? I think in general removal will be challenging.
1293
1294        debug!(?requested_classes);
1295
1296        // What attrs are owned by the set of requested classes?
1297        // We also need to account for phantom attrs somehow!
1298        //
1299        // - either we nominate phantom attrs on the classes they can import with
1300        //   or we need to always allow them?
1301        let sync_owned_attrs: BTreeSet<Attribute> = requested_classes
1302            .values()
1303            .flat_map(|cls| {
1304                cls.systemmay
1305                    .iter()
1306                    .chain(cls.may.iter())
1307                    .chain(cls.systemmust.iter())
1308                    .chain(cls.must.iter())
1309            })
1310            // Finally, establish if the attribute is syncable. Technically this could probe some attrs
1311            // multiple times due to how the loop is established, but in reality there are few attr overlaps.
1312            .filter(|a| sync_allow_attr_set.contains(*a))
1313            // Add in the set of phantom syncable attrs.
1314            .chain(phantom_attr_set.iter())
1315            .cloned()
1316            .collect();
1317
1318        debug!(?sync_owned_attrs);
1319
1320        for attr in sync_owned_attrs.iter() {
1321            if !phantom_attr_set.contains(attr) {
1322                // These are the attrs that are "real" and need to be cleaned out first.
1323                mods.push(Modify::Purged(attr.clone()));
1324            }
1325        }
1326
1327        // For each attr in the scim entry, see if it's in the sync_owned set. If so, proceed.
1328        for (scim_attr_name, scim_attr) in scim_ent.attrs.iter() {
1329            let scim_attr_name = Attribute::from(scim_attr_name.as_str());
1330
1331            if !sync_owned_attrs.contains(&scim_attr_name) {
1332                error!(
1333                    "Rejecting attribute {} for entry {} which is not sync owned",
1334                    scim_attr_name, scim_ent.id
1335                );
1336                return Err(OperationError::InvalidEntryState);
1337            }
1338
1339            // Convert each scim_attr to a set of valuesets.
1340            let valueset = self
1341                .scim_attr_to_values(&scim_attr_name, scim_attr)
1342                .inspect_err(|err| {
1343                    error!(
1344                        ?err,
1345                        "Failed to convert {} for entry {}", scim_attr_name, scim_ent.id
1346                    );
1347                })?;
1348
1349            mods.push(Modify::Set(scim_attr_name.clone(), valueset));
1350        }
1351
1352        trace!(?mods);
1353
1354        Ok(ModifyList::new_list(mods))
1355    }
1356
1357    #[instrument(level = "info", skip_all)]
1358    pub(crate) fn scim_sync_apply_phase_3(
1359        &mut self,
1360        change_entries: &BTreeMap<Uuid, &ScimEntry>,
1361        sync_uuid: Uuid,
1362        sync_authority_set: &BTreeSet<Attribute>,
1363    ) -> Result<(), OperationError> {
1364        if change_entries.is_empty() {
1365            info!("No change_entries requested");
1366            return Ok(());
1367        }
1368
1369        // Generally this is just assembling a large batch modify. Since we rely on external_id
1370        // to be present and valid, this is why we pre-apply that in phase 2.
1371        //
1372        // Another key point here is this is where we exclude changes to entries that our
1373        // domain has been granted authority over.
1374        //
1375
1376        // The sync_allow_attr_set is what the sync connect *can* change. Authority is what the user
1377        // wants kani to control. As a result:
1378        //   sync_allow_attr = set of attrs from classes subtract attrs from authority.
1379
1380        let schema = self.qs_write.get_schema();
1381
1382        let class_snapshot = schema.get_classes();
1383        let attr_snapshot = schema.get_attributes();
1384
1385        let sync_allow_class_set: BTreeMap<String, SchemaClass> = class_snapshot
1386            .values()
1387            .filter_map(|cls| {
1388                if cls.sync_allowed {
1389                    Some((cls.name.to_string(), cls.clone()))
1390                } else {
1391                    None
1392                }
1393            })
1394            .collect();
1395
1396        let sync_allow_attr_set: BTreeSet<Attribute> = attr_snapshot
1397            .values()
1398            // Only add attrs to this if they are both sync allowed AND authority granted.
1399            .filter_map(|attr| {
1400                if attr.sync_allowed && !sync_authority_set.contains(&attr.name) {
1401                    Some(attr.name.clone())
1402                } else {
1403                    None
1404                }
1405            })
1406            .collect();
1407
1408        let phantom_attr_set: BTreeSet<Attribute> = attr_snapshot
1409            .values()
1410            .filter_map(|attr| {
1411                if attr.phantom && attr.sync_allowed {
1412                    Some(attr.name.clone())
1413                } else {
1414                    None
1415                }
1416            })
1417            .collect();
1418
1419        let asserts = change_entries
1420            .iter()
1421            .map(|(u, scim_ent)| {
1422                self.scim_entry_to_mod(
1423                    scim_ent,
1424                    sync_uuid,
1425                    &sync_allow_class_set,
1426                    &sync_allow_attr_set,
1427                    &phantom_attr_set,
1428                )
1429                .map(|e| (*u, e))
1430            })
1431            .collect::<Result<Vec<_>, _>>()?;
1432
1433        // We can't just pass the above iter in here since it's fallible due to the
1434        // external resolve phase.
1435
1436        self.qs_write
1437            .internal_batch_modify(asserts.into_iter())
1438            .inspect_err(|err| {
1439                error!(?err, "Unable to apply modifications to sync entries.");
1440            })
1441    }
1442
1443    #[instrument(level = "info", skip_all)]
1444    pub(crate) fn scim_sync_apply_phase_4(
1445        &mut self,
1446        retain: &ScimSyncRetentionMode,
1447        sync_uuid: Uuid,
1448    ) -> Result<(), OperationError> {
1449        let delete_filter = match retain {
1450            ScimSyncRetentionMode::Ignore => {
1451                info!("No retention mode requested");
1452                return Ok(());
1453            }
1454            ScimSyncRetentionMode::Retain(present_uuids) => {
1455                let filter_or = present_uuids
1456                    .iter()
1457                    .copied()
1458                    .map(|u| f_eq(Attribute::Uuid, PartialValue::Uuid(u)))
1459                    .collect::<Vec<_>>();
1460
1461                if filter_or.is_empty() {
1462                    filter!(f_and!([
1463                        // F in chat for all these entries.
1464                        f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid))
1465                    ]))
1466                } else {
1467                    filter!(f_and!([
1468                        // Must be part of this sync agreement.
1469                        f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid)),
1470                        // Must not be an entry in the change set.
1471                        f_andnot(f_or(filter_or))
1472                    ]))
1473                }
1474            }
1475            ScimSyncRetentionMode::Delete(delete_uuids) => {
1476                if delete_uuids.is_empty() {
1477                    info!("No delete_uuids requested");
1478                    return Ok(());
1479                }
1480
1481                // Search the set of delete_uuids that were requested.
1482                let filter_or = delete_uuids
1483                    .iter()
1484                    .copied()
1485                    .map(|u| f_eq(Attribute::Uuid, PartialValue::Uuid(u)))
1486                    .collect();
1487
1488                // NOTE: We bypass recycled/ts here because we WANT to know if we are in that
1489                // state so we can AVOID updates to these entries!
1490                let delete_cands = self
1491                    .qs_write
1492                    .internal_search(filter_all!(f_or(filter_or)))
1493                    .inspect_err(|err| {
1494                        error!(?err, "Failed to determine existing entries set");
1495                    })?;
1496
1497                let delete_filter = delete_cands
1498                    .into_iter()
1499                    .filter_map(|ent| {
1500                        if ent.mask_recycled_ts().is_none() {
1501                            debug!("Skipping already deleted entry {}", ent.get_uuid());
1502                            None
1503                        } else if ent.get_ava_single_refer(Attribute::SyncParentUuid)
1504                            != Some(sync_uuid)
1505                        {
1506                            warn!(
1507                                "Skipping entry that is not within sync control {}",
1508                                ent.get_uuid()
1509                            );
1510                            Some(Err(OperationError::AccessDenied))
1511                        } else {
1512                            Some(Ok(f_eq(
1513                                Attribute::Uuid,
1514                                PartialValue::Uuid(ent.get_uuid()),
1515                            )))
1516                        }
1517                    })
1518                    .collect::<Result<Vec<_>, _>>()?;
1519
1520                if delete_filter.is_empty() {
1521                    info!("No valid deletes requested");
1522                    return Ok(());
1523                }
1524
1525                filter!(f_and(vec![
1526                    // Technically not needed, but it's better to add more safeties and this
1527                    // costs nothing to add.
1528                    f_eq(Attribute::SyncParentUuid, PartialValue::Refer(sync_uuid)),
1529                    f_or(delete_filter)
1530                ]))
1531            }
1532        };
1533
1534        // Do the delete
1535        let res = self.qs_write.internal_delete(&delete_filter).map_err(|e| {
1536            error!(?e, "Failed to delete uuids");
1537            e
1538        });
1539        match res {
1540            Ok(()) => Ok(()),
1541            Err(OperationError::NoMatchingEntries) => {
1542                debug!("No deletes required");
1543                Ok(())
1544            }
1545            Err(e) => Err(e),
1546        }
1547    }
1548
1549    #[instrument(level = "info", skip_all)]
1550    pub(crate) fn scim_sync_apply_phase_5(
1551        &mut self,
1552        sync_uuid: Uuid,
1553        to_state: &ScimSyncState,
1554    ) -> Result<(), OperationError> {
1555        // At this point everything is done. Now we do a final modify on the sync state entry
1556        // to reflect the new sync state.
1557
1558        let modlist = match to_state {
1559            ScimSyncState::Active { cookie } => ModifyList::new_purge_and_set(
1560                Attribute::SyncCookie,
1561                Value::PrivateBinary(cookie.to_vec()),
1562            ),
1563            ScimSyncState::Refresh => ModifyList::new_purge(Attribute::SyncCookie),
1564        };
1565
1566        self.qs_write
1567            .internal_modify_uuid(sync_uuid, &modlist)
1568            .inspect_err(|err| {
1569                error!(?err, "Failed to update sync entry state");
1570            })
1571    }
1572}
1573
1574impl IdmServerProxyReadTransaction<'_> {
1575    pub fn scim_sync_get_state(
1576        &mut self,
1577        ident: &Identity,
1578    ) -> Result<ScimSyncState, OperationError> {
1579        // We must be *extra* careful in these functions since we do *internal* searches
1580        // which are *bypassing* normal access checks!
1581
1582        // The ident *must* be a synchronise session.
1583        let sync_uuid = match &ident.origin {
1584            IdentType::User(_) | IdentType::Internal(_) => {
1585                warn!("Ident type is not synchronise");
1586                return Err(OperationError::AccessDenied);
1587            }
1588            IdentType::Synch(u) => {
1589                // Ok!
1590                *u
1591            }
1592        };
1593
1594        match ident.access_scope() {
1595            AccessScope::ReadOnly | AccessScope::ReadWrite => {
1596                warn!("Ident access scope is not synchronise");
1597                return Err(OperationError::AccessDenied);
1598            }
1599            AccessScope::Synchronise => {
1600                // As you were
1601            }
1602        };
1603
1604        // Get the sync cookie of that session.
1605        let sync_entry = self.qs_read.internal_search_uuid(sync_uuid)?;
1606
1607        Ok(
1608            match sync_entry.get_ava_single_private_binary(Attribute::SyncCookie) {
1609                Some(b) => ScimSyncState::Active { cookie: b.to_vec() },
1610                None => ScimSyncState::Refresh,
1611            },
1612        )
1613    }
1614}
1615
1616#[cfg(test)]
1617mod tests {
1618    use crate::{
1619        idm::server::{IdmServerProxyWriteTransaction, IdmServerTransaction},
1620        prelude::*,
1621    };
1622    use compact_jwt::{traits::JwsVerifiable, Jws, JwsCompact, JwsEs256Signer, JwsSigner};
1623    use kanidm_proto::{internal::ApiTokenPurpose, scim_v1::*};
1624    use std::{sync::Arc, time::Duration};
1625
1626    use super::{
1627        GenerateScimSyncTokenEvent, ScimSyncFinaliseEvent, ScimSyncTerminateEvent, ScimSyncToken,
1628        ScimSyncUpdateEvent,
1629    };
1630
1631    const TEST_CURRENT_TIME: u64 = 6000;
1632
1633    fn create_scim_sync_account(
1634        idms_prox_write: &mut IdmServerProxyWriteTransaction<'_>,
1635        ct: Duration,
1636    ) -> (Uuid, JwsCompact) {
1637        let sync_uuid = Uuid::new_v4();
1638
1639        let e1 = entry_init!(
1640            (Attribute::Class, EntryClass::Object.to_value()),
1641            (Attribute::Class, EntryClass::SyncAccount.to_value()),
1642            (Attribute::Name, Value::new_iname("test_scim_sync")),
1643            (Attribute::Uuid, Value::Uuid(sync_uuid)),
1644            (
1645                Attribute::Description,
1646                Value::new_utf8s("A test sync agreement")
1647            )
1648        );
1649
1650        idms_prox_write
1651            .qs_write
1652            .internal_create(vec![e1])
1653            .expect("Failed to create sync account");
1654
1655        let gte = GenerateScimSyncTokenEvent::new_internal(sync_uuid, "Sync Connector");
1656
1657        let sync_token = idms_prox_write
1658            .scim_sync_generate_token(&gte, ct)
1659            .expect("failed to generate new scim sync token");
1660
1661        (sync_uuid, sync_token)
1662    }
1663
1664    #[idm_test]
1665    async fn test_idm_scim_sync_basic_function(
1666        idms: &IdmServer,
1667        _idms_delayed: &mut IdmServerDelayed,
1668    ) {
1669        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1670
1671        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1672        let (sync_uuid, sync_token) = create_scim_sync_account(&mut idms_prox_write, ct);
1673
1674        assert!(idms_prox_write.commit().is_ok());
1675
1676        // Do a get_state to get the current "state cookie" if any.
1677        let mut idms_prox_read = idms.proxy_read().await.unwrap();
1678
1679        let ident = idms_prox_read
1680            .validate_sync_client_auth_info_to_ident(sync_token.into(), ct)
1681            .expect("Failed to validate sync token");
1682
1683        assert_eq!(ident.get_uuid(), sync_uuid);
1684
1685        let sync_state = idms_prox_read
1686            .scim_sync_get_state(&ident)
1687            .expect("Failed to get current sync state");
1688        trace!(?sync_state);
1689
1690        assert!(matches!(sync_state, ScimSyncState::Refresh));
1691
1692        drop(idms_prox_read);
1693    }
1694
1695    #[idm_test]
1696    async fn test_idm_scim_sync_token_security(
1697        idms: &IdmServer,
1698        _idms_delayed: &mut IdmServerDelayed,
1699    ) {
1700        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1701
1702        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1703
1704        let sync_uuid = Uuid::new_v4();
1705
1706        let e1 = entry_init!(
1707            (Attribute::Class, EntryClass::Object.to_value()),
1708            (Attribute::Class, EntryClass::SyncAccount.to_value()),
1709            (Attribute::Name, Value::new_iname("test_scim_sync")),
1710            (Attribute::Uuid, Value::Uuid(sync_uuid)),
1711            (
1712                Attribute::Description,
1713                Value::new_utf8s("A test sync agreement")
1714            )
1715        );
1716
1717        let ce = CreateEvent::new_internal(vec![e1]);
1718        let cr = idms_prox_write.qs_write.create(&ce);
1719        assert!(cr.is_ok());
1720
1721        let gte = GenerateScimSyncTokenEvent::new_internal(sync_uuid, "Sync Connector");
1722
1723        let sync_token = idms_prox_write
1724            .scim_sync_generate_token(&gte, ct)
1725            .expect("failed to generate new scim sync token");
1726
1727        assert!(idms_prox_write.commit().is_ok());
1728
1729        // -- Check the happy path.
1730        let mut idms_prox_read = idms.proxy_read().await.unwrap();
1731        let ident = idms_prox_read
1732            .validate_sync_client_auth_info_to_ident(sync_token.clone().into(), ct)
1733            .expect("Failed to validate sync token");
1734        assert_eq!(ident.get_uuid(), sync_uuid);
1735        drop(idms_prox_read);
1736
1737        // -- Revoke the session
1738
1739        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1740        let me_inv_m = ModifyEvent::new_internal_invalid(
1741            filter!(f_eq(
1742                Attribute::Name,
1743                PartialValue::new_iname("test_scim_sync")
1744            )),
1745            ModifyList::new_list(vec![Modify::Purged(Attribute::SyncTokenSession)]),
1746        );
1747        assert!(idms_prox_write.qs_write.modify(&me_inv_m).is_ok());
1748        assert!(idms_prox_write.commit().is_ok());
1749
1750        // Must fail
1751        let mut idms_prox_read = idms.proxy_read().await.unwrap();
1752        let fail =
1753            idms_prox_read.validate_sync_client_auth_info_to_ident(sync_token.clone().into(), ct);
1754        assert!(matches!(fail, Err(OperationError::NotAuthenticated)));
1755        drop(idms_prox_read);
1756
1757        // -- New session, reset the JWS
1758        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1759
1760        let gte = GenerateScimSyncTokenEvent::new_internal(sync_uuid, "Sync Connector");
1761        let sync_token = idms_prox_write
1762            .scim_sync_generate_token(&gte, ct)
1763            .expect("failed to generate new scim sync token");
1764
1765        let revoke_kid = sync_token.kid().expect("token does not contain a key id");
1766
1767        idms_prox_write
1768            .qs_write
1769            .internal_modify_uuid(
1770                UUID_DOMAIN_INFO,
1771                &ModifyList::new_append(
1772                    Attribute::KeyActionRevoke,
1773                    Value::HexString(revoke_kid.to_string()),
1774                ),
1775            )
1776            .expect("Unable to revoke key");
1777
1778        assert!(idms_prox_write.commit().is_ok());
1779
1780        let mut idms_prox_read = idms.proxy_read().await.unwrap();
1781        let fail =
1782            idms_prox_read.validate_sync_client_auth_info_to_ident(sync_token.clone().into(), ct);
1783        assert!(matches!(fail, Err(OperationError::NotAuthenticated)));
1784
1785        // -- Forge a session, use wrong types
1786
1787        let sync_entry = idms_prox_read
1788            .qs_read
1789            .internal_search_uuid(sync_uuid)
1790            .expect("Unable to access sync entry");
1791
1792        let sync_tokens = sync_entry
1793            .get_ava_as_apitoken_map(Attribute::SyncTokenSession)
1794            .cloned()
1795            .unwrap_or_default();
1796
1797        // Steal these from the legit sesh.
1798        let (token_id, issued_at) = sync_tokens
1799            .iter()
1800            .next()
1801            .map(|(k, v)| (*k, v.issued_at))
1802            .expect("No sync tokens present");
1803
1804        let purpose = ApiTokenPurpose::ReadWrite;
1805
1806        let scim_sync_token = ScimSyncToken {
1807            token_id,
1808            issued_at,
1809            purpose,
1810        };
1811
1812        let token = Jws::into_json(&scim_sync_token).expect("Unable to serialise forged token");
1813
1814        let jws_key = JwsEs256Signer::generate_es256().expect("Unable to create signer");
1815
1816        let forged_token = jws_key.sign(&token).expect("Unable to sign forged token");
1817
1818        let fail = idms_prox_read.validate_sync_client_auth_info_to_ident(forged_token.into(), ct);
1819        assert!(matches!(fail, Err(OperationError::NotAuthenticated)));
1820    }
1821
1822    fn test_scim_sync_apply_setup_ident(
1823        idms_prox_write: &mut IdmServerProxyWriteTransaction,
1824        ct: Duration,
1825    ) -> (Uuid, Identity) {
1826        let sync_uuid = Uuid::new_v4();
1827
1828        let e1 = entry_init!(
1829            (Attribute::Class, EntryClass::Object.to_value()),
1830            (Attribute::Class, EntryClass::SyncAccount.to_value()),
1831            (Attribute::Name, Value::new_iname("test_scim_sync")),
1832            (Attribute::Uuid, Value::Uuid(sync_uuid)),
1833            (
1834                Attribute::Description,
1835                Value::new_utf8s("A test sync agreement")
1836            )
1837        );
1838
1839        let ce = CreateEvent::new_internal(vec![e1]);
1840        let cr = idms_prox_write.qs_write.create(&ce);
1841        assert!(cr.is_ok());
1842
1843        let gte = GenerateScimSyncTokenEvent::new_internal(sync_uuid, "Sync Connector");
1844
1845        let sync_token = idms_prox_write
1846            .scim_sync_generate_token(&gte, ct)
1847            .expect("failed to generate new scim sync token");
1848
1849        let ident = idms_prox_write
1850            .validate_sync_client_auth_info_to_ident(sync_token.into(), ct)
1851            .expect("Failed to process sync token to ident");
1852
1853        (sync_uuid, ident)
1854    }
1855
1856    #[idm_test]
1857    async fn test_idm_scim_sync_apply_phase_1_inconsistent(
1858        idms: &IdmServer,
1859        _idms_delayed: &mut IdmServerDelayed,
1860    ) {
1861        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1862        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1863        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
1864        let sse = ScimSyncUpdateEvent { ident };
1865
1866        let changes = ScimSyncRequest {
1867            from_state: ScimSyncState::Active {
1868                cookie: vec![1, 2, 3, 4],
1869            },
1870            to_state: ScimSyncState::Refresh,
1871            entries: Vec::with_capacity(0),
1872            retain: ScimSyncRetentionMode::Ignore,
1873        };
1874
1875        let res = idms_prox_write.scim_sync_apply_phase_1(&sse, &changes);
1876
1877        assert!(matches!(res, Err(OperationError::InvalidSyncState)));
1878
1879        assert!(idms_prox_write.commit().is_ok());
1880    }
1881
1882    #[idm_test]
1883    async fn test_idm_scim_sync_apply_phase_2_basic(
1884        idms: &IdmServer,
1885        _idms_delayed: &mut IdmServerDelayed,
1886    ) {
1887        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1888        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1889        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
1890        let sse = ScimSyncUpdateEvent { ident };
1891
1892        let user_sync_uuid = uuid::uuid!("91b7aaf2-2445-46ce-8998-96d9f186cc69");
1893
1894        let changes = ScimSyncRequest {
1895            from_state: ScimSyncState::Refresh,
1896            to_state: ScimSyncState::Active {
1897                cookie: vec![1, 2, 3, 4],
1898            },
1899            entries: vec![ScimEntry {
1900                schemas: vec![SCIM_SCHEMA_SYNC_PERSON.to_string()],
1901                id: user_sync_uuid,
1902                external_id: Some("dn=william,ou=people,dc=test".to_string()),
1903                meta: None,
1904                attrs: btreemap!((
1905                    Attribute::Name.to_string(),
1906                    ScimValue::Simple(ScimAttr::String("william".to_string()))
1907                ),),
1908            }],
1909            retain: ScimSyncRetentionMode::Ignore,
1910        };
1911
1912        let (sync_uuid, _sync_authority_set, change_entries, _sync_refresh) = idms_prox_write
1913            .scim_sync_apply_phase_1(&sse, &changes)
1914            .expect("Failed to run phase 1");
1915
1916        idms_prox_write
1917            .scim_sync_apply_phase_2(&change_entries, sync_uuid)
1918            .expect("Failed to run phase 2");
1919
1920        let synced_entry = idms_prox_write
1921            .qs_write
1922            .internal_search_uuid(user_sync_uuid)
1923            .expect("Failed to access sync stub entry");
1924
1925        assert!(
1926            synced_entry.get_ava_single_iutf8(Attribute::SyncExternalId)
1927                == Some("dn=william,ou=people,dc=test")
1928        );
1929        assert_eq!(synced_entry.get_uuid(), user_sync_uuid);
1930
1931        assert!(idms_prox_write.commit().is_ok());
1932    }
1933
1934    #[idm_test]
1935    async fn test_idm_scim_sync_apply_phase_2_deny_on_tombstone(
1936        idms: &IdmServer,
1937        _idms_delayed: &mut IdmServerDelayed,
1938    ) {
1939        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1940        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1941        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
1942
1943        let user_sync_uuid = Uuid::new_v4();
1944        // Create a recycled entry
1945        assert!(idms_prox_write
1946            .qs_write
1947            .internal_create(vec![entry_init!(
1948                (Attribute::Class, EntryClass::Object.to_value()),
1949                (Attribute::Uuid, Value::Uuid(user_sync_uuid))
1950            )])
1951            .is_ok());
1952
1953        assert!(idms_prox_write
1954            .qs_write
1955            .internal_delete_uuid(user_sync_uuid)
1956            .is_ok());
1957
1958        // Now create a sync that conflicts with the tombstone uuid. This will be REJECTED.
1959
1960        let sse = ScimSyncUpdateEvent { ident };
1961
1962        let changes = ScimSyncRequest {
1963            from_state: ScimSyncState::Refresh,
1964            to_state: ScimSyncState::Active {
1965                cookie: vec![1, 2, 3, 4],
1966            },
1967            entries: vec![ScimEntry {
1968                schemas: vec![SCIM_SCHEMA_SYNC_PERSON.to_string()],
1969                id: user_sync_uuid,
1970                external_id: Some("dn=william,ou=people,dc=test".to_string()),
1971                meta: None,
1972                attrs: btreemap!((
1973                    Attribute::Name.to_string(),
1974                    ScimValue::Simple(ScimAttr::String("william".to_string()))
1975                ),),
1976            }],
1977            retain: ScimSyncRetentionMode::Ignore,
1978        };
1979
1980        let (sync_uuid, _sync_authority_set, change_entries, _sync_refresh) = idms_prox_write
1981            .scim_sync_apply_phase_1(&sse, &changes)
1982            .expect("Failed to run phase 1");
1983
1984        let res = idms_prox_write.scim_sync_apply_phase_2(&change_entries, sync_uuid);
1985
1986        assert!(matches!(res, Err(OperationError::InvalidEntryState)));
1987
1988        assert!(idms_prox_write.commit().is_ok());
1989    }
1990
1991    // Phase 3
1992
1993    async fn apply_phase_3_test(
1994        idms: &IdmServer,
1995        entries: Vec<ScimEntry>,
1996    ) -> Result<(), OperationError> {
1997        let ct = Duration::from_secs(TEST_CURRENT_TIME);
1998        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
1999        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2000        let sse = ScimSyncUpdateEvent { ident };
2001
2002        let changes = ScimSyncRequest {
2003            from_state: ScimSyncState::Refresh,
2004            to_state: ScimSyncState::Active {
2005                cookie: vec![1, 2, 3, 4],
2006            },
2007            entries,
2008            retain: ScimSyncRetentionMode::Ignore,
2009        };
2010
2011        let (sync_uuid, sync_authority_set, change_entries, _sync_refresh) = idms_prox_write
2012            .scim_sync_apply_phase_1(&sse, &changes)
2013            .expect("Failed to run phase 1");
2014
2015        assert!(idms_prox_write
2016            .scim_sync_apply_phase_2(&change_entries, sync_uuid)
2017            .is_ok());
2018
2019        idms_prox_write
2020            .scim_sync_apply_phase_3(&change_entries, sync_uuid, &sync_authority_set)
2021            .and_then(|a| idms_prox_write.commit().map(|()| a))
2022    }
2023
2024    #[idm_test]
2025    async fn test_idm_scim_sync_phase_3_basic(
2026        idms: &IdmServer,
2027        _idms_delayed: &mut IdmServerDelayed,
2028    ) {
2029        let user_sync_uuid = Uuid::new_v4();
2030
2031        assert!(apply_phase_3_test(
2032            idms,
2033            vec![ScimEntry {
2034                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2035                id: user_sync_uuid,
2036                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2037                meta: None,
2038                attrs: btreemap!((
2039                    Attribute::Name.to_string(),
2040                    ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2041                ),),
2042            }]
2043        )
2044        .await
2045        .is_ok());
2046
2047        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2048        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2049
2050        let ent = idms_prox_write
2051            .qs_write
2052            .internal_search_uuid(user_sync_uuid)
2053            .expect("Unable to access entry");
2054
2055        assert_eq!(ent.get_ava_single_iname(Attribute::Name), Some("testgroup"));
2056        assert!(
2057            ent.get_ava_single_iutf8(Attribute::SyncExternalId)
2058                == Some("cn=testgroup,ou=people,dc=test")
2059        );
2060
2061        assert!(idms_prox_write.commit().is_ok());
2062    }
2063
2064    // -- try to set uuid
2065    #[idm_test]
2066    async fn test_idm_scim_sync_phase_3_uuid_manipulation(
2067        idms: &IdmServer,
2068        _idms_delayed: &mut IdmServerDelayed,
2069    ) {
2070        let user_sync_uuid = Uuid::new_v4();
2071
2072        assert!(apply_phase_3_test(
2073            idms,
2074            vec![ScimEntry {
2075                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2076                id: user_sync_uuid,
2077                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2078                meta: None,
2079                attrs: btreemap!(
2080                    (
2081                        Attribute::Name.to_string(),
2082                        ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2083                    ),
2084                    (
2085                        Attribute::Uuid.to_string(),
2086                        ScimValue::Simple(ScimAttr::String(
2087                            "2c019619-f894-4a94-b356-05d371850e3d".to_string()
2088                        ))
2089                    )
2090                ),
2091            }]
2092        )
2093        .await
2094        .is_err());
2095    }
2096
2097    // -- try to set sync_uuid / sync_object attrs
2098    #[idm_test]
2099    async fn test_idm_scim_sync_phase_3_sync_parent_uuid_manipulation(
2100        idms: &IdmServer,
2101        _idms_delayed: &mut IdmServerDelayed,
2102    ) {
2103        let user_sync_uuid = Uuid::new_v4();
2104
2105        assert!(apply_phase_3_test(
2106            idms,
2107            vec![ScimEntry {
2108                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2109                id: user_sync_uuid,
2110                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2111                meta: None,
2112                attrs: btreemap!(
2113                    (
2114                        Attribute::Name.to_string(),
2115                        ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2116                    ),
2117                    (
2118                        "sync_parent_uuid".to_string(),
2119                        ScimValue::Simple(ScimAttr::String(
2120                            "2c019619-f894-4a94-b356-05d371850e3d".to_string()
2121                        ))
2122                    )
2123                ),
2124            }]
2125        )
2126        .await
2127        .is_err());
2128    }
2129
2130    // -- try to add class via class attr (not via scim schema)
2131    #[idm_test]
2132    async fn test_idm_scim_sync_phase_3_disallowed_class_forbidden(
2133        idms: &IdmServer,
2134        _idms_delayed: &mut IdmServerDelayed,
2135    ) {
2136        let user_sync_uuid = Uuid::new_v4();
2137
2138        assert!(apply_phase_3_test(
2139            idms,
2140            vec![ScimEntry {
2141                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2142                id: user_sync_uuid,
2143                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2144                meta: None,
2145                attrs: btreemap!(
2146                    (
2147                        Attribute::Name.to_string(),
2148                        ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2149                    ),
2150                    (
2151                        Attribute::Class.to_string(),
2152                        ScimValue::Simple(ScimAttr::String("posixgroup".to_string()))
2153                    )
2154                ),
2155            }]
2156        )
2157        .await
2158        .is_err());
2159    }
2160
2161    // -- try to add class not in allowed class set (via scim schema)
2162
2163    #[idm_test]
2164    async fn test_idm_scim_sync_phase_3_disallowed_class_system(
2165        idms: &IdmServer,
2166        _idms_delayed: &mut IdmServerDelayed,
2167    ) {
2168        let user_sync_uuid = Uuid::new_v4();
2169
2170        assert!(apply_phase_3_test(
2171            idms,
2172            vec![ScimEntry {
2173                schemas: vec![format!("{SCIM_SCHEMA_SYNC_1}system")],
2174                id: user_sync_uuid,
2175                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2176                meta: None,
2177                attrs: btreemap!((
2178                    Attribute::Name.to_string(),
2179                    ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2180                ),),
2181            }]
2182        )
2183        .await
2184        .is_err());
2185    }
2186
2187    // Phase 4
2188
2189    // Good delete - requires phase 5 due to need to do two syncs
2190    #[idm_test]
2191    async fn test_idm_scim_sync_phase_4_correct_delete(
2192        idms: &IdmServer,
2193        _idms_delayed: &mut IdmServerDelayed,
2194    ) {
2195        let user_sync_uuid = Uuid::new_v4();
2196        // Create an entry via sync
2197
2198        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2199        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2200        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2201        let sse = ScimSyncUpdateEvent {
2202            ident: ident.clone(),
2203        };
2204
2205        let changes = ScimSyncRequest {
2206            from_state: ScimSyncState::Refresh,
2207            to_state: ScimSyncState::Active {
2208                cookie: vec![1, 2, 3, 4],
2209            },
2210            entries: vec![ScimEntry {
2211                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2212                id: user_sync_uuid,
2213                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2214                meta: None,
2215                attrs: btreemap!((
2216                    Attribute::Name.to_string(),
2217                    ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2218                ),),
2219            }],
2220            retain: ScimSyncRetentionMode::Ignore,
2221        };
2222
2223        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2224        assert!(idms_prox_write.commit().is_ok());
2225
2226        // Now we can attempt the delete.
2227        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2228        let sse = ScimSyncUpdateEvent { ident };
2229
2230        let changes = ScimSyncRequest {
2231            from_state: ScimSyncState::Active {
2232                cookie: vec![1, 2, 3, 4],
2233            },
2234            to_state: ScimSyncState::Active {
2235                cookie: vec![2, 3, 4, 5],
2236            },
2237            entries: vec![],
2238            retain: ScimSyncRetentionMode::Delete(vec![user_sync_uuid]),
2239        };
2240
2241        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2242
2243        // Can't use internal_search_uuid since that applies a mask.
2244        assert!(idms_prox_write
2245            .qs_write
2246            .internal_search(filter_all!(f_eq(
2247                Attribute::Uuid,
2248                PartialValue::Uuid(user_sync_uuid)
2249            )))
2250            // Should be none as the entry was masked by being recycled.
2251            .map(|entries| {
2252                assert_eq!(entries.len(), 1);
2253                let ent = entries.first().unwrap();
2254                ent.mask_recycled_ts().is_none()
2255            })
2256            .unwrap_or(false));
2257
2258        assert!(idms_prox_write.commit().is_ok());
2259    }
2260
2261    // Delete that doesn't exist.
2262    #[idm_test]
2263    async fn test_idm_scim_sync_phase_4_nonexisting_delete(
2264        idms: &IdmServer,
2265        _idms_delayed: &mut IdmServerDelayed,
2266    ) {
2267        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2268        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2269        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2270        let sse = ScimSyncUpdateEvent { ident };
2271
2272        let changes = ScimSyncRequest {
2273            from_state: ScimSyncState::Refresh,
2274            to_state: ScimSyncState::Active {
2275                cookie: vec![1, 2, 3, 4],
2276            },
2277            // Doesn't exist. If it does, then bless rng.
2278            entries: Vec::with_capacity(0),
2279            retain: ScimSyncRetentionMode::Delete(vec![Uuid::new_v4()]),
2280        };
2281
2282        // Hard to know what was right here. IMO because it doesn't exist at all, we just ignore it
2283        // because the source sync is being overzealous, or it previously used to exist. Maybe
2284        // it was added and immediately removed. Either way, this is ok because we changed
2285        // nothing.
2286        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2287        assert!(idms_prox_write.commit().is_ok());
2288    }
2289
2290    // Delete of something outside of agreement control - must fail.
2291    #[idm_test]
2292    async fn test_idm_scim_sync_phase_4_out_of_scope_delete(
2293        idms: &IdmServer,
2294        _idms_delayed: &mut IdmServerDelayed,
2295    ) {
2296        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2297        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2298
2299        let user_sync_uuid = Uuid::new_v4();
2300        assert!(idms_prox_write
2301            .qs_write
2302            .internal_create(vec![entry_init!(
2303                (Attribute::Class, EntryClass::Object.to_value()),
2304                (Attribute::Uuid, Value::Uuid(user_sync_uuid))
2305            )])
2306            .is_ok());
2307
2308        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2309        let sse = ScimSyncUpdateEvent { ident };
2310
2311        let changes = ScimSyncRequest {
2312            from_state: ScimSyncState::Refresh,
2313            to_state: ScimSyncState::Active {
2314                cookie: vec![1, 2, 3, 4],
2315            },
2316            // Doesn't exist. If it does, then bless rng.
2317            entries: Vec::with_capacity(0),
2318            retain: ScimSyncRetentionMode::Delete(vec![user_sync_uuid]),
2319        };
2320
2321        // Again, not sure what to do here. I think because this is clearly an overstep of the
2322        // rights of the delete_uuid request, this is an error here.
2323        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_err());
2324        // assert!(idms_prox_write.commit().is_ok());
2325    }
2326
2327    // Delete already deleted entry.
2328    #[idm_test]
2329    async fn test_idm_scim_sync_phase_4_delete_already_deleted(
2330        idms: &IdmServer,
2331        _idms_delayed: &mut IdmServerDelayed,
2332    ) {
2333        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2334        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2335
2336        let user_sync_uuid = Uuid::new_v4();
2337        assert!(idms_prox_write
2338            .qs_write
2339            .internal_create(vec![entry_init!(
2340                (Attribute::Class, EntryClass::Object.to_value()),
2341                (Attribute::Uuid, Value::Uuid(user_sync_uuid))
2342            )])
2343            .is_ok());
2344
2345        assert!(idms_prox_write
2346            .qs_write
2347            .internal_delete_uuid(user_sync_uuid)
2348            .is_ok());
2349
2350        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2351        let sse = ScimSyncUpdateEvent { ident };
2352
2353        let changes = ScimSyncRequest {
2354            from_state: ScimSyncState::Refresh,
2355            to_state: ScimSyncState::Active {
2356                cookie: vec![1, 2, 3, 4],
2357            },
2358            // Doesn't exist. If it does, then bless rng.
2359            entries: Vec::with_capacity(0),
2360            retain: ScimSyncRetentionMode::Delete(vec![user_sync_uuid]),
2361        };
2362
2363        // More subtely. There is clearly a theme here. In this case while the sync request
2364        // is trying to delete something out of scope and already deleted, since it already
2365        // is in a recycled state it doesn't matter, it's a no-op. We only care about when
2366        // the delete req applies to a live entry.
2367        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2368        assert!(idms_prox_write.commit().is_ok());
2369    }
2370
2371    #[idm_test]
2372    async fn test_idm_scim_sync_phase_4_correct_retain(
2373        idms: &IdmServer,
2374        _idms_delayed: &mut IdmServerDelayed,
2375    ) {
2376        // Setup two entries.
2377        let sync_uuid_a = Uuid::new_v4();
2378        let sync_uuid_b = Uuid::new_v4();
2379        // Create an entry via sync
2380
2381        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2382        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2383        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2384        let sse = ScimSyncUpdateEvent {
2385            ident: ident.clone(),
2386        };
2387
2388        let changes = ScimSyncRequest {
2389            from_state: ScimSyncState::Refresh,
2390            to_state: ScimSyncState::Active {
2391                cookie: vec![1, 2, 3, 4],
2392            },
2393            entries: vec![
2394                ScimEntry {
2395                    schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2396                    id: sync_uuid_a,
2397                    external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2398                    meta: None,
2399                    attrs: btreemap!((
2400                        Attribute::Name.to_string(),
2401                        ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2402                    ),),
2403                },
2404                ScimEntry {
2405                    schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2406                    id: sync_uuid_b,
2407                    external_id: Some("cn=anothergroup,ou=people,dc=test".to_string()),
2408                    meta: None,
2409                    attrs: btreemap!((
2410                        Attribute::Name.to_string(),
2411                        ScimValue::Simple(ScimAttr::String("anothergroup".to_string()))
2412                    ),),
2413                },
2414            ],
2415            retain: ScimSyncRetentionMode::Ignore,
2416        };
2417
2418        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2419        assert!(idms_prox_write.commit().is_ok());
2420
2421        // Now retain only a single entry
2422        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2423        let sse = ScimSyncUpdateEvent { ident };
2424
2425        let changes = ScimSyncRequest {
2426            from_state: ScimSyncState::Active {
2427                cookie: vec![1, 2, 3, 4],
2428            },
2429            to_state: ScimSyncState::Active {
2430                cookie: vec![2, 3, 4, 5],
2431            },
2432            entries: vec![],
2433            retain: ScimSyncRetentionMode::Retain(vec![sync_uuid_a]),
2434        };
2435
2436        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2437
2438        // Can't use internal_search_uuid since that applies a mask.
2439        assert!(idms_prox_write
2440            .qs_write
2441            .internal_search(filter_all!(f_eq(
2442                Attribute::Uuid,
2443                PartialValue::Uuid(sync_uuid_b)
2444            )))
2445            // Should be none as the entry was masked by being recycled.
2446            .map(|entries| {
2447                assert_eq!(entries.len(), 1);
2448                let ent = entries.first().unwrap();
2449                ent.mask_recycled_ts().is_none()
2450            })
2451            .unwrap_or(false));
2452
2453        assert!(idms_prox_write.commit().is_ok());
2454    }
2455
2456    #[idm_test]
2457    async fn test_idm_scim_sync_phase_4_retain_none(
2458        idms: &IdmServer,
2459        _idms_delayed: &mut IdmServerDelayed,
2460    ) {
2461        // Setup two entries.
2462        let sync_uuid_a = Uuid::new_v4();
2463        let sync_uuid_b = Uuid::new_v4();
2464
2465        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2466        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2467        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2468        let sse = ScimSyncUpdateEvent {
2469            ident: ident.clone(),
2470        };
2471
2472        let changes = ScimSyncRequest {
2473            from_state: ScimSyncState::Refresh,
2474            to_state: ScimSyncState::Active {
2475                cookie: vec![1, 2, 3, 4],
2476            },
2477            entries: vec![
2478                ScimEntry {
2479                    schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2480                    id: sync_uuid_a,
2481                    external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2482                    meta: None,
2483                    attrs: btreemap!((
2484                        Attribute::Name.to_string(),
2485                        ScimValue::Simple(ScimAttr::String("testgroup".to_string()))
2486                    ),),
2487                },
2488                ScimEntry {
2489                    schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2490                    id: sync_uuid_b,
2491                    external_id: Some("cn=anothergroup,ou=people,dc=test".to_string()),
2492                    meta: None,
2493                    attrs: btreemap!((
2494                        Attribute::Name.to_string(),
2495                        ScimValue::Simple(ScimAttr::String("anothergroup".to_string()))
2496                    ),),
2497                },
2498            ],
2499            retain: ScimSyncRetentionMode::Ignore,
2500        };
2501
2502        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2503        assert!(idms_prox_write.commit().is_ok());
2504
2505        // Now retain no entries at all
2506        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2507        let sse = ScimSyncUpdateEvent { ident };
2508
2509        let changes = ScimSyncRequest {
2510            from_state: ScimSyncState::Active {
2511                cookie: vec![1, 2, 3, 4],
2512            },
2513            to_state: ScimSyncState::Active {
2514                cookie: vec![2, 3, 4, 5],
2515            },
2516            entries: vec![],
2517            retain: ScimSyncRetentionMode::Retain(vec![]),
2518        };
2519
2520        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2521
2522        // Can't use internal_search_uuid since that applies a mask.
2523        assert!(idms_prox_write
2524            .qs_write
2525            .internal_search(filter_all!(f_eq(
2526                Attribute::Uuid,
2527                PartialValue::Uuid(sync_uuid_a)
2528            )))
2529            // Should be none as the entry was masked by being recycled.
2530            .map(|entries| {
2531                assert_eq!(entries.len(), 1);
2532                let ent = entries.first().unwrap();
2533                ent.mask_recycled_ts().is_none()
2534            })
2535            .unwrap_or(false));
2536
2537        // Can't use internal_search_uuid since that applies a mask.
2538        assert!(idms_prox_write
2539            .qs_write
2540            .internal_search(filter_all!(f_eq(
2541                Attribute::Uuid,
2542                PartialValue::Uuid(sync_uuid_b)
2543            )))
2544            // Should be none as the entry was masked by being recycled.
2545            .map(|entries| {
2546                assert_eq!(entries.len(), 1);
2547                let ent = entries.first().unwrap();
2548                ent.mask_recycled_ts().is_none()
2549            })
2550            .unwrap_or(false));
2551
2552        assert!(idms_prox_write.commit().is_ok());
2553    }
2554
2555    #[idm_test]
2556    async fn test_idm_scim_sync_phase_4_retain_no_deletes(
2557        idms: &IdmServer,
2558        _idms_delayed: &mut IdmServerDelayed,
2559    ) {
2560        // Setup two entries.
2561        let sync_uuid_a = Uuid::new_v4();
2562
2563        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2564        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2565        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2566        let sse = ScimSyncUpdateEvent {
2567            ident: ident.clone(),
2568        };
2569
2570        let changes = ScimSyncRequest {
2571            from_state: ScimSyncState::Refresh,
2572            to_state: ScimSyncState::Active {
2573                cookie: vec![1, 2, 3, 4],
2574            },
2575            entries: vec![ScimEntry {
2576                schemas: vec![SCIM_SCHEMA_SYNC_GROUP.to_string()],
2577                id: sync_uuid_a,
2578                external_id: Some("cn=testgroup,ou=people,dc=test".to_string()),
2579                meta: None,
2580                attrs: btreemap!((
2581                    Attribute::Name.to_string(),
2582                    ScimAttr::String("testgroup".to_string()).into()
2583                ),),
2584            }],
2585            retain: ScimSyncRetentionMode::Ignore,
2586        };
2587
2588        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2589        assert!(idms_prox_write.commit().is_ok());
2590
2591        // Now retain no entries at all
2592        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2593        let sse = ScimSyncUpdateEvent { ident };
2594
2595        let changes = ScimSyncRequest {
2596            from_state: ScimSyncState::Active {
2597                cookie: vec![1, 2, 3, 4],
2598            },
2599            to_state: ScimSyncState::Active {
2600                cookie: vec![2, 3, 4, 5],
2601            },
2602            entries: vec![],
2603            retain: ScimSyncRetentionMode::Retain(vec![sync_uuid_a]),
2604        };
2605
2606        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2607
2608        // Entry still exists
2609        let ent = idms_prox_write
2610            .qs_write
2611            .internal_search_uuid(sync_uuid_a)
2612            .expect("Unable to access entry");
2613
2614        assert_eq!(ent.get_ava_single_iname(Attribute::Name), Some("testgroup"));
2615
2616        assert!(idms_prox_write.commit().is_ok());
2617    }
2618
2619    // Phase 5
2620    #[idm_test]
2621    async fn test_idm_scim_sync_phase_5_from_refresh_to_active(
2622        idms: &IdmServer,
2623        _idms_delayed: &mut IdmServerDelayed,
2624    ) {
2625        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2626        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2627        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2628        let sse = ScimSyncUpdateEvent {
2629            ident: ident.clone(),
2630        };
2631
2632        let changes = ScimSyncRequest {
2633            from_state: ScimSyncState::Refresh,
2634            to_state: ScimSyncState::Active {
2635                cookie: vec![1, 2, 3, 4],
2636            },
2637            entries: Vec::with_capacity(0),
2638            retain: ScimSyncRetentionMode::Ignore,
2639        };
2640
2641        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2642        assert!(idms_prox_write.commit().is_ok());
2643
2644        // Advance the from -> to state.
2645        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2646        let sse = ScimSyncUpdateEvent { ident };
2647
2648        let changes = ScimSyncRequest {
2649            from_state: ScimSyncState::Active {
2650                cookie: vec![1, 2, 3, 4],
2651            },
2652            to_state: ScimSyncState::Active {
2653                cookie: vec![2, 3, 4, 5],
2654            },
2655            entries: vec![],
2656            retain: ScimSyncRetentionMode::Ignore,
2657        };
2658
2659        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2660        assert!(idms_prox_write.commit().is_ok());
2661    }
2662
2663    // Test the client doing a sync refresh request (active -> refresh).
2664
2665    // Real sample data test
2666
2667    fn get_single_entry(
2668        name: &str,
2669        idms_prox_write: &mut IdmServerProxyWriteTransaction,
2670    ) -> Arc<EntrySealedCommitted> {
2671        idms_prox_write
2672            .qs_write
2673            .internal_search(filter!(f_eq(
2674                Attribute::Name,
2675                PartialValue::new_iname(name)
2676            )))
2677            .map_err(|_| ())
2678            .and_then(|mut entries| {
2679                if entries.len() != 1 {
2680                    error!("Incorrect number of results {:?}", entries);
2681                    Err(())
2682                } else {
2683                    entries.pop().ok_or(())
2684                }
2685            })
2686            .expect("Failed to access entry.")
2687    }
2688
2689    #[idm_test]
2690    async fn test_idm_scim_sync_refresh_ipa_example_1(
2691        idms: &IdmServer,
2692        _idms_delayed: &mut IdmServerDelayed,
2693    ) {
2694        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2695        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2696        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2697        let sse = ScimSyncUpdateEvent { ident };
2698
2699        let changes =
2700            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
2701
2702        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2703
2704        assert!(idms_prox_write.commit().is_ok());
2705
2706        // Test properties of the imported entries.
2707        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2708
2709        let testgroup = get_single_entry("testgroup", &mut idms_prox_write);
2710        assert!(
2711            testgroup.get_ava_single_iutf8(Attribute::SyncExternalId)
2712                == Some("cn=testgroup,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2713        );
2714        assert!(testgroup
2715            .get_ava_single_uint32(Attribute::GidNumber)
2716            .is_none());
2717
2718        let testposix = get_single_entry("testposix", &mut idms_prox_write);
2719        assert!(
2720            testposix.get_ava_single_iutf8(Attribute::SyncExternalId)
2721                == Some("cn=testposix,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2722        );
2723        assert_eq!(
2724            testposix.get_ava_single_uint32(Attribute::GidNumber),
2725            Some(1234567)
2726        );
2727
2728        let testexternal = get_single_entry("testexternal", &mut idms_prox_write);
2729        assert!(
2730            testexternal.get_ava_single_iutf8(Attribute::SyncExternalId)
2731                == Some("cn=testexternal,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2732        );
2733        assert!(testexternal
2734            .get_ava_single_uint32(Attribute::GidNumber)
2735            .is_none());
2736
2737        let testuser = get_single_entry("testuser", &mut idms_prox_write);
2738        assert!(
2739            testuser.get_ava_single_iutf8(Attribute::SyncExternalId)
2740                == Some("uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2741        );
2742        assert_eq!(
2743            testuser.get_ava_single_uint32(Attribute::GidNumber),
2744            Some(12345)
2745        );
2746        assert_eq!(
2747            testuser.get_ava_single_utf8(Attribute::DisplayName),
2748            Some("Test User")
2749        );
2750        assert_eq!(
2751            testuser.get_ava_single_iutf8(Attribute::LoginShell),
2752            Some("/bin/sh")
2753        );
2754
2755        let mut ssh_keyiter = testuser
2756            .get_ava_iter_sshpubkeys(Attribute::SshPublicKey)
2757            .expect("Failed to access ssh pubkeys");
2758
2759        assert_eq!(ssh_keyiter.next(), Some("sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBENubZikrb8hu+HeVRdZ0pp/VAk2qv4JDbuJhvD0yNdWDL2e3cBbERiDeNPkWx58Q4rVnxkbV1fa8E2waRtT91wAAAAEc3NoOg== testuser@fidokey".to_string()));
2760        assert_eq!(ssh_keyiter.next(), None);
2761
2762        // Check memberof works.
2763        let testgroup_mb = testgroup
2764            .get_ava_refer(Attribute::Member)
2765            .expect("No members!");
2766        assert!(testgroup_mb.contains(&testuser.get_uuid()));
2767
2768        let testposix_mb = testposix
2769            .get_ava_refer(Attribute::Member)
2770            .expect("No members!");
2771        assert!(testposix_mb.contains(&testuser.get_uuid()));
2772
2773        let testuser_mo = testuser
2774            .get_ava_refer(Attribute::MemberOf)
2775            .expect("No memberof!");
2776        assert!(testuser_mo.contains(&testposix.get_uuid()));
2777        assert!(testuser_mo.contains(&testgroup.get_uuid()));
2778
2779        assert!(idms_prox_write.commit().is_ok());
2780
2781        // Now apply updates.
2782        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2783        let changes =
2784            serde_json::from_str(TEST_SYNC_SCIM_IPA_2).expect("failed to parse scim sync");
2785
2786        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2787        assert!(idms_prox_write.commit().is_ok());
2788
2789        // Test properties of the updated entries.
2790        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2791
2792        // Deleted
2793        assert!(idms_prox_write
2794            .qs_write
2795            .internal_search(filter!(f_eq(
2796                Attribute::Name,
2797                PartialValue::new_iname("testgroup")
2798            )))
2799            .unwrap()
2800            .is_empty());
2801
2802        let testposix = get_single_entry("testposix", &mut idms_prox_write);
2803        info!("{:?}", testposix);
2804        assert!(
2805            testposix.get_ava_single_iutf8(Attribute::SyncExternalId)
2806                == Some("cn=testposix,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2807        );
2808        assert_eq!(
2809            testposix.get_ava_single_uint32(Attribute::GidNumber),
2810            Some(1234567)
2811        );
2812
2813        let testexternal = get_single_entry("testexternal2", &mut idms_prox_write);
2814        info!("{:?}", testexternal);
2815        assert!(
2816            testexternal.get_ava_single_iutf8(Attribute::SyncExternalId)
2817                == Some("cn=testexternal2,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2818        );
2819        assert!(testexternal
2820            .get_ava_single_uint32(Attribute::GidNumber)
2821            .is_none());
2822
2823        let testuser = get_single_entry("testuser", &mut idms_prox_write);
2824
2825        // Check memberof works.
2826        let testexternal_mb = testexternal
2827            .get_ava_refer(Attribute::Member)
2828            .expect("No members!");
2829        assert!(testexternal_mb.contains(&testuser.get_uuid()));
2830
2831        assert!(testposix.get_ava_refer(Attribute::Member).is_none());
2832
2833        let testuser_mo = testuser
2834            .get_ava_refer(Attribute::MemberOf)
2835            .expect("No memberof!");
2836        assert!(testuser_mo.contains(&testexternal.get_uuid()));
2837
2838        assert!(idms_prox_write.commit().is_ok());
2839    }
2840
2841    #[idm_test]
2842    async fn test_idm_scim_sync_refresh_ipa_example_2(
2843        idms: &IdmServer,
2844        _idms_delayed: &mut IdmServerDelayed,
2845    ) {
2846        let ct = Duration::from_secs(TEST_CURRENT_TIME);
2847        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
2848        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
2849        let sse = ScimSyncUpdateEvent { ident };
2850
2851        let changes =
2852            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
2853
2854        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2855
2856        let from_state = changes.to_state.clone();
2857
2858        // Indicate the next set of changes will be a refresh. Don't change content.
2859        // Strictly speaking this step isn't need.
2860
2861        let changes = ScimSyncRequest::need_refresh(from_state);
2862        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2863
2864        // Check entries still remain as expected.
2865        let testgroup = get_single_entry("testgroup", &mut idms_prox_write);
2866        assert!(
2867            testgroup.get_ava_single_iutf8(Attribute::SyncExternalId)
2868                == Some("cn=testgroup,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2869        );
2870        assert!(testgroup
2871            .get_ava_single_uint32(Attribute::GidNumber)
2872            .is_none());
2873
2874        let testposix = get_single_entry("testposix", &mut idms_prox_write);
2875        assert!(
2876            testposix.get_ava_single_iutf8(Attribute::SyncExternalId)
2877                == Some("cn=testposix,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2878        );
2879        assert_eq!(
2880            testposix.get_ava_single_uint32(Attribute::GidNumber),
2881            Some(1234567)
2882        );
2883
2884        let testexternal = get_single_entry("testexternal", &mut idms_prox_write);
2885        assert!(
2886            testexternal.get_ava_single_iutf8(Attribute::SyncExternalId)
2887                == Some("cn=testexternal,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2888        );
2889        assert!(testexternal
2890            .get_ava_single_uint32(Attribute::GidNumber)
2891            .is_none());
2892
2893        let testuser = get_single_entry("testuser", &mut idms_prox_write);
2894        assert!(
2895            testuser.get_ava_single_iutf8(Attribute::SyncExternalId)
2896                == Some("uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2897        );
2898        assert_eq!(
2899            testuser.get_ava_single_uint32(Attribute::GidNumber),
2900            Some(12345)
2901        );
2902        assert_eq!(
2903            testuser.get_ava_single_utf8(Attribute::DisplayName),
2904            Some("Test User")
2905        );
2906        assert_eq!(
2907            testuser.get_ava_single_iutf8(Attribute::LoginShell),
2908            Some("/bin/sh")
2909        );
2910
2911        // Check memberof works.
2912        let testgroup_mb = testgroup
2913            .get_ava_refer(Attribute::Member)
2914            .expect("No members!");
2915        assert!(testgroup_mb.contains(&testuser.get_uuid()));
2916
2917        let testposix_mb = testposix
2918            .get_ava_refer(Attribute::Member)
2919            .expect("No members!");
2920        assert!(testposix_mb.contains(&testuser.get_uuid()));
2921
2922        let testuser_mo = testuser
2923            .get_ava_refer(Attribute::MemberOf)
2924            .expect("No memberof!");
2925        assert!(testuser_mo.contains(&testposix.get_uuid()));
2926        assert!(testuser_mo.contains(&testgroup.get_uuid()));
2927
2928        // Now, the next change is the refresh.
2929
2930        let changes =
2931            serde_json::from_str(TEST_SYNC_SCIM_IPA_REFRESH_1).expect("failed to parse scim sync");
2932
2933        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
2934
2935        assert!(idms_prox_write
2936            .qs_write
2937            .internal_search(filter!(f_eq(
2938                Attribute::Name,
2939                PartialValue::new_iname("testposix")
2940            )))
2941            .unwrap()
2942            .is_empty());
2943
2944        assert!(idms_prox_write
2945            .qs_write
2946            .internal_search(filter!(f_eq(
2947                Attribute::Name,
2948                PartialValue::new_iname("testexternal")
2949            )))
2950            .unwrap()
2951            .is_empty());
2952
2953        let testgroup = get_single_entry("testgroup", &mut idms_prox_write);
2954        assert!(
2955            testgroup.get_ava_single_iutf8(Attribute::SyncExternalId)
2956                == Some("cn=testgroup,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2957        );
2958        assert!(testgroup
2959            .get_ava_single_uint32(Attribute::GidNumber)
2960            .is_none());
2961
2962        let testuser = get_single_entry("testuser", &mut idms_prox_write);
2963        assert!(
2964            testuser.get_ava_single_iutf8(Attribute::SyncExternalId)
2965                == Some("uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au")
2966        );
2967        assert_eq!(
2968            testuser.get_ava_single_uint32(Attribute::GidNumber),
2969            Some(12345)
2970        );
2971        assert_eq!(
2972            testuser.get_ava_single_utf8(Attribute::DisplayName),
2973            Some("Test User")
2974        );
2975        assert_eq!(
2976            testuser.get_ava_single_iutf8(Attribute::LoginShell),
2977            Some("/bin/sh")
2978        );
2979
2980        // Check memberof works.
2981        let testgroup_mb = testgroup
2982            .get_ava_refer(Attribute::Member)
2983            .expect("No members!");
2984        assert!(testgroup_mb.contains(&testuser.get_uuid()));
2985
2986        let testuser_mo = testuser
2987            .get_ava_refer(Attribute::MemberOf)
2988            .expect("No memberof!");
2989        assert!(testuser_mo.contains(&testgroup.get_uuid()));
2990
2991        assert!(idms_prox_write.commit().is_ok());
2992    }
2993
2994    #[idm_test]
2995    async fn test_idm_scim_sync_yield_authority(
2996        idms: &IdmServer,
2997        _idms_delayed: &mut IdmServerDelayed,
2998    ) {
2999        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3000        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3001        let (sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3002        let sse = ScimSyncUpdateEvent { ident };
3003
3004        let changes =
3005            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
3006
3007        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3008
3009        // Now we set the sync agreement to have description yielded.
3010        assert!(idms_prox_write
3011            .qs_write
3012            .internal_modify_uuid(
3013                sync_uuid,
3014                &ModifyList::new_purge_and_set(
3015                    Attribute::SyncYieldAuthority,
3016                    Value::new_iutf8n(Attribute::LegalName.as_ref())
3017                )
3018            )
3019            .is_ok());
3020
3021        let testuser_filter = filter!(f_eq(Attribute::Name, PartialValue::new_iname("testuser")));
3022
3023        // We then can change our user.
3024        assert!(idms_prox_write
3025            .qs_write
3026            .internal_modify(
3027                &testuser_filter,
3028                &ModifyList::new_purge_and_set(
3029                    Attribute::LegalName,
3030                    Value::Utf8("Test Userington the First".to_string())
3031                )
3032            )
3033            .is_ok());
3034
3035        let changes =
3036            serde_json::from_str(TEST_SYNC_SCIM_IPA_REFRESH_1).expect("failed to parse scim sync");
3037
3038        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3039
3040        // Finally, now the gidnumber should not have changed.
3041        let testuser = idms_prox_write
3042            .qs_write
3043            .internal_search(testuser_filter)
3044            .map(|mut results| results.pop().expect("Empty result set"))
3045            .expect("Failed to access testuser");
3046
3047        assert!(
3048            testuser.get_ava_single_utf8(Attribute::LegalName) == Some("Test Userington the First")
3049        );
3050
3051        assert!(idms_prox_write.commit().is_ok());
3052    }
3053
3054    #[idm_test]
3055    async fn test_idm_scim_sync_finalise_1(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
3056        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3057        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3058        let (sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3059        let sse = ScimSyncUpdateEvent { ident };
3060
3061        let changes =
3062            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
3063
3064        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3065
3066        assert!(idms_prox_write.commit().is_ok());
3067
3068        // Finalise the sync account.
3069        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3070
3071        let ident = idms_prox_write
3072            .qs_write
3073            .internal_search_uuid(UUID_ADMIN)
3074            .map(Identity::from_impersonate_entry_readwrite)
3075            .expect("Failed to get admin");
3076
3077        let sfe = ScimSyncFinaliseEvent {
3078            ident,
3079            target: sync_uuid,
3080        };
3081
3082        idms_prox_write
3083            .scim_sync_finalise(&sfe)
3084            .expect("Failed to finalise sync account");
3085
3086        // Check that the entries still exists but now have no sync_object attached.
3087        let testgroup = get_single_entry("testgroup", &mut idms_prox_write);
3088        assert!(!testgroup.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3089
3090        let testposix = get_single_entry("testposix", &mut idms_prox_write);
3091        assert!(!testposix.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3092
3093        let testexternal = get_single_entry("testexternal", &mut idms_prox_write);
3094        assert!(!testexternal.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3095
3096        let testuser = get_single_entry("testuser", &mut idms_prox_write);
3097        assert!(!testuser.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3098
3099        assert!(idms_prox_write.commit().is_ok());
3100    }
3101
3102    #[idm_test]
3103    async fn test_idm_scim_sync_finalise_2(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
3104        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3105        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3106        let (sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3107        let sse = ScimSyncUpdateEvent { ident };
3108
3109        let changes =
3110            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
3111
3112        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3113
3114        // The difference in this test is that the refresh deletes some entries
3115        // so the recycle bin case needs to be handled.
3116        let changes =
3117            serde_json::from_str(TEST_SYNC_SCIM_IPA_REFRESH_1).expect("failed to parse scim sync");
3118
3119        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3120
3121        assert!(idms_prox_write.commit().is_ok());
3122
3123        // Finalise the sync account.
3124        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3125
3126        let ident = idms_prox_write
3127            .qs_write
3128            .internal_search_uuid(UUID_ADMIN)
3129            .map(Identity::from_impersonate_entry_readwrite)
3130            .expect("Failed to get admin");
3131
3132        let sfe = ScimSyncFinaliseEvent {
3133            ident,
3134            target: sync_uuid,
3135        };
3136
3137        idms_prox_write
3138            .scim_sync_finalise(&sfe)
3139            .expect("Failed to finalise sync account");
3140
3141        // Check that the entries still exists but now have no sync_object attached.
3142        let testgroup = get_single_entry("testgroup", &mut idms_prox_write);
3143        assert!(!testgroup.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3144
3145        let testuser = get_single_entry("testuser", &mut idms_prox_write);
3146        assert!(!testuser.attribute_equality(Attribute::Class, &EntryClass::SyncObject.into()));
3147
3148        for iname in ["testposix", "testexternal"] {
3149            trace!(%iname);
3150            assert!(idms_prox_write
3151                .qs_write
3152                .internal_search(filter!(f_eq(
3153                    Attribute::Name,
3154                    PartialValue::new_iname(iname)
3155                )))
3156                .unwrap()
3157                .is_empty());
3158        }
3159
3160        assert!(idms_prox_write.commit().is_ok());
3161    }
3162
3163    #[idm_test]
3164    async fn test_idm_scim_sync_terminate_1(
3165        idms: &IdmServer,
3166        _idms_delayed: &mut IdmServerDelayed,
3167    ) {
3168        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3169        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3170        let (sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3171        let sse = ScimSyncUpdateEvent { ident };
3172
3173        let changes =
3174            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
3175
3176        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3177
3178        assert!(idms_prox_write.commit().is_ok());
3179
3180        // Terminate the sync account
3181        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3182
3183        let ident = idms_prox_write
3184            .qs_write
3185            .internal_search_uuid(UUID_ADMIN)
3186            .map(Identity::from_impersonate_entry_readwrite)
3187            .expect("Failed to get admin");
3188
3189        let sfe = ScimSyncTerminateEvent {
3190            ident,
3191            target: sync_uuid,
3192        };
3193
3194        idms_prox_write
3195            .scim_sync_terminate(&sfe)
3196            .expect("Failed to terminate sync account");
3197
3198        // Check that the entries no longer exist
3199        for iname in ["testgroup", "testposix", "testexternal", "testuser"] {
3200            trace!(%iname);
3201            assert!(idms_prox_write
3202                .qs_write
3203                .internal_search(filter!(f_eq(
3204                    Attribute::Name,
3205                    PartialValue::new_iname(iname)
3206                )))
3207                .unwrap()
3208                .is_empty());
3209        }
3210
3211        assert!(idms_prox_write.commit().is_ok());
3212    }
3213
3214    #[idm_test]
3215    async fn test_idm_scim_sync_terminate_2(
3216        idms: &IdmServer,
3217        _idms_delayed: &mut IdmServerDelayed,
3218    ) {
3219        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3220        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3221        let (sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3222        let sse = ScimSyncUpdateEvent { ident };
3223
3224        let changes =
3225            serde_json::from_str(TEST_SYNC_SCIM_IPA_1).expect("failed to parse scim sync");
3226
3227        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3228
3229        // The difference in this test is that the refresh deletes some entries
3230        // so the recycle bin case needs to be handled.
3231        let changes =
3232            serde_json::from_str(TEST_SYNC_SCIM_IPA_REFRESH_1).expect("failed to parse scim sync");
3233
3234        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3235
3236        assert!(idms_prox_write.commit().is_ok());
3237
3238        // Terminate the sync account
3239        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3240
3241        let ident = idms_prox_write
3242            .qs_write
3243            .internal_search_uuid(UUID_ADMIN)
3244            .map(Identity::from_impersonate_entry_readwrite)
3245            .expect("Failed to get admin");
3246
3247        let sfe = ScimSyncTerminateEvent {
3248            ident,
3249            target: sync_uuid,
3250        };
3251
3252        idms_prox_write
3253            .scim_sync_terminate(&sfe)
3254            .expect("Failed to terminate sync account");
3255
3256        // Check that the entries no longer exist
3257        for iname in ["testgroup", "testposix", "testexternal", "testuser"] {
3258            trace!(%iname);
3259            assert!(idms_prox_write
3260                .qs_write
3261                .internal_search(filter!(f_eq(
3262                    Attribute::Name,
3263                    PartialValue::new_iname(iname)
3264                )))
3265                .unwrap()
3266                .is_empty());
3267        }
3268
3269        assert!(idms_prox_write.commit().is_ok());
3270    }
3271
3272    #[idm_test]
3273    /// Assert that a SCIM JSON proto entry correctly serialises and deserialises
3274    /// and can be applied as a changeset. This serialisation is performed during
3275    /// the ScimEntry::try_from step.
3276    async fn test_idm_scim_sync_json_proto(idms: &IdmServer, _idms_delayed: &mut IdmServerDelayed) {
3277        let ct = Duration::from_secs(TEST_CURRENT_TIME);
3278        let mut idms_prox_write = idms.proxy_write(ct).await.unwrap();
3279        let (_sync_uuid, ident) = test_scim_sync_apply_setup_ident(&mut idms_prox_write, ct);
3280        let sse = ScimSyncUpdateEvent { ident };
3281
3282        // Minimum Viable Person
3283        let person_1 = ScimSyncPerson::builder(
3284            Uuid::new_v4(),
3285            "cn=testperson_1".to_string(),
3286            "testperson_1".to_string(),
3287            "Test Person One".to_string(),
3288        )
3289        .build()
3290        .try_into()
3291        .unwrap();
3292
3293        // Minimum Viable Group
3294        let group_1 = ScimSyncGroup::builder(
3295            Uuid::new_v4(),
3296            "cn=testgroup_1".to_string(),
3297            "testgroup_1".to_string(),
3298        )
3299        .build()
3300        .try_into()
3301        .unwrap();
3302
3303        let user_sshkey = "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBENubZikrb8hu+HeVRdZ0pp/VAk2qv4JDbuJhvD0yNdWDL2e3cBbERiDeNPkWx58Q4rVnxkbV1fa8E2waRtT91wAAAAEc3NoOg== testuser@fidokey";
3304
3305        // All Attribute Person
3306        let person_2 = ScimSyncPerson::builder(
3307            Uuid::new_v4(),
3308            "cn=testperson_2".to_string(),
3309            "testperson_2".to_string(),
3310            "Test Person Two".to_string(),
3311        )
3312        .set_password_import(Some("ipaNTHash: iEb36u6PsRetBr3YMLdYbA".to_string()))
3313        .set_unix_password_import(Some("ipaNTHash: iEb36u6PsRetBr3YMLdYbA".to_string()))
3314        .set_totp_import(vec![ScimTotp {
3315            external_id: "Totp".to_string(),
3316            secret: "QICWZTON72IBS5MXWNURKAONC3JNOOOFMLKNRTIPXBYQ4BLRSEBM7KF5".to_string(),
3317            algo: "sha256".to_string(),
3318            step: 60,
3319            digits: 8,
3320        }])
3321        .set_mail(vec![MultiValueAttr {
3322            primary: Some(true),
3323            value: "testuser@example.com".to_string(),
3324            ..Default::default()
3325        }])
3326        .set_ssh_publickey(vec![ScimSshPubKey {
3327            label: "Key McKeyface".to_string(),
3328            value: user_sshkey.to_string(),
3329        }])
3330        .set_login_shell(Some("/bin/zsh".to_string()))
3331        .set_account_valid_from(Some("2023-11-28T04:57:55Z".to_string()))
3332        .set_account_expire(Some("2023-11-28T04:57:55Z".to_string()))
3333        .set_gidnumber(Some(12346))
3334        .build()
3335        .try_into()
3336        .unwrap();
3337
3338        // All Attribute Group
3339        let group_2 = ScimSyncGroup::builder(
3340            Uuid::new_v4(),
3341            "cn=testgroup_2".to_string(),
3342            "testgroup_2".to_string(),
3343        )
3344        .set_description(Some("description".to_string()))
3345        .set_gidnumber(Some(12345))
3346        .set_members(vec!["cn=testperson_1".to_string(), "cn=testperson_2".to_string()].into_iter())
3347        .build()
3348        .try_into()
3349        .unwrap();
3350
3351        let entries = vec![person_1, group_1, person_2, group_2];
3352
3353        let changes = ScimSyncRequest {
3354            from_state: ScimSyncState::Refresh,
3355            to_state: ScimSyncState::Active {
3356                cookie: vec![1, 2, 3, 4],
3357            },
3358            entries,
3359            retain: ScimSyncRetentionMode::Ignore,
3360        };
3361
3362        assert!(idms_prox_write.scim_sync_apply(&sse, &changes, ct).is_ok());
3363        assert!(idms_prox_write.commit().is_ok());
3364    }
3365
3366    const TEST_SYNC_SCIM_IPA_1: &str = r#"
3367{
3368  "from_state": "Refresh",
3369  "to_state": {
3370    "Active": {
3371      "cookie": "aXBhLXN5bmNyZXBsLWthbmkuZGV2LmJsYWNraGF0cy5uZXQuYXU6Mzg5I2NuPWRpcmVjdG9yeSBtYW5hZ2VyOmRjPWRldixkYz1ibGFja2hhdHMsZGM9bmV0LGRjPWF1Oih8KCYob2JqZWN0Q2xhc3M9cGVyc29uKShvYmplY3RDbGFzcz1pcGFudHVzZXJhdHRycykob2JqZWN0Q2xhc3M9cG9zaXhhY2NvdW50KSkoJihvYmplY3RDbGFzcz1ncm91cG9mbmFtZXMpKG9iamVjdENsYXNzPWlwYXVzZXJncm91cCkoIShvYmplY3RDbGFzcz1tZXBtYW5hZ2VkZW50cnkpKSghKGNuPWFkbWlucykpKCEoY249aXBhdXNlcnMpKSkoJihvYmplY3RDbGFzcz1pcGF0b2tlbikob2JqZWN0Q2xhc3M9aXBhdG9rZW50b3RwKSkpIzEzNQ"
3372    }
3373  },
3374  "entries": [
3375    {
3376      "schemas": [
3377        "urn:ietf:params:scim:schemas:kanidm:sync:1:person",
3378        "urn:ietf:params:scim:schemas:kanidm:sync:1:account",
3379        "urn:ietf:params:scim:schemas:kanidm:sync:1:posixaccount"
3380      ],
3381      "id": "babb8302-43a1-11ed-a50d-919b4b1a5ec0",
3382      "externalId": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3383      "displayname": "Test User",
3384      "gidnumber": 12345,
3385      "loginshell": "/bin/sh",
3386      "name": "testuser",
3387      "mail": [
3388        {
3389          "value": "testuser@dev.blackhats.net.au"
3390        }
3391      ],
3392      "ssh_publickey": [
3393        {
3394          "label": "ssh-key",
3395          "value": "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBENubZikrb8hu+HeVRdZ0pp/VAk2qv4JDbuJhvD0yNdWDL2e3cBbERiDeNPkWx58Q4rVnxkbV1fa8E2waRtT91wAAAAEc3NoOg== testuser@fidokey"
3396        }
3397      ],
3398      "unix_password_import": "ipaNTHash: iEb36u6PsRetBr3YMLdYbA",
3399      "password_import": "ipaNTHash: iEb36u6PsRetBr3YMLdYbA"
3400    },
3401    {
3402      "schemas": [
3403        "urn:ietf:params:scim:schemas:kanidm:sync:1:group"
3404      ],
3405      "id": "d547c581-5f26-11ed-a50d-919b4b1a5ec0",
3406      "externalId": "cn=testgroup,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3407      "description": "Test group",
3408      "member": [
3409        {
3410          "external_id": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au"
3411        }
3412      ],
3413      "name": "testgroup"
3414    },
3415    {
3416      "schemas": [
3417        "urn:ietf:params:scim:schemas:kanidm:sync:1:group"
3418      ],
3419      "id": "d547c583-5f26-11ed-a50d-919b4b1a5ec0",
3420      "externalId": "cn=testexternal,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3421      "name": "testexternal"
3422    },
3423    {
3424      "schemas": [
3425        "urn:ietf:params:scim:schemas:kanidm:sync:1:group",
3426        "urn:ietf:params:scim:schemas:kanidm:sync:1:posixgroup"
3427      ],
3428      "id": "f90b0b81-5f26-11ed-a50d-919b4b1a5ec0",
3429      "externalId": "cn=testposix,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3430      "gidnumber": 1234567,
3431      "member": [
3432        {
3433          "external_id": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au"
3434        }
3435      ],
3436      "name": "testposix"
3437    }
3438  ],
3439  "retain": "Ignore"
3440}
3441    "#;
3442
3443    const TEST_SYNC_SCIM_IPA_2: &str = r#"
3444{
3445  "from_state": {
3446    "Active": {
3447      "cookie": "aXBhLXN5bmNyZXBsLWthbmkuZGV2LmJsYWNraGF0cy5uZXQuYXU6Mzg5I2NuPWRpcmVjdG9yeSBtYW5hZ2VyOmRjPWRldixkYz1ibGFja2hhdHMsZGM9bmV0LGRjPWF1Oih8KCYob2JqZWN0Q2xhc3M9cGVyc29uKShvYmplY3RDbGFzcz1pcGFudHVzZXJhdHRycykob2JqZWN0Q2xhc3M9cG9zaXhhY2NvdW50KSkoJihvYmplY3RDbGFzcz1ncm91cG9mbmFtZXMpKG9iamVjdENsYXNzPWlwYXVzZXJncm91cCkoIShvYmplY3RDbGFzcz1tZXBtYW5hZ2VkZW50cnkpKSghKGNuPWFkbWlucykpKCEoY249aXBhdXNlcnMpKSkoJihvYmplY3RDbGFzcz1pcGF0b2tlbikob2JqZWN0Q2xhc3M9aXBhdG9rZW50b3RwKSkpIzEzNQ"
3448    }
3449  },
3450  "to_state": {
3451    "Active": {
3452      "cookie": "aXBhLXN5bmNyZXBsLWthbmkuZGV2LmJsYWNraGF0cy5uZXQuYXU6Mzg5I2NuPWRpcmVjdG9yeSBtYW5hZ2VyOmRjPWRldixkYz1ibGFja2hhdHMsZGM9bmV0LGRjPWF1Oih8KCYob2JqZWN0Q2xhc3M9cGVyc29uKShvYmplY3RDbGFzcz1pcGFudHVzZXJhdHRycykob2JqZWN0Q2xhc3M9cG9zaXhhY2NvdW50KSkoJihvYmplY3RDbGFzcz1ncm91cG9mbmFtZXMpKG9iamVjdENsYXNzPWlwYXVzZXJncm91cCkoIShvYmplY3RDbGFzcz1tZXBtYW5hZ2VkZW50cnkpKSghKGNuPWFkbWlucykpKCEoY249aXBhdXNlcnMpKSkoJihvYmplY3RDbGFzcz1pcGF0b2tlbikob2JqZWN0Q2xhc3M9aXBhdG9rZW50b3RwKSkpIzE0MA"
3453    }
3454  },
3455  "entries": [
3456    {
3457      "schemas": [
3458        "urn:ietf:params:scim:schemas:kanidm:sync:1:group"
3459      ],
3460      "id": "d547c583-5f26-11ed-a50d-919b4b1a5ec0",
3461      "externalId": "cn=testexternal2,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3462      "member": [
3463        {
3464          "external_id": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au"
3465        }
3466      ],
3467      "name": "testexternal2"
3468    },
3469    {
3470      "schemas": [
3471        "urn:ietf:params:scim:schemas:kanidm:sync:1:group",
3472        "urn:ietf:params:scim:schemas:kanidm:sync:1:posixgroup"
3473      ],
3474      "id": "f90b0b81-5f26-11ed-a50d-919b4b1a5ec0",
3475      "externalId": "cn=testposix,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3476      "gidnumber": 1234567,
3477      "name": "testposix"
3478    }
3479  ],
3480  "retain": {
3481    "Delete": [
3482      "d547c581-5f26-11ed-a50d-919b4b1a5ec0"
3483    ]
3484  }
3485}
3486    "#;
3487
3488    const TEST_SYNC_SCIM_IPA_REFRESH_1: &str = r#"
3489{
3490  "from_state": "Refresh",
3491  "to_state": {
3492    "Active": {
3493      "cookie": "aXBhLXN5bmNyZXBsLWthbmkuZGV2LmJsYWNraGF0cy5uZXQuYXU6Mzg5I2NuPWRpcmVjdG9yeSBtYW5hZ2VyOmRjPWRldixkYz1ibGFja2hhdHMsZGM9bmV0LGRjPWF1Oih8KCYob2JqZWN0Q2xhc3M9cGVyc29uKShvYmplY3RDbGFzcz1pcGFudHVzZXJhdHRycykob2JqZWN0Q2xhc3M9cG9zaXhhY2NvdW50KSkoJihvYmplY3RDbGFzcz1ncm91cG9mbmFtZXMpKG9iamVjdENsYXNzPWlwYXVzZXJncm91cCkoIShvYmplY3RDbGFzcz1tZXBtYW5hZ2VkZW50cnkpKSghKGNuPWFkbWlucykpKCEoY249aXBhdXNlcnMpKSkoJihvYmplY3RDbGFzcz1pcGF0b2tlbikob2JqZWN0Q2xhc3M9aXBhdG9rZW50b3RwKSkpIzEzNQ"
3494    }
3495  },
3496  "entries": [
3497    {
3498      "schemas": [
3499        "urn:ietf:params:scim:schemas:kanidm:sync:1:person",
3500        "urn:ietf:params:scim:schemas:kanidm:sync:1:account",
3501        "urn:ietf:params:scim:schemas:kanidm:sync:1:posixaccount"
3502      ],
3503      "id": "babb8302-43a1-11ed-a50d-919b4b1a5ec0",
3504      "externalId": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3505      "displayname": "Test User",
3506      "gidnumber": 12345,
3507      "loginshell": "/bin/sh",
3508      "name": "testuser",
3509      "password_import": "ipaNTHash: iEb36u6PsRetBr3YMLdYbA",
3510      "unix_password_import": "ipaNTHash: iEb36u6PsRetBr3YMLdYbA",
3511      "account_valid_from": "2021-11-28T04:57:55Z",
3512      "account_expire": "2023-11-28T04:57:55Z"
3513    },
3514    {
3515      "schemas": [
3516        "urn:ietf:params:scim:schemas:kanidm:sync:1:group"
3517      ],
3518      "id": "d547c581-5f26-11ed-a50d-919b4b1a5ec0",
3519      "externalId": "cn=testgroup,cn=groups,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au",
3520      "description": "Test group",
3521      "member": [
3522        {
3523          "external_id": "uid=testuser,cn=users,cn=accounts,dc=dev,dc=blackhats,dc=net,dc=au"
3524        }
3525      ],
3526      "name": "testgroup"
3527    }
3528  ],
3529  "retain": "Ignore"
3530}
3531    "#;
3532}