Skip to main content

kanidmd_lib/server/
recycle.rs

1use super::modify::ModifyPartial;
2use crate::{event::ReviveRecycledEvent, prelude::*, server::Plugins};
3use std::collections::BTreeMap;
4
5impl QueryServerWriteTransaction<'_> {
6    #[instrument(level = "debug", skip_all)]
7    pub fn purge_tombstones(&mut self) -> Result<usize, OperationError> {
8        // purge everything that is a tombstone.
9        let trim_cid = self.trim_cid().clone();
10        let anchor_cid = self.get_txn_cid().clone();
11
12        // Delete them - this is a TRUE delete, no going back now!
13        self.be_txn
14            .reap_tombstones(&anchor_cid, &trim_cid)
15            .map_err(|e| {
16                error!(err = ?e, "Tombstone purge operation failed (backend)");
17                e
18            })
19            .inspect(|_res| {
20                admin_info!("Tombstone purge operation success");
21            })
22    }
23
24    #[instrument(level = "debug", skip_all)]
25    pub fn purge_recycled(&mut self) -> Result<usize, OperationError> {
26        // Send everything that is recycled to tombstone
27        // Search all recycled
28        let cid = self.cid.sub_secs(RECYCLEBIN_MAX_AGE).map_err(|e| {
29            admin_error!(err = ?e, "Unable to generate search cid for purge_recycled");
30            e
31        })?;
32        let rc = self.internal_search(filter_all!(f_and!([
33            f_eq(Attribute::Class, EntryClass::Recycled.into()),
34            f_lt(Attribute::LastModifiedCid, PartialValue::new_cid(cid)),
35        ])))?;
36
37        if rc.is_empty() {
38            admin_debug!("No recycled items present - purge operation success");
39            return Ok(0);
40        }
41
42        // Modify them to strip all avas except uuid
43        let tombstone_cand: Result<Vec<_>, _> = rc
44            .iter()
45            .map(|e| {
46                e.to_tombstone(self.cid.clone())
47                    .validate(&self.schema)
48                    .map_err(|e| {
49                        admin_error!("Schema Violation in purge_recycled validate: {:?}", e);
50                        OperationError::SchemaViolation(e)
51                    })
52                    // seal if it worked.
53                    .map(|e| e.seal(&self.schema))
54            })
55            .collect();
56
57        let tombstone_cand = tombstone_cand?;
58        // it's enough to say "yeah we tried to touch this many" because
59        // we're using this to decide if we're going to commit the txn
60        let touched = tombstone_cand.len();
61
62        // Backend Modify
63        self.be_txn
64            .modify(&self.cid, &rc, &tombstone_cand)
65            .map_err(|e| {
66                admin_error!("Purge recycled operation failed (backend), {:?}", e);
67                e
68            })
69            .map(|_| {
70                admin_info!("Purge recycled operation success");
71                touched
72            })
73    }
74
75    #[instrument(level = "debug", skip_all)]
76    /// Delete all items that have expired / delete_after *now*.
77    pub fn purge_delete_after(&mut self) -> Result<usize, OperationError> {
78        let curtime_odt = self.get_curtime_odt();
79
80        let filter = filter!(f_and(vec![
81            f_pres(Attribute::DeleteAfter),
82            f_lt(Attribute::DeleteAfter, PartialValue::DateTime(curtime_odt))
83        ]));
84
85        // First, search to see if anything matches.
86        let entries = self.internal_search(filter.clone())?;
87
88        if entries.is_empty() {
89            return Ok(0);
90        }
91
92        self.internal_delete(&filter)?;
93
94        Ok(entries.len())
95    }
96
97    #[instrument(level = "debug", skip_all)]
98    pub fn revive_recycled(&mut self, re: &ReviveRecycledEvent) -> Result<(), OperationError> {
99        // Revive an entry to live. This is a specialised function, and draws a lot of
100        // inspiration from modify.
101        //
102        // Access is granted by the ability to ability to search the class=recycled
103        // and the ability modify + remove that class from the object.
104        if !re.ident.is_internal() {
105            security_info!(name = %re.ident, "revive initiator");
106        }
107
108        // Get the list of pre_candidates, using impersonate search.
109        let mut pre_candidates =
110            self.impersonate_search_valid(re.filter.clone(), re.filter.clone(), &re.ident)?;
111
112        // Is the list empty?
113        if pre_candidates.is_empty() {
114            if re.ident.is_internal() {
115                trace!(
116                    "revive: no candidates match filter ... continuing {:?}",
117                    re.filter
118                );
119                return Ok(());
120            } else {
121                error!(
122                    "revive: no candidates match filter, failure {:?}",
123                    re.filter
124                );
125                return Err(OperationError::NoMatchingEntries);
126            }
127        };
128
129        trace!("revive: pre_candidates -> {:?}", pre_candidates);
130
131        // Check access against a "fake" modify.
132        let modlist = ModifyList::new_list(vec![Modify::Removed(
133            Attribute::Class,
134            EntryClass::Recycled.into(),
135        )]);
136
137        let m_valid = modlist.validate(self.get_schema()).map_err(|e| {
138            admin_error!("revive recycled modlist Schema Violation {:?}", e);
139            OperationError::SchemaViolation(e)
140        })?;
141
142        let me =
143            ModifyEvent::new_impersonate(&re.ident, re.filter.clone(), re.filter.clone(), m_valid);
144
145        let access = self.get_accesscontrols();
146        let op_allow = access
147            .modify_allow_operation(&me, &pre_candidates)
148            .map_err(|e| {
149                admin_error!("Unable to check modify access {:?}", e);
150                e
151            })?;
152        if !op_allow {
153            return Err(OperationError::AccessDenied);
154        }
155
156        // Are all of the entries actually recycled?
157        if pre_candidates.iter().all(|e| e.mask_recycled().is_some()) {
158            admin_warn!("Refusing to revive entries that are already live!");
159            return Err(OperationError::AccessDenied);
160        }
161
162        // ======= Access Control and Invariants Checked !!! ========
163
164        // From the pre_candidate set, find all related entries that also need to
165        // be revived at the same time.
166        let references_filt = filter_rec!(f_or(
167            pre_candidates
168                .iter()
169                .map(|entry| {
170                    f_eq(
171                        Attribute::CascadeDeleted,
172                        PartialValue::Uuid(entry.get_uuid()),
173                    )
174                })
175                .collect(),
176        ));
177
178        let mut pre_cascade_revive_candidates = self
179            .internal_search(references_filt)
180            .inspect_err(|err| error!(?err, "unable to find reference entries"))?;
181
182        pre_candidates.append(&mut pre_cascade_revive_candidates);
183
184        // clone the writeable entries.
185        let mut candidates: Vec<Entry<EntryInvalid, EntryCommitted>> = pre_candidates
186            .iter()
187            .map(|er| {
188                er.as_ref()
189                    .clone()
190                    .invalidate(self.cid.clone(), &self.trim_cid)
191            })
192            // Restore their Refers attribute.
193            .map(|mut entry| {
194                if let Some(refers_uuid) = entry.get_ava_single_uuid(Attribute::CascadeDeleted) {
195                    entry.set_ava_set(&Attribute::Refers, ValueSetRefer::new(refers_uuid));
196                }
197                entry
198            })
199            // Mutate to apply the revive.
200            .map(|er| er.to_revived())
201            .collect();
202
203        // Are they all revived?
204        if candidates.iter().all(|e| e.mask_recycled().is_none()) {
205            error!("Not all candidates were correctly revived, unable to proceed");
206            return Err(OperationError::InvalidEntryState);
207        }
208
209        // Were there any established memorials to these entries?
210        let memoriam_filters = candidates
211            .iter()
212            .filter_map(|entry| {
213                entry
214                    .get_uuid()
215                    .map(PartialValue::Uuid)
216                    .map(|pv| f_eq(Attribute::InMemoriam, pv))
217            })
218            .collect::<Vec<_>>();
219
220        let memorial_candidates = self.internal_search(filter!(f_and(vec![
221            f_eq(Attribute::Class, EntryClass::Memorial.into()),
222            f_or(memoriam_filters)
223        ])))?;
224
225        if !memorial_candidates.is_empty() {
226            // We need to create a linkage between the memorial and the entry.
227            let memorial_map: BTreeMap<Uuid, &EntrySealedCommitted> = memorial_candidates
228                .iter()
229                .map(|entry| (entry.get_uuid(), entry.as_ref()))
230                .collect();
231
232            // We need to setup a map of the pairs, so we can mod candidates based on the content
233            // of their memorials. For example, we want to ensure that any hmacNameHistories
234            // that were merged on memorials, are all brought back together.
235            let mut memorial_candidate_pairs: Vec<(
236                &EntrySealedCommitted,
237                &mut EntryInvalidCommitted,
238            )> = candidates
239                .iter_mut()
240                .filter_map(|entry| {
241                    entry
242                        .get_uuid()
243                        .and_then(|uuid| memorial_map.get(&uuid).map(|memorial| (*memorial, entry)))
244                })
245                .collect();
246
247            // If so, we need to clean them up NOW!
248            Plugins::run_teardown_memorials(self, &mut memorial_candidate_pairs, re).inspect_err(
249                |err| {
250                    error!(?err, "Revive operation failed (plugin)");
251                },
252            )?;
253
254            // Delete the memorials NOW! Unlike a normal delete, go STRAIGHT TO TOMBSTONE!!!
255            let tombstone_cand = memorial_candidates
256                .iter()
257                .map(|e| {
258                    e.to_tombstone(self.cid.clone())
259                        .validate(&self.schema)
260                        .map_err(|e| {
261                            error!("Schema Violation in teardown memorials validation: {:?}", e);
262                            OperationError::SchemaViolation(e)
263                        })
264                        // seal if it worked.
265                        .map(|e| e.seal(&self.schema))
266                })
267                .collect::<Result<Vec<_>, _>>()?;
268
269            self.be_txn
270                .modify(&self.cid, &memorial_candidates, &tombstone_cand)
271                .inspect_err(|err| {
272                    error!(?err, "Teardown memorials operation failed (backend)");
273                })?;
274        };
275
276        // Do we need to apply pre-mod?
277        // Very likely, in case domain has renamed etc.
278        Plugins::run_pre_modify(self, &pre_candidates, &mut candidates, &me).inspect_err(
279            |err| {
280                error!(?err, "Revive operation failed (plugin)");
281            },
282        )?;
283
284        // Schema validate
285        let res: Result<Vec<Entry<EntrySealed, EntryCommitted>>, OperationError> = candidates
286            .into_iter()
287            .map(|e| {
288                e.validate(&self.schema)
289                    .map_err(|e| {
290                        admin_error!("Schema Violation {:?}", e);
291                        OperationError::SchemaViolation(e)
292                    })
293                    .map(|e| e.seal(&self.schema))
294            })
295            .collect();
296
297        let norm_cand: Vec<Entry<_, _>> = res?;
298
299        // Finally, setup the mod for restoring memberships from direct member of
300        let mut dm_mods: BTreeMap<Uuid, ModifyList<ModifyInvalid>> = Default::default();
301
302        for entry in &pre_candidates {
303            // Get this entry's uuid.
304            let u: Uuid = entry.get_uuid();
305
306            if let Some(riter) = entry.get_ava_as_refuuid(Attribute::RecycledDirectMemberOf) {
307                for g_uuid in riter {
308                    dm_mods
309                        .entry(g_uuid)
310                        .and_modify(|mlist| {
311                            let m = Modify::Present(Attribute::Member, Value::ReferN(u));
312                            mlist.push_mod(m);
313                        })
314                        .or_insert({
315                            let m = Modify::Present(Attribute::Member, Value::ReferN(u));
316                            ModifyList::new_list(vec![m])
317                        });
318                }
319            }
320        }
321
322        // build the mod partial
323        let mp = ModifyPartial {
324            norm_cand,
325            pre_candidates,
326            me: &me,
327        };
328
329        // Call modify_apply
330        self.modify_apply(mp)?;
331
332        // If and only if that succeeds, apply the direct membership modifications
333        // if possible.
334        for (g, mods) in dm_mods {
335            // I think the filter/filter_all shouldn't matter here because the only
336            // valid direct memberships should be still valid/live references, as refint
337            // removes anything that was deleted even from recycled entries.
338            let f = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(g)));
339            self.internal_modify(&f, &mods)?;
340        }
341
342        Ok(())
343    }
344
345    #[cfg(test)]
346    pub(crate) fn internal_revive_uuid(&mut self, target_uuid: Uuid) -> Result<(), OperationError> {
347        // Note the use of filter_rec here for only recycled targets.
348        let filter = filter_rec!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
349        let f_valid = filter
350            .validate(self.get_schema())
351            .map_err(OperationError::SchemaViolation)?;
352        let re = ReviveRecycledEvent::new_internal(f_valid);
353        self.revive_recycled(&re)
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use super::ReviveRecycledEvent;
360    use crate::{
361        event::{CreateEvent, DeleteEvent},
362        prelude::*,
363        server::{ModifyEvent, SearchEvent, ValueSetMessage},
364    };
365    use kanidm_proto::v1::OutboundMessage;
366    use time::OffsetDateTime;
367
368    #[qs_test]
369    async fn test_recycle_simple(server: &QueryServer) {
370        // First we setup some timestamps
371        let time_p1 = duration_from_epoch_now();
372        let time_p2 = time_p1 + Duration::from_secs(RECYCLEBIN_MAX_AGE * 2);
373
374        let mut server_txn = server.write(time_p1).await.unwrap();
375        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
376
377        let filt_i_rc = filter_all!(f_eq(Attribute::Class, EntryClass::Recycled.into()));
378
379        let filt_i_ts = filter_all!(f_eq(Attribute::Class, EntryClass::Tombstone.into()));
380
381        let filt_i_per = filter_all!(f_eq(Attribute::Class, EntryClass::Person.into()));
382
383        // Create fake external requests. Probably from admin later
384        let me_rc = ModifyEvent::new_impersonate_entry(
385            admin.clone(),
386            filt_i_rc.clone(),
387            ModifyList::new_list(vec![Modify::Present(
388                Attribute::Class,
389                EntryClass::Recycled.into(),
390            )]),
391        );
392
393        let de_rc = DeleteEvent::new_impersonate_entry(admin.clone(), filt_i_rc.clone());
394
395        let se_rc = SearchEvent::new_ext_impersonate_entry(admin.clone(), filt_i_rc.clone());
396
397        let sre_rc = SearchEvent::new_rec_impersonate_entry(admin.clone(), filt_i_rc.clone());
398
399        let rre_rc = ReviveRecycledEvent::new_impersonate_entry(
400            admin,
401            filter_all!(f_eq(
402                Attribute::Name,
403                PartialValue::new_iname("testperson1")
404            )),
405        );
406
407        // Create some recycled objects
408        let e1 = entry_init!(
409            (Attribute::Class, EntryClass::Object.to_value()),
410            (Attribute::Class, EntryClass::Account.to_value()),
411            (Attribute::Class, EntryClass::Person.to_value()),
412            (Attribute::Name, Value::new_iname("testperson1")),
413            (
414                Attribute::Uuid,
415                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
416            ),
417            (Attribute::Description, Value::new_utf8s("testperson1")),
418            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
419        );
420
421        let e2 = entry_init!(
422            (Attribute::Class, EntryClass::Object.to_value()),
423            (Attribute::Class, EntryClass::Account.to_value()),
424            (Attribute::Class, EntryClass::Person.to_value()),
425            (Attribute::Name, Value::new_iname("testperson2")),
426            (
427                Attribute::Uuid,
428                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63932"))
429            ),
430            (Attribute::Description, Value::new_utf8s("testperson2")),
431            (Attribute::DisplayName, Value::new_utf8s("testperson2"))
432        );
433
434        let ce = CreateEvent::new_internal(vec![e1, e2]);
435        let cr = server_txn.create(&ce);
436        assert!(cr.is_ok());
437
438        // Now we immediately delete these to force them to the correct state.
439        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_or!([
440            f_eq(Attribute::Name, PartialValue::new_iname("testperson1")),
441            f_eq(Attribute::Name, PartialValue::new_iname("testperson2")),
442        ])));
443        assert!(server_txn.delete(&de_sin).is_ok());
444
445        // Can it be seen (external search)
446        let r1 = server_txn.search(&se_rc).expect("search failed");
447        assert!(r1.is_empty());
448
449        // Can it be deleted (external delete)
450        // Should be err-no candidates.
451        assert!(server_txn.delete(&de_rc).is_err());
452
453        // Can it be modified? (external modify)
454        // Should be err-no candidates
455        assert!(server_txn.modify(&me_rc).is_err());
456
457        // Can in be seen by special search? (external recycle search)
458        let r2 = server_txn.search(&sre_rc).expect("search failed");
459        assert_eq!(r2.len(), 2);
460
461        // Can it be seen (internal search)
462        // Internal search should see it.
463        let r2 = server_txn
464            .internal_search(filt_i_rc.clone())
465            .expect("internal search failed");
466        assert_eq!(r2.len(), 2);
467
468        // There are now two paths forward
469        //  revival or purge!
470        assert!(server_txn.revive_recycled(&rre_rc).is_ok());
471
472        // Not enough time has passed, won't have an effect for purge to TS
473        assert!(server_txn.purge_recycled().is_ok());
474        let r3 = server_txn
475            .internal_search(filt_i_rc.clone())
476            .expect("internal search failed");
477        assert_eq!(r3.len(), 1);
478
479        // Commit
480        assert!(server_txn.commit().is_ok());
481
482        // Now, establish enough time for the recycled items to be purged.
483        let mut server_txn = server.write(time_p2).await.unwrap();
484
485        //  purge to tombstone, now that time has passed.
486        assert!(server_txn.purge_recycled().is_ok());
487
488        // Should be no recycled objects.
489        let r4 = server_txn
490            .internal_search(filt_i_rc.clone())
491            .expect("internal search failed");
492        assert!(r4.is_empty());
493
494        // There should be one tombstone
495        let r5 = server_txn
496            .internal_search(filt_i_ts.clone())
497            .expect("internal search failed");
498        assert_eq!(r5.len(), 1);
499
500        // There should be one entry
501        let r6 = server_txn
502            .internal_search(filt_i_per.clone())
503            .expect("internal search failed");
504        assert_eq!(r6.len(), 1);
505
506        assert!(server_txn.commit().is_ok());
507    }
508
509    // The delete test above should be unaffected by recycle anyway
510    #[qs_test]
511    async fn test_qs_recycle_advanced(server: &QueryServer) {
512        // Create items
513        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
514        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
515
516        let e1 = entry_init!(
517            (Attribute::Class, EntryClass::Object.to_value()),
518            (Attribute::Class, EntryClass::Account.to_value()),
519            (Attribute::Class, EntryClass::Person.to_value()),
520            (Attribute::Name, Value::new_iname("testperson1")),
521            (
522                Attribute::Uuid,
523                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
524            ),
525            (Attribute::Description, Value::new_utf8s("testperson1")),
526            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
527        );
528        let ce = CreateEvent::new_internal(vec![e1]);
529
530        let cr = server_txn.create(&ce);
531        assert!(cr.is_ok());
532        // Delete and ensure they became recycled.
533        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_eq(
534            Attribute::Name,
535            PartialValue::new_iname("testperson1")
536        )));
537        assert!(server_txn.delete(&de_sin).is_ok());
538        // Can in be seen by special search? (external recycle search)
539        let filt_rc = filter_all!(f_eq(Attribute::Class, EntryClass::Recycled.into()));
540        let sre_rc = SearchEvent::new_rec_impersonate_entry(admin, filt_rc);
541        let r2 = server_txn.search(&sre_rc).expect("search failed");
542        assert_eq!(r2.len(), 1);
543
544        // Create dup uuid (rej)
545        // After a delete -> recycle, create duplicate name etc.
546        let cr = server_txn.create(&ce);
547        assert!(cr.is_err());
548
549        assert!(server_txn.commit().is_ok());
550    }
551
552    #[qs_test]
553    async fn test_uuid_to_star_recycle(server: &QueryServer) {
554        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
555
556        let e1 = entry_init!(
557            (Attribute::Class, EntryClass::Object.to_value()),
558            (Attribute::Class, EntryClass::Person.to_value()),
559            (Attribute::Class, EntryClass::Account.to_value()),
560            (Attribute::Name, Value::new_iname("testperson1")),
561            (
562                Attribute::Uuid,
563                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
564            ),
565            (Attribute::Description, Value::new_utf8s("testperson1")),
566            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
567        );
568
569        let tuuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
570
571        let ce = CreateEvent::new_internal(vec![e1]);
572        let cr = server_txn.create(&ce);
573        assert!(cr.is_ok());
574
575        assert_eq!(
576            server_txn.uuid_to_rdn(tuuid),
577            Ok("spn=testperson1@example.com".to_string())
578        );
579
580        assert!(
581            server_txn.uuid_to_spn(tuuid)
582                == Ok(Some(Value::new_spn_str("testperson1", "example.com")))
583        );
584
585        assert_eq!(server_txn.name_to_uuid("testperson1"), Ok(tuuid));
586
587        // delete
588        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_eq(
589            Attribute::Name,
590            PartialValue::new_iname("testperson1")
591        )));
592        assert!(server_txn.delete(&de_sin).is_ok());
593
594        // all should fail
595        assert!(
596            server_txn.uuid_to_rdn(tuuid)
597                == Ok("uuid=cc8e95b4-c24f-4d68-ba54-8bed76f63930".to_string())
598        );
599
600        assert_eq!(server_txn.uuid_to_spn(tuuid), Ok(None));
601
602        assert!(server_txn.name_to_uuid("testperson1").is_err());
603
604        // revive
605        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
606        let rre_rc = ReviveRecycledEvent::new_impersonate_entry(
607            admin,
608            filter_all!(f_eq(
609                Attribute::Name,
610                PartialValue::new_iname("testperson1")
611            )),
612        );
613        assert!(server_txn.revive_recycled(&rre_rc).is_ok());
614
615        // all checks pass
616
617        assert_eq!(
618            server_txn.uuid_to_rdn(tuuid),
619            Ok("spn=testperson1@example.com".to_string())
620        );
621
622        assert!(
623            server_txn.uuid_to_spn(tuuid)
624                == Ok(Some(Value::new_spn_str("testperson1", "example.com")))
625        );
626
627        assert_eq!(server_txn.name_to_uuid("testperson1"), Ok(tuuid));
628    }
629
630    #[qs_test]
631    async fn test_tombstone(server: &QueryServer) {
632        // First we setup some timestamps
633        let time_p1 = duration_from_epoch_now();
634        let time_p2 = time_p1 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
635        let time_p3 = time_p2 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
636
637        trace!("test_tombstone_start");
638        let mut server_txn = server.write(time_p1).await.unwrap();
639        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
640
641        let filt_i_ts = filter_all!(f_eq(Attribute::Class, EntryClass::Tombstone.into()));
642
643        // Create fake external requests. Probably from admin later
644        // Should we do this with impersonate instead of using the external
645        let me_ts = ModifyEvent::new_impersonate_entry(
646            admin.clone(),
647            filt_i_ts.clone(),
648            ModifyList::new_list(vec![Modify::Present(
649                Attribute::Class,
650                EntryClass::Tombstone.into(),
651            )]),
652        );
653
654        let de_ts = DeleteEvent::new_impersonate_entry(admin.clone(), filt_i_ts.clone());
655        let se_ts = SearchEvent::new_ext_impersonate_entry(admin, filt_i_ts.clone());
656
657        // First, create an entry, then push it through the lifecycle.
658        let e_ts = entry_init!(
659            (Attribute::Class, EntryClass::Object.to_value()),
660            (Attribute::Class, EntryClass::Account.to_value()),
661            (Attribute::Class, EntryClass::Person.to_value()),
662            (Attribute::Name, Value::new_iname("testperson1")),
663            (
664                Attribute::Uuid,
665                Value::Uuid(uuid!("9557f49c-97a5-4277-a9a5-097d17eb8317"))
666            ),
667            (Attribute::Description, Value::new_utf8s("testperson1")),
668            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
669        );
670
671        let ce = CreateEvent::new_internal(vec![e_ts]);
672        let cr = server_txn.create(&ce);
673        assert!(cr.is_ok());
674
675        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_or!([f_eq(
676            Attribute::Name,
677            PartialValue::new_iname("testperson1")
678        )])));
679        assert!(server_txn.delete(&de_sin).is_ok());
680
681        // Commit
682        assert!(server_txn.commit().is_ok());
683
684        // Now, establish enough time for the recycled items to be purged.
685        let mut server_txn = server.write(time_p2).await.unwrap();
686        assert!(server_txn.purge_recycled().is_ok());
687
688        // Now test the tombstone properties.
689
690        // Can it be seen (external search)
691        let r1 = server_txn.search(&se_ts).expect("search failed");
692        assert!(r1.is_empty());
693
694        // Can it be deleted (external delete)
695        // Should be err-no candidates.
696        assert!(server_txn.delete(&de_ts).is_err());
697
698        // Can it be modified? (external modify)
699        // Should be err-no candidates
700        assert!(server_txn.modify(&me_ts).is_err());
701
702        // Can it be seen (internal search)
703        // Internal search should see it.
704        let r2 = server_txn
705            .internal_search(filt_i_ts.clone())
706            .expect("internal search failed");
707        assert_eq!(r2.len(), 1);
708
709        // If we purge now, nothing happens, we aren't past the time window.
710        assert!(server_txn.purge_tombstones().is_ok());
711
712        let r3 = server_txn
713            .internal_search(filt_i_ts.clone())
714            .expect("internal search failed");
715        assert_eq!(r3.len(), 1);
716
717        // Commit
718        assert!(server_txn.commit().is_ok());
719
720        // New txn, push the cid forward.
721        let mut server_txn = server.write(time_p3).await.unwrap();
722
723        // Now purge
724        assert!(server_txn.purge_tombstones().is_ok());
725
726        // Assert it's gone
727        // Internal search should not see it.
728        let r4 = server_txn
729            .internal_search(filt_i_ts)
730            .expect("internal search failed");
731        assert!(r4.is_empty());
732
733        assert!(server_txn.commit().is_ok());
734    }
735
736    fn create_user(name: &str, uuid: &str) -> Entry<EntryInit, EntryNew> {
737        entry_init!(
738            (Attribute::Class, EntryClass::Object.to_value()),
739            (Attribute::Class, EntryClass::Account.to_value()),
740            (Attribute::Class, EntryClass::Person.to_value()),
741            (Attribute::Name, Value::new_iname(name)),
742            (
743                Attribute::Uuid,
744                #[allow(clippy::panic)]
745                Value::new_uuid_s(uuid).unwrap_or_else(|| { panic!("{}", Attribute::Uuid) })
746            ),
747            (Attribute::Description, Value::new_utf8s("testperson-entry")),
748            (Attribute::DisplayName, Value::new_utf8s(name))
749        )
750    }
751
752    fn create_group(name: &str, uuid: &str, members: &[&str]) -> Entry<EntryInit, EntryNew> {
753        #[allow(clippy::panic)]
754        let mut e1 = entry_init!(
755            (Attribute::Class, EntryClass::Object.to_value()),
756            (Attribute::Class, EntryClass::Group.to_value()),
757            (Attribute::Name, Value::new_iname(name)),
758            (
759                Attribute::Uuid,
760                Value::new_uuid_s(uuid).unwrap_or_else(|| { panic!("{}", Attribute::Uuid) })
761            ),
762            (Attribute::Description, Value::new_utf8s("testgroup-entry"))
763        );
764        members.iter().for_each(|m| {
765            e1.add_ava(
766                Attribute::Member,
767                Value::ReferN(Uuid::parse_str(m).unwrap()),
768            )
769        });
770        e1
771    }
772
773    fn check_entry_has_mo(qs: &mut QueryServerWriteTransaction, name: &str, mo: &str) -> bool {
774        let entry = qs
775            .internal_search(filter!(f_eq(
776                Attribute::Name,
777                PartialValue::new_iname(name)
778            )))
779            .unwrap()
780            .pop()
781            .unwrap();
782
783        trace!(?entry);
784
785        entry.attribute_equality(Attribute::MemberOf, &PartialValue::new_refer_s(mo).unwrap())
786    }
787
788    #[qs_test]
789    async fn test_revive_advanced_directmemberships(server: &QueryServer) {
790        // Create items
791        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
792        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
793
794        // Right need a user in a direct group.
795        let u1 = create_user("u1", "22b47373-d123-421f-859e-9ddd8ab14a2a");
796        let g1 = create_group(
797            "g1",
798            "cca2bbfc-5b43-43f3-be9e-f5b03b3defec",
799            &["22b47373-d123-421f-859e-9ddd8ab14a2a"],
800        );
801
802        // Need a user in A -> B -> User, such that A/B are re-added as MO
803        let u2 = create_user("u2", "5c19a4a2-b9f0-4429-b130-5782de5fddda");
804        let g2a = create_group(
805            "g2a",
806            "e44cf9cd-9941-44cb-a02f-307b6e15ac54",
807            &["5c19a4a2-b9f0-4429-b130-5782de5fddda"],
808        );
809        let g2b = create_group(
810            "g2b",
811            "d3132e6e-18ce-4b87-bee1-1d25e4bfe96d",
812            &["e44cf9cd-9941-44cb-a02f-307b6e15ac54"],
813        );
814
815        // Need a user in a group that is recycled after, then revived at the same time.
816        let u3 = create_user("u3", "68467a41-6e8e-44d0-9214-a5164e75ca03");
817        let g3 = create_group(
818            "g3",
819            "36048117-e479-45ed-aeb5-611e8d83d5b1",
820            &["68467a41-6e8e-44d0-9214-a5164e75ca03"],
821        );
822
823        // A user in a group that is recycled, user is revived, THEN the group is. Group
824        // should be present in MO after the second revive.
825        let u4 = create_user("u4", "d696b10f-1729-4f1a-83d0-ca06525c2f59");
826        let g4 = create_group(
827            "g4",
828            "d5c59ac6-c533-4b00-989f-d0e183f07bab",
829            &["d696b10f-1729-4f1a-83d0-ca06525c2f59"],
830        );
831
832        let ce = CreateEvent::new_internal(vec![u1, g1, u2, g2a, g2b, u3, g3, u4, g4]);
833        let cr = server_txn.create(&ce);
834        assert!(cr.is_ok());
835
836        // Now recycle the needed entries.
837        let de = DeleteEvent::new_internal_invalid(filter!(f_or(vec![
838            f_eq(Attribute::Name, PartialValue::new_iname("u1")),
839            f_eq(Attribute::Name, PartialValue::new_iname("u2")),
840            f_eq(Attribute::Name, PartialValue::new_iname("u3")),
841            f_eq(Attribute::Name, PartialValue::new_iname("g3")),
842            f_eq(Attribute::Name, PartialValue::new_iname("u4")),
843            f_eq(Attribute::Name, PartialValue::new_iname("g4"))
844        ])));
845        assert!(server_txn.delete(&de).is_ok());
846
847        // Now revive and check each one, one at a time.
848        let rev1 = ReviveRecycledEvent::new_impersonate_entry(
849            admin.clone(),
850            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u1"))),
851        );
852        assert!(server_txn.revive_recycled(&rev1).is_ok());
853        // check u1 contains MO ->
854        assert!(check_entry_has_mo(
855            &mut server_txn,
856            "u1",
857            "cca2bbfc-5b43-43f3-be9e-f5b03b3defec"
858        ));
859
860        // Revive u2 and check it has two mo.
861        let rev2 = ReviveRecycledEvent::new_impersonate_entry(
862            admin.clone(),
863            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u2"))),
864        );
865        assert!(server_txn.revive_recycled(&rev2).is_ok());
866        assert!(check_entry_has_mo(
867            &mut server_txn,
868            "u2",
869            "e44cf9cd-9941-44cb-a02f-307b6e15ac54"
870        ));
871        assert!(check_entry_has_mo(
872            &mut server_txn,
873            "u2",
874            "d3132e6e-18ce-4b87-bee1-1d25e4bfe96d"
875        ));
876
877        // Revive u3 and g3 at the same time.
878        let rev3 = ReviveRecycledEvent::new_impersonate_entry(
879            admin.clone(),
880            filter_all!(f_or(vec![
881                f_eq(Attribute::Name, PartialValue::new_iname("u3")),
882                f_eq(Attribute::Name, PartialValue::new_iname("g3"))
883            ])),
884        );
885        assert!(server_txn.revive_recycled(&rev3).is_ok());
886        assert!(!check_entry_has_mo(
887            &mut server_txn,
888            "u3",
889            "36048117-e479-45ed-aeb5-611e8d83d5b1"
890        ));
891
892        // Revive u4, should NOT have the MO.
893        let rev4a = ReviveRecycledEvent::new_impersonate_entry(
894            admin.clone(),
895            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u4"))),
896        );
897        assert!(server_txn.revive_recycled(&rev4a).is_ok());
898        assert!(!check_entry_has_mo(
899            &mut server_txn,
900            "u4",
901            "d5c59ac6-c533-4b00-989f-d0e183f07bab"
902        ));
903
904        // Now revive g4, should allow MO onto u4.
905        let rev4b = ReviveRecycledEvent::new_impersonate_entry(
906            admin,
907            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("g4"))),
908        );
909        assert!(server_txn.revive_recycled(&rev4b).is_ok());
910        assert!(!check_entry_has_mo(
911            &mut server_txn,
912            "u4",
913            "d5c59ac6-c533-4b00-989f-d0e183f07bab"
914        ));
915
916        assert!(server_txn.commit().is_ok());
917    }
918
919    #[qs_test]
920    async fn test_entry_delete_after(server: &QueryServer) {
921        let time_p1 = duration_from_epoch_now();
922        let time_p2 = time_p1 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
923        let time_p3 = time_p2 + Duration::from_secs(1);
924
925        let odt_p1 = OffsetDateTime::UNIX_EPOCH + time_p1;
926        let odt_p2 = OffsetDateTime::UNIX_EPOCH + time_p2;
927
928        let message_uuid = Uuid::new_v4();
929
930        let mut server_txn = server.write(time_p1).await.unwrap();
931
932        let mut e_msg = entry_init!(
933            (Attribute::Class, EntryClass::Object.to_value()),
934            (Attribute::Class, EntryClass::OutboundMessage.to_value()),
935            (Attribute::Uuid, Value::Uuid(message_uuid)),
936            (Attribute::SendAfter, Value::DateTime(odt_p1)),
937            (Attribute::DeleteAfter, Value::DateTime(odt_p2))
938        );
939
940        e_msg.set_ava_set(
941            &Attribute::MessageTemplate,
942            ValueSetMessage::new(OutboundMessage::TestMessageV1 {
943                display_name: "testuser".into(),
944            }),
945        );
946
947        server_txn.internal_create(vec![e_msg]).unwrap();
948
949        server_txn.commit().unwrap();
950
951        // Now start a new txn, should not delete the message.
952        let mut server_txn = server.write(time_p1).await.unwrap();
953
954        server_txn.purge_delete_after().unwrap();
955
956        let _msg = server_txn
957            .internal_search_uuid(message_uuid)
958            .expect("Message was deleted!!!");
959
960        server_txn.commit().unwrap();
961
962        // Clock forwards, will now delete.
963        let mut server_txn = server.write(time_p3).await.unwrap();
964
965        trace!(?odt_p2);
966        server_txn.purge_delete_after().unwrap();
967
968        server_txn
969            .internal_search_uuid(message_uuid)
970            .expect_err("Message is still present");
971
972        // Search recycle bin
973        let _msg = server_txn
974            .internal_search_all_uuid(message_uuid)
975            .expect("It's not in the recycle bin!");
976
977        server_txn.commit().unwrap();
978    }
979}