1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use super::modify::ModifyPartial;
use crate::event::ReviveRecycledEvent;
use crate::prelude::*;
use crate::server::Plugins;
use hashbrown::HashMap;

impl<'a> QueryServerWriteTransaction<'a> {
    #[instrument(level = "debug", skip_all)]
    pub fn purge_tombstones(&mut self) -> Result<usize, OperationError> {
        // purge everything that is a tombstone.
        let trim_cid = self.trim_cid().clone();
        let anchor_cid = self.get_txn_cid().clone();

        // Delete them - this is a TRUE delete, no going back now!
        self.be_txn
            .reap_tombstones(&anchor_cid, &trim_cid)
            .map_err(|e| {
                error!(err = ?e, "Tombstone purge operation failed (backend)");
                e
            })
            .inspect(|_res| {
                admin_info!("Tombstone purge operation success");
            })
    }

    #[instrument(level = "debug", skip_all)]
    pub fn purge_recycled(&mut self) -> Result<usize, OperationError> {
        // Send everything that is recycled to tombstone
        // Search all recycled
        let cid = self.cid.sub_secs(RECYCLEBIN_MAX_AGE).map_err(|e| {
            admin_error!(err = ?e, "Unable to generate search cid for purge_recycled");
            e
        })?;
        let rc = self.internal_search(filter_all!(f_and!([
            f_eq(Attribute::Class, EntryClass::Recycled.into()),
            f_lt(Attribute::LastModifiedCid, PartialValue::new_cid(cid)),
        ])))?;

        if rc.is_empty() {
            admin_debug!("No recycled items present - purge operation success");
            return Ok(0);
        }

        // Modify them to strip all avas except uuid
        let tombstone_cand: Result<Vec<_>, _> = rc
            .iter()
            .map(|e| {
                e.to_tombstone(self.cid.clone())
                    .validate(&self.schema)
                    .map_err(|e| {
                        admin_error!("Schema Violation in purge_recycled validate: {:?}", e);
                        OperationError::SchemaViolation(e)
                    })
                    // seal if it worked.
                    .map(|e| e.seal(&self.schema))
            })
            .collect();

        let tombstone_cand = tombstone_cand?;
        // it's enough to say "yeah we tried to touch this many" because
        // we're using this to decide if we're going to commit the txn
        let touched = tombstone_cand.len();

        // Backend Modify
        self.be_txn
            .modify(&self.cid, &rc, &tombstone_cand)
            .map_err(|e| {
                admin_error!("Purge recycled operation failed (backend), {:?}", e);
                e
            })
            .map(|_| {
                admin_info!("Purge recycled operation success");
                touched
            })
    }

    #[instrument(level = "debug", skip_all)]
    pub fn revive_recycled(&mut self, re: &ReviveRecycledEvent) -> Result<(), OperationError> {
        // Revive an entry to live. This is a specialised function, and draws a lot of
        // inspiration from modify.
        //
        // Access is granted by the ability to ability to search the class=recycled
        // and the ability modify + remove that class from the object.
        if !re.ident.is_internal() {
            security_info!(name = %re.ident, "revive initiator");
        }

        // Get the list of pre_candidates, using impersonate search.
        let pre_candidates =
            self.impersonate_search_valid(re.filter.clone(), re.filter.clone(), &re.ident)?;

        // Is the list empty?
        if pre_candidates.is_empty() {
            if re.ident.is_internal() {
                trace!(
                    "revive: no candidates match filter ... continuing {:?}",
                    re.filter
                );
                return Ok(());
            } else {
                request_error!(
                    "revive: no candidates match filter, failure {:?}",
                    re.filter
                );
                return Err(OperationError::NoMatchingEntries);
            }
        };

        trace!("revive: pre_candidates -> {:?}", pre_candidates);

        // Check access against a "fake" modify.
        let modlist = ModifyList::new_list(vec![Modify::Removed(
            Attribute::Class,
            EntryClass::Recycled.into(),
        )]);

        let m_valid = modlist.validate(self.get_schema()).map_err(|e| {
            admin_error!("revive recycled modlist Schema Violation {:?}", e);
            OperationError::SchemaViolation(e)
        })?;

        let me =
            ModifyEvent::new_impersonate(&re.ident, re.filter.clone(), re.filter.clone(), m_valid);

        let access = self.get_accesscontrols();
        let op_allow = access
            .modify_allow_operation(&me, &pre_candidates)
            .map_err(|e| {
                admin_error!("Unable to check modify access {:?}", e);
                e
            })?;
        if !op_allow {
            return Err(OperationError::AccessDenied);
        }

        // Are all of the entries actually recycled?
        if pre_candidates.iter().all(|e| e.mask_recycled().is_some()) {
            admin_warn!("Refusing to revive entries that are already live!");
            return Err(OperationError::AccessDenied);
        }

        // Build the list of mods from directmo, to revive memberships.
        let mut dm_mods: HashMap<Uuid, ModifyList<ModifyInvalid>> =
            HashMap::with_capacity(pre_candidates.len());

        for e in &pre_candidates {
            // Get this entries uuid.
            let u: Uuid = e.get_uuid();

            if let Some(riter) = e.get_ava_as_refuuid(Attribute::RecycledDirectMemberOf) {
                for g_uuid in riter {
                    dm_mods
                        .entry(g_uuid)
                        .and_modify(|mlist| {
                            let m = Modify::Present(Attribute::Member, Value::Refer(u));
                            mlist.push_mod(m);
                        })
                        .or_insert({
                            let m = Modify::Present(Attribute::Member, Value::Refer(u));
                            ModifyList::new_list(vec![m])
                        });
                }
            }
        }

        // clone the writeable entries.
        let mut candidates: Vec<Entry<EntryInvalid, EntryCommitted>> = pre_candidates
            .iter()
            .map(|er| {
                er.as_ref()
                    .clone()
                    .invalidate(self.cid.clone(), &self.trim_cid)
            })
            // Mutate to apply the revive.
            .map(|er| er.to_revived())
            .collect();

        // Are they all revived?
        if candidates.iter().all(|e| e.mask_recycled().is_none()) {
            admin_error!("Not all candidates were correctly revived, unable to proceed");
            return Err(OperationError::InvalidEntryState);
        }

        // Do we need to apply pre-mod?
        // Very likely, in case domain has renamed etc.
        Plugins::run_pre_modify(self, &pre_candidates, &mut candidates, &me).map_err(|e| {
            admin_error!("Revive operation failed (plugin), {:?}", e);
            e
        })?;

        // Schema validate
        let res: Result<Vec<Entry<EntrySealed, EntryCommitted>>, OperationError> = candidates
            .into_iter()
            .map(|e| {
                e.validate(&self.schema)
                    .map_err(|e| {
                        admin_error!("Schema Violation {:?}", e);
                        OperationError::SchemaViolation(e)
                    })
                    .map(|e| e.seal(&self.schema))
            })
            .collect();

        let norm_cand: Vec<Entry<_, _>> = res?;

        // build the mod partial
        let mp = ModifyPartial {
            norm_cand,
            pre_candidates,
            me: &me,
        };

        // Call modify_apply
        self.modify_apply(mp)?;

        // If and only if that succeeds, apply the direct membership modifications
        // if possible.
        for (g, mods) in dm_mods {
            // I think the filter/filter_all shouldn't matter here because the only
            // valid direct memberships should be still valid/live references, as refint
            // removes anything that was deleted even from recycled entries.
            let f = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(g)));
            self.internal_modify(&f, &mods)?;
        }

        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn internal_revive_uuid(&mut self, target_uuid: Uuid) -> Result<(), OperationError> {
        // Note the use of filter_rec here for only recycled targets.
        let filter = filter_rec!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
        let f_valid = filter
            .validate(self.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let re = ReviveRecycledEvent::new_internal(f_valid);
        self.revive_recycled(&re)
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    use crate::event::{CreateEvent, DeleteEvent};
    use crate::server::ModifyEvent;
    use crate::server::SearchEvent;

    use super::ReviveRecycledEvent;

    #[qs_test]
    async fn test_recycle_simple(server: &QueryServer) {
        // First we setup some timestamps
        let time_p1 = duration_from_epoch_now();
        let time_p2 = time_p1 + Duration::from_secs(RECYCLEBIN_MAX_AGE * 2);

        let mut server_txn = server.write(time_p1).await.unwrap();
        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");

        let filt_i_rc = filter_all!(f_eq(Attribute::Class, EntryClass::Recycled.into()));

        let filt_i_ts = filter_all!(f_eq(Attribute::Class, EntryClass::Tombstone.into()));

        let filt_i_per = filter_all!(f_eq(Attribute::Class, EntryClass::Person.into()));

        // Create fake external requests. Probably from admin later
        let me_rc = ModifyEvent::new_impersonate_entry(
            admin.clone(),
            filt_i_rc.clone(),
            ModifyList::new_list(vec![Modify::Present(
                Attribute::Class,
                EntryClass::Recycled.into(),
            )]),
        );

        let de_rc = DeleteEvent::new_impersonate_entry(admin.clone(), filt_i_rc.clone());

        let se_rc = SearchEvent::new_ext_impersonate_entry(admin.clone(), filt_i_rc.clone());

        let sre_rc = SearchEvent::new_rec_impersonate_entry(admin.clone(), filt_i_rc.clone());

        let rre_rc = ReviveRecycledEvent::new_impersonate_entry(
            admin,
            filter_all!(f_eq(
                Attribute::Name,
                PartialValue::new_iname("testperson1")
            )),
        );

        // Create some recycled objects
        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("testperson1")),
            (
                Attribute::Uuid,
                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
            ),
            (Attribute::Description, Value::new_utf8s("testperson1")),
            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
        );

        let e2 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("testperson2")),
            (
                Attribute::Uuid,
                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63932"))
            ),
            (Attribute::Description, Value::new_utf8s("testperson2")),
            (Attribute::DisplayName, Value::new_utf8s("testperson2"))
        );

        let ce = CreateEvent::new_internal(vec![e1, e2]);
        let cr = server_txn.create(&ce);
        assert!(cr.is_ok());

        // Now we immediately delete these to force them to the correct state.
        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_or!([
            f_eq(Attribute::Name, PartialValue::new_iname("testperson1")),
            f_eq(Attribute::Name, PartialValue::new_iname("testperson2")),
        ])));
        assert!(server_txn.delete(&de_sin).is_ok());

        // Can it be seen (external search)
        let r1 = server_txn.search(&se_rc).expect("search failed");
        assert!(r1.is_empty());

        // Can it be deleted (external delete)
        // Should be err-no candidates.
        assert!(server_txn.delete(&de_rc).is_err());

        // Can it be modified? (external modify)
        // Should be err-no candidates
        assert!(server_txn.modify(&me_rc).is_err());

        // Can in be seen by special search? (external recycle search)
        let r2 = server_txn.search(&sre_rc).expect("search failed");
        assert_eq!(r2.len(), 2);

        // Can it be seen (internal search)
        // Internal search should see it.
        let r2 = server_txn
            .internal_search(filt_i_rc.clone())
            .expect("internal search failed");
        assert_eq!(r2.len(), 2);

        // There are now two paths forward
        //  revival or purge!
        assert!(server_txn.revive_recycled(&rre_rc).is_ok());

        // Not enough time has passed, won't have an effect for purge to TS
        assert!(server_txn.purge_recycled().is_ok());
        let r3 = server_txn
            .internal_search(filt_i_rc.clone())
            .expect("internal search failed");
        assert_eq!(r3.len(), 1);

        // Commit
        assert!(server_txn.commit().is_ok());

        // Now, establish enough time for the recycled items to be purged.
        let mut server_txn = server.write(time_p2).await.unwrap();

        //  purge to tombstone, now that time has passed.
        assert!(server_txn.purge_recycled().is_ok());

        // Should be no recycled objects.
        let r4 = server_txn
            .internal_search(filt_i_rc.clone())
            .expect("internal search failed");
        assert!(r4.is_empty());

        // There should be one tombstone
        let r5 = server_txn
            .internal_search(filt_i_ts.clone())
            .expect("internal search failed");
        assert_eq!(r5.len(), 1);

        // There should be one entry
        let r6 = server_txn
            .internal_search(filt_i_per.clone())
            .expect("internal search failed");
        assert_eq!(r6.len(), 1);

        assert!(server_txn.commit().is_ok());
    }

    // The delete test above should be unaffected by recycle anyway
    #[qs_test]
    async fn test_qs_recycle_advanced(server: &QueryServer) {
        // Create items
        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");

        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("testperson1")),
            (
                Attribute::Uuid,
                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
            ),
            (Attribute::Description, Value::new_utf8s("testperson1")),
            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
        );
        let ce = CreateEvent::new_internal(vec![e1]);

        let cr = server_txn.create(&ce);
        assert!(cr.is_ok());
        // Delete and ensure they became recycled.
        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_eq(
            Attribute::Name,
            PartialValue::new_iname("testperson1")
        )));
        assert!(server_txn.delete(&de_sin).is_ok());
        // Can in be seen by special search? (external recycle search)
        let filt_rc = filter_all!(f_eq(Attribute::Class, EntryClass::Recycled.into()));
        let sre_rc = SearchEvent::new_rec_impersonate_entry(admin, filt_rc);
        let r2 = server_txn.search(&sre_rc).expect("search failed");
        assert_eq!(r2.len(), 1);

        // Create dup uuid (rej)
        // After a delete -> recycle, create duplicate name etc.
        let cr = server_txn.create(&ce);
        assert!(cr.is_err());

        assert!(server_txn.commit().is_ok());
    }

    #[qs_test]
    async fn test_uuid_to_star_recycle(server: &QueryServer) {
        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();

        let e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Name, Value::new_iname("testperson1")),
            (
                Attribute::Uuid,
                Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
            ),
            (Attribute::Description, Value::new_utf8s("testperson1")),
            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
        );

        let tuuid = uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");

        let ce = CreateEvent::new_internal(vec![e1]);
        let cr = server_txn.create(&ce);
        assert!(cr.is_ok());

        assert_eq!(
            server_txn.uuid_to_rdn(tuuid),
            Ok("spn=testperson1@example.com".to_string())
        );

        assert!(
            server_txn.uuid_to_spn(tuuid)
                == Ok(Some(Value::new_spn_str("testperson1", "example.com")))
        );

        assert_eq!(server_txn.name_to_uuid("testperson1"), Ok(tuuid));

        // delete
        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_eq(
            Attribute::Name,
            PartialValue::new_iname("testperson1")
        )));
        assert!(server_txn.delete(&de_sin).is_ok());

        // all should fail
        assert!(
            server_txn.uuid_to_rdn(tuuid)
                == Ok("uuid=cc8e95b4-c24f-4d68-ba54-8bed76f63930".to_string())
        );

        assert_eq!(server_txn.uuid_to_spn(tuuid), Ok(None));

        assert!(server_txn.name_to_uuid("testperson1").is_err());

        // revive
        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");
        let rre_rc = ReviveRecycledEvent::new_impersonate_entry(
            admin,
            filter_all!(f_eq(
                Attribute::Name,
                PartialValue::new_iname("testperson1")
            )),
        );
        assert!(server_txn.revive_recycled(&rre_rc).is_ok());

        // all checks pass

        assert_eq!(
            server_txn.uuid_to_rdn(tuuid),
            Ok("spn=testperson1@example.com".to_string())
        );

        assert!(
            server_txn.uuid_to_spn(tuuid)
                == Ok(Some(Value::new_spn_str("testperson1", "example.com")))
        );

        assert_eq!(server_txn.name_to_uuid("testperson1"), Ok(tuuid));
    }

    #[qs_test]
    async fn test_tombstone(server: &QueryServer) {
        // First we setup some timestamps
        let time_p1 = duration_from_epoch_now();
        let time_p2 = time_p1 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
        let time_p3 = time_p2 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);

        trace!("test_tombstone_start");
        let mut server_txn = server.write(time_p1).await.unwrap();
        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");

        let filt_i_ts = filter_all!(f_eq(Attribute::Class, EntryClass::Tombstone.into()));

        // Create fake external requests. Probably from admin later
        // Should we do this with impersonate instead of using the external
        let me_ts = ModifyEvent::new_impersonate_entry(
            admin.clone(),
            filt_i_ts.clone(),
            ModifyList::new_list(vec![Modify::Present(
                Attribute::Class,
                EntryClass::Tombstone.into(),
            )]),
        );

        let de_ts = DeleteEvent::new_impersonate_entry(admin.clone(), filt_i_ts.clone());
        let se_ts = SearchEvent::new_ext_impersonate_entry(admin, filt_i_ts.clone());

        // First, create an entry, then push it through the lifecycle.
        let e_ts = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname("testperson1")),
            (
                Attribute::Uuid,
                Value::Uuid(uuid!("9557f49c-97a5-4277-a9a5-097d17eb8317"))
            ),
            (Attribute::Description, Value::new_utf8s("testperson1")),
            (Attribute::DisplayName, Value::new_utf8s("testperson1"))
        );

        let ce = CreateEvent::new_internal(vec![e_ts]);
        let cr = server_txn.create(&ce);
        assert!(cr.is_ok());

        let de_sin = DeleteEvent::new_internal_invalid(filter!(f_or!([f_eq(
            Attribute::Name,
            PartialValue::new_iname("testperson1")
        )])));
        assert!(server_txn.delete(&de_sin).is_ok());

        // Commit
        assert!(server_txn.commit().is_ok());

        // Now, establish enough time for the recycled items to be purged.
        let mut server_txn = server.write(time_p2).await.unwrap();
        assert!(server_txn.purge_recycled().is_ok());

        // Now test the tombstone properties.

        // Can it be seen (external search)
        let r1 = server_txn.search(&se_ts).expect("search failed");
        assert!(r1.is_empty());

        // Can it be deleted (external delete)
        // Should be err-no candidates.
        assert!(server_txn.delete(&de_ts).is_err());

        // Can it be modified? (external modify)
        // Should be err-no candidates
        assert!(server_txn.modify(&me_ts).is_err());

        // Can it be seen (internal search)
        // Internal search should see it.
        let r2 = server_txn
            .internal_search(filt_i_ts.clone())
            .expect("internal search failed");
        assert_eq!(r2.len(), 1);

        // If we purge now, nothing happens, we aren't past the time window.
        assert!(server_txn.purge_tombstones().is_ok());

        let r3 = server_txn
            .internal_search(filt_i_ts.clone())
            .expect("internal search failed");
        assert_eq!(r3.len(), 1);

        // Commit
        assert!(server_txn.commit().is_ok());

        // New txn, push the cid forward.
        let mut server_txn = server.write(time_p3).await.unwrap();

        // Now purge
        assert!(server_txn.purge_tombstones().is_ok());

        // Assert it's gone
        // Internal search should not see it.
        let r4 = server_txn
            .internal_search(filt_i_ts)
            .expect("internal search failed");
        assert!(r4.is_empty());

        assert!(server_txn.commit().is_ok());
    }

    fn create_user(name: &str, uuid: &str) -> Entry<EntryInit, EntryNew> {
        entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Account.to_value()),
            (Attribute::Class, EntryClass::Person.to_value()),
            (Attribute::Name, Value::new_iname(name)),
            (
                Attribute::Uuid,
                #[allow(clippy::panic)]
                Value::new_uuid_s(uuid).unwrap_or_else(|| { panic!("{}", Attribute::Uuid) })
            ),
            (Attribute::Description, Value::new_utf8s("testperson-entry")),
            (Attribute::DisplayName, Value::new_utf8s(name))
        )
    }

    fn create_group(name: &str, uuid: &str, members: &[&str]) -> Entry<EntryInit, EntryNew> {
        #[allow(clippy::panic)]
        let mut e1 = entry_init!(
            (Attribute::Class, EntryClass::Object.to_value()),
            (Attribute::Class, EntryClass::Group.to_value()),
            (Attribute::Name, Value::new_iname(name)),
            (
                Attribute::Uuid,
                Value::new_uuid_s(uuid).unwrap_or_else(|| { panic!("{}", Attribute::Uuid) })
            ),
            (Attribute::Description, Value::new_utf8s("testgroup-entry"))
        );
        members
            .iter()
            .for_each(|m| e1.add_ava(Attribute::Member, Value::new_refer_s(m).unwrap()));
        e1
    }

    fn check_entry_has_mo(qs: &mut QueryServerWriteTransaction, name: &str, mo: &str) -> bool {
        let entry = qs
            .internal_search(filter!(f_eq(
                Attribute::Name,
                PartialValue::new_iname(name)
            )))
            .unwrap()
            .pop()
            .unwrap();

        trace!(?entry);

        entry.attribute_equality(Attribute::MemberOf, &PartialValue::new_refer_s(mo).unwrap())
    }

    #[qs_test]
    async fn test_revive_advanced_directmemberships(server: &QueryServer) {
        // Create items
        let mut server_txn = server.write(duration_from_epoch_now()).await.unwrap();
        let admin = server_txn.internal_search_uuid(UUID_ADMIN).expect("failed");

        // Right need a user in a direct group.
        let u1 = create_user("u1", "22b47373-d123-421f-859e-9ddd8ab14a2a");
        let g1 = create_group(
            "g1",
            "cca2bbfc-5b43-43f3-be9e-f5b03b3defec",
            &["22b47373-d123-421f-859e-9ddd8ab14a2a"],
        );

        // Need a user in A -> B -> User, such that A/B are re-added as MO
        let u2 = create_user("u2", "5c19a4a2-b9f0-4429-b130-5782de5fddda");
        let g2a = create_group(
            "g2a",
            "e44cf9cd-9941-44cb-a02f-307b6e15ac54",
            &["5c19a4a2-b9f0-4429-b130-5782de5fddda"],
        );
        let g2b = create_group(
            "g2b",
            "d3132e6e-18ce-4b87-bee1-1d25e4bfe96d",
            &["e44cf9cd-9941-44cb-a02f-307b6e15ac54"],
        );

        // Need a user in a group that is recycled after, then revived at the same time.
        let u3 = create_user("u3", "68467a41-6e8e-44d0-9214-a5164e75ca03");
        let g3 = create_group(
            "g3",
            "36048117-e479-45ed-aeb5-611e8d83d5b1",
            &["68467a41-6e8e-44d0-9214-a5164e75ca03"],
        );

        // A user in a group that is recycled, user is revived, THEN the group is. Group
        // should be present in MO after the second revive.
        let u4 = create_user("u4", "d696b10f-1729-4f1a-83d0-ca06525c2f59");
        let g4 = create_group(
            "g4",
            "d5c59ac6-c533-4b00-989f-d0e183f07bab",
            &["d696b10f-1729-4f1a-83d0-ca06525c2f59"],
        );

        let ce = CreateEvent::new_internal(vec![u1, g1, u2, g2a, g2b, u3, g3, u4, g4]);
        let cr = server_txn.create(&ce);
        assert!(cr.is_ok());

        // Now recycle the needed entries.
        let de = DeleteEvent::new_internal_invalid(filter!(f_or(vec![
            f_eq(Attribute::Name, PartialValue::new_iname("u1")),
            f_eq(Attribute::Name, PartialValue::new_iname("u2")),
            f_eq(Attribute::Name, PartialValue::new_iname("u3")),
            f_eq(Attribute::Name, PartialValue::new_iname("g3")),
            f_eq(Attribute::Name, PartialValue::new_iname("u4")),
            f_eq(Attribute::Name, PartialValue::new_iname("g4"))
        ])));
        assert!(server_txn.delete(&de).is_ok());

        // Now revive and check each one, one at a time.
        let rev1 = ReviveRecycledEvent::new_impersonate_entry(
            admin.clone(),
            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u1"))),
        );
        assert!(server_txn.revive_recycled(&rev1).is_ok());
        // check u1 contains MO ->
        assert!(check_entry_has_mo(
            &mut server_txn,
            "u1",
            "cca2bbfc-5b43-43f3-be9e-f5b03b3defec"
        ));

        // Revive u2 and check it has two mo.
        let rev2 = ReviveRecycledEvent::new_impersonate_entry(
            admin.clone(),
            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u2"))),
        );
        assert!(server_txn.revive_recycled(&rev2).is_ok());
        assert!(check_entry_has_mo(
            &mut server_txn,
            "u2",
            "e44cf9cd-9941-44cb-a02f-307b6e15ac54"
        ));
        assert!(check_entry_has_mo(
            &mut server_txn,
            "u2",
            "d3132e6e-18ce-4b87-bee1-1d25e4bfe96d"
        ));

        // Revive u3 and g3 at the same time.
        let rev3 = ReviveRecycledEvent::new_impersonate_entry(
            admin.clone(),
            filter_all!(f_or(vec![
                f_eq(Attribute::Name, PartialValue::new_iname("u3")),
                f_eq(Attribute::Name, PartialValue::new_iname("g3"))
            ])),
        );
        assert!(server_txn.revive_recycled(&rev3).is_ok());
        assert!(!check_entry_has_mo(
            &mut server_txn,
            "u3",
            "36048117-e479-45ed-aeb5-611e8d83d5b1"
        ));

        // Revive u4, should NOT have the MO.
        let rev4a = ReviveRecycledEvent::new_impersonate_entry(
            admin.clone(),
            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("u4"))),
        );
        assert!(server_txn.revive_recycled(&rev4a).is_ok());
        assert!(!check_entry_has_mo(
            &mut server_txn,
            "u4",
            "d5c59ac6-c533-4b00-989f-d0e183f07bab"
        ));

        // Now revive g4, should allow MO onto u4.
        let rev4b = ReviveRecycledEvent::new_impersonate_entry(
            admin,
            filter_all!(f_eq(Attribute::Name, PartialValue::new_iname("g4"))),
        );
        assert!(server_txn.revive_recycled(&rev4b).is_ok());
        assert!(!check_entry_has_mo(
            &mut server_txn,
            "u4",
            "d5c59ac6-c533-4b00-989f-d0e183f07bab"
        ));

        assert!(server_txn.commit().is_ok());
    }
}