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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! An `event` is a self contained module of data, that contains all of the
//! required information for any operation to proceed. While there are many
//! types of potential events, they all eventually lower to one of:
//!
//! * AuthEvent
//! * SearchEvent
//! * ExistsEvent
//! * ModifyEvent
//! * CreateEvent
//! * DeleteEvent
//!
//! An "event" is generally then passed to the `QueryServer` for processing.
//! By making these fully self contained units, it means that we can assert
//! at event creation time we have all the correct data required to proceed
//! with the operation, and a clear path to know how to transform events between
//! various types.

use std::collections::BTreeSet;
#[cfg(test)]
use std::sync::Arc;

use kanidm_proto::internal::{
    CreateRequest, DeleteRequest, ModifyList as ProtoModifyList, ModifyRequest, OperationError,
    SearchRequest, SearchResponse,
};
use kanidm_proto::v1::{Entry as ProtoEntry, WhoamiResponse};
use ldap3_proto::simple::LdapFilter;
use uuid::Uuid;

use crate::entry::{Entry, EntryCommitted, EntryInit, EntryNew, EntryReduced};
use crate::filter::{Filter, FilterInvalid, FilterValid};
use crate::modify::{ModifyInvalid, ModifyList, ModifyValid};
use crate::prelude::*;
use crate::schema::SchemaTransaction;
use crate::value::PartialValue;

#[derive(Debug)]
pub struct SearchResult {
    entries: Vec<ProtoEntry>,
}

impl SearchResult {
    pub fn new(
        qs: &mut QueryServerReadTransaction,
        entries: &[Entry<EntryReduced, EntryCommitted>],
    ) -> Result<Self, OperationError> {
        let entries: Result<_, _> = entries
            .iter()
            .map(|e| {
                // All the needed transforms for this result are done
                // in search_ext. This is just an entry -> protoentry
                // step.
                e.to_pe(qs)
            })
            .collect();
        Ok(SearchResult { entries: entries? })
    }

    // Consume self into a search response
    pub fn response(self) -> SearchResponse {
        SearchResponse {
            entries: self.entries,
        }
    }

    // Consume into the array of entries, used in the json proto
    pub fn into_proto_array(self) -> Vec<ProtoEntry> {
        self.entries
    }
}

#[derive(Debug)]
pub struct SearchEvent {
    pub ident: Identity,
    // This is the filter as we apply and process it.
    pub filter: Filter<FilterValid>,
    // This is the original filter, for the purpose of ACI checking.
    pub filter_orig: Filter<FilterValid>,
    pub attrs: Option<BTreeSet<Attribute>>,
}

impl SearchEvent {
    pub fn from_message(
        ident: Identity,
        req: &SearchRequest,
        qs: &mut QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        let f = Filter::from_ro(&ident, &req.filter, qs)?;
        // We do need to do this twice to account for the ignore_hidden
        // changes.
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            // We can't get this from the SearchMessage because it's annoying with the
            // current macro design.
            attrs: None,
        })
    }

    pub fn from_internal_message(
        ident: Identity,
        filter: &Filter<FilterInvalid>,
        attrs: Option<&[String]>,
        qs: &mut QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        let r_attrs: Option<BTreeSet<Attribute>> = attrs.map(|vs| {
            vs.iter()
                .filter_map(|a| qs.get_schema().normalise_attr_if_exists(a.as_str()))
                .collect()
        });

        if let Some(s) = &r_attrs {
            if s.is_empty() {
                request_error!("EmptyRequest for attributes");
                return Err(OperationError::EmptyRequest);
            }
        }

        let filter_orig = filter.validate(qs.get_schema()).map_err(|e| {
            request_error!(?e, "filter schema violation");
            OperationError::SchemaViolation(e)
        })?;
        let filter = filter_orig.clone().into_ignore_hidden();

        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            attrs: r_attrs,
        })
    }

    pub fn from_internal_recycle_message(
        ident: Identity,
        filter: &Filter<FilterInvalid>,
        attrs: Option<&[String]>,
        qs: &QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        let r_attrs: Option<BTreeSet<Attribute>> = attrs.map(|vs| {
            vs.iter()
                .filter_map(|a| {
                    qs.get_schema()
                        .normalise_attr_if_exists(a.as_str())
                        .map(|a_str| Attribute::from(a_str.as_str()))
                })
                .collect()
        });

        if let Some(s) = &r_attrs {
            if s.is_empty() {
                return Err(OperationError::EmptyRequest);
            }
        }

        let filter_orig = filter
            .validate(qs.get_schema())
            .map(|f| f.into_recycled())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone();

        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            attrs: r_attrs,
        })
    }

    pub fn from_whoami_request(
        ident: Identity,
        qs: &QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        let filter_orig = filter_all!(f_self())
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();

        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            attrs: None,
        })
    }

    pub fn from_target_uuid_request(
        ident: Identity,
        target_uuid: Uuid,
        qs: &QueryServerReadTransaction,
    ) -> Result<Self, OperationError> {
        let filter_orig = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)))
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            attrs: None,
        })
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
    ) -> Self {
        SearchEvent {
            ident: Identity::from_impersonate_entry_readonly(e),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            attrs: None,
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_identity(ident: Identity, filter: Filter<FilterInvalid>) -> Self {
        SearchEvent {
            ident,
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            attrs: None,
        }
    }

    pub fn new_impersonate(
        ident: &Identity,
        filter: Filter<FilterValid>,
        filter_orig: Filter<FilterValid>,
    ) -> Self {
        SearchEvent {
            ident: Identity::from_impersonate(ident),
            filter,
            filter_orig,
            attrs: None,
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_rec_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
    ) -> Self {
        /* Impersonate a request for recycled objects */
        let filter_orig = filter.into_valid();
        let filter = filter_orig.clone().into_recycled();
        SearchEvent {
            ident: Identity::from_impersonate_entry_readonly(e),
            filter,
            filter_orig,
            attrs: None,
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_ext_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
    ) -> Self {
        /* Impersonate an external request AKA filter ts + recycle */
        SearchEvent {
            ident: Identity::from_impersonate_entry_readonly(e),
            filter: filter.clone().into_valid().into_ignore_hidden(),
            filter_orig: filter.into_valid(),
            attrs: None,
        }
    }

    pub(crate) fn new_ext_impersonate_uuid(
        qs: &mut QueryServerReadTransaction,
        ident: Identity,
        lf: &LdapFilter,
        attrs: Option<BTreeSet<Attribute>>,
    ) -> Result<Self, OperationError> {
        // Kanidm Filter from LdapFilter
        let f = Filter::from_ldap_ro(&ident, lf, qs)?;
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        Ok(SearchEvent {
            ident,
            filter,
            filter_orig,
            attrs,
        })
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_internal_invalid(filter: Filter<FilterInvalid>) -> Self {
        SearchEvent {
            ident: Identity::from_internal(),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            attrs: None,
        }
    }

    pub fn new_internal(filter: Filter<FilterValid>) -> Self {
        SearchEvent {
            ident: Identity::from_internal(),
            filter: filter.clone(),
            filter_orig: filter,
            attrs: None,
        }
    }
}

// Represents the decoded entries from the protocol -> internal entry representation
// including information about the identity performing the request, and if the
// request is internal or not.
#[derive(Debug)]
pub struct CreateEvent {
    pub ident: Identity,
    // This may still actually change to handle the *raw* nature of the
    // input that we plan to parse.
    pub entries: Vec<Entry<EntryInit, EntryNew>>,
    // Is the CreateEvent from an internal or external source?
    // This may affect which plugins are run ...
}

impl CreateEvent {
    pub fn from_message(
        ident: Identity,
        req: &CreateRequest,
        qs: &mut QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let rentries: Result<Vec<_>, _> = req
            .entries
            .iter()
            .map(|e| Entry::from_proto_entry(e, qs))
            .collect();
        // From ProtoEntry -> Entry
        // What is the correct consuming iterator here? Can we
        // even do that?
        match rentries {
            Ok(entries) => Ok(CreateEvent { ident, entries }),
            Err(e) => Err(e),
        }
    }

    #[cfg(test)]
    pub fn new_impersonate_identity(
        ident: Identity,
        entries: Vec<Entry<EntryInit, EntryNew>>,
    ) -> Self {
        CreateEvent { ident, entries }
    }

    pub fn new_internal(entries: Vec<Entry<EntryInit, EntryNew>>) -> Self {
        CreateEvent {
            ident: Identity::from_internal(),
            entries,
        }
    }
}

#[derive(Debug)]
pub struct ExistsEvent {
    pub ident: Identity,
    // This is the filter, as it will be processed.
    pub filter: Filter<FilterValid>,
    // This is the original filter, for the purpose of ACI checking.
    pub filter_orig: Filter<FilterValid>,
}

impl ExistsEvent {
    pub fn new_internal(filter: Filter<FilterValid>) -> Self {
        ExistsEvent {
            ident: Identity::from_internal(),
            filter: filter.clone(),
            filter_orig: filter,
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_internal_invalid(filter: Filter<FilterInvalid>) -> Self {
        ExistsEvent {
            ident: Identity::from_internal(),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
        }
    }
}

#[derive(Debug)]
pub struct DeleteEvent {
    pub ident: Identity,
    // This is the filter, as it will be processed.
    pub filter: Filter<FilterValid>,
    // This is the original filter, for the purpose of ACI checking.
    pub filter_orig: Filter<FilterValid>,
}

impl DeleteEvent {
    pub fn from_message(
        ident: Identity,
        req: &DeleteRequest,
        qs: &mut QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let f = Filter::from_rw(&ident, &req.filter, qs)?;
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        Ok(DeleteEvent {
            ident,
            filter,
            filter_orig,
        })
    }

    pub fn from_parts(
        ident: Identity,
        f: &Filter<FilterInvalid>,
        qs: &mut QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        Ok(DeleteEvent {
            ident,
            filter,
            filter_orig,
        })
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
    ) -> Self {
        DeleteEvent {
            ident: Identity::from_impersonate_entry_readwrite(e),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
        }
    }

    /// ⚠️  - Bypass the schema state machine, allowing an invalid filter to be used in an impersonate request.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_identity(ident: Identity, filter: Filter<FilterInvalid>) -> Self {
        DeleteEvent {
            ident,
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_internal_invalid(filter: Filter<FilterInvalid>) -> Self {
        DeleteEvent {
            ident: Identity::from_internal(),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
        }
    }

    pub fn new_internal(filter: Filter<FilterValid>) -> Self {
        DeleteEvent {
            ident: Identity::from_internal(),
            filter: filter.clone(),
            filter_orig: filter,
        }
    }
}

#[derive(Debug)]
pub struct ModifyEvent {
    pub ident: Identity,
    // This is the filter, as it will be processed.
    pub filter: Filter<FilterValid>,
    // This is the original filter, for the purpose of ACI checking.
    pub filter_orig: Filter<FilterValid>,
    pub modlist: ModifyList<ModifyValid>,
}

impl ModifyEvent {
    pub fn from_message(
        ident: Identity,
        req: &ModifyRequest,
        qs: &mut QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let f = Filter::from_rw(&ident, &req.filter, qs)?;
        let m = ModifyList::from(&req.modlist, qs)?;
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        let modlist = m
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        Ok(ModifyEvent {
            ident,
            filter,
            filter_orig,
            modlist,
        })
    }

    pub fn from_parts(
        ident: Identity,
        target_uuid: Uuid,
        proto_ml: &ProtoModifyList,
        filter: Filter<FilterInvalid>,
        qs: &mut QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let f_uuid = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
        // Add any supplemental conditions we have.
        let f = Filter::join_parts_and(f_uuid, filter);

        let m = ModifyList::from(proto_ml, qs)?;
        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        let modlist = m
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;

        Ok(ModifyEvent {
            ident,
            filter,
            filter_orig,
            modlist,
        })
    }

    pub fn from_internal_parts(
        ident: Identity,
        ml: &ModifyList<ModifyInvalid>,
        filter: &Filter<FilterInvalid>,
        qs: &QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let filter_orig = filter
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        let modlist = ml
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;

        Ok(ModifyEvent {
            ident,
            filter,
            filter_orig,
            modlist,
        })
    }

    pub fn from_target_uuid_attr_purge(
        ident: Identity,
        target_uuid: Uuid,
        attr: Attribute,
        filter: Filter<FilterInvalid>,
        qs: &QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let ml = ModifyList::new_purge(attr);
        let f_uuid = filter_all!(f_eq(Attribute::Uuid, PartialValue::Uuid(target_uuid)));
        // Add any supplemental conditions we have.
        let f = Filter::join_parts_and(f_uuid, filter);

        let filter_orig = f
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        let filter = filter_orig.clone().into_ignore_hidden();
        let modlist = ml
            .validate(qs.get_schema())
            .map_err(OperationError::SchemaViolation)?;
        Ok(ModifyEvent {
            ident,
            filter,
            filter_orig,
            modlist,
        })
    }

    pub fn new_internal(filter: Filter<FilterValid>, modlist: ModifyList<ModifyValid>) -> Self {
        ModifyEvent {
            ident: Identity::from_internal(),
            filter: filter.clone(),
            filter_orig: filter,
            modlist,
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_internal_invalid(
        filter: Filter<FilterInvalid>,
        modlist: ModifyList<ModifyInvalid>,
    ) -> Self {
        ModifyEvent {
            ident: Identity::from_internal(),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            modlist: modlist.into_valid(),
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_entry_ser(
        e: BuiltinAccount,
        filter: Filter<FilterInvalid>,
        modlist: ModifyList<ModifyInvalid>,
    ) -> Self {
        let ei: EntryInitNew = e.into();
        ModifyEvent {
            ident: Identity::from_impersonate_entry_readwrite(Arc::new(ei.into_sealed_committed())),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            modlist: modlist.into_valid(),
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_identity(
        ident: Identity,
        filter: Filter<FilterInvalid>,
        modlist: ModifyList<ModifyInvalid>,
    ) -> Self {
        ModifyEvent {
            ident,
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            modlist: modlist.into_valid(),
        }
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
        modlist: ModifyList<ModifyInvalid>,
    ) -> Self {
        ModifyEvent {
            ident: Identity::from_impersonate_entry_readwrite(e),
            filter: filter.clone().into_valid(),
            filter_orig: filter.into_valid(),
            modlist: modlist.into_valid(),
        }
    }

    pub fn new_impersonate(
        ident: &Identity,
        filter: Filter<FilterValid>,
        filter_orig: Filter<FilterValid>,
        modlist: ModifyList<ModifyValid>,
    ) -> Self {
        ModifyEvent {
            ident: Identity::from_impersonate(ident),
            filter,
            filter_orig,
            modlist,
        }
    }
}

pub struct WhoamiResult {
    youare: ProtoEntry,
}

impl WhoamiResult {
    pub fn new(
        qs: &mut QueryServerReadTransaction,
        e: &Entry<EntryReduced, EntryCommitted>,
    ) -> Result<Self, OperationError> {
        Ok(WhoamiResult {
            youare: e.to_pe(qs)?,
        })
    }

    pub fn response(self) -> WhoamiResponse {
        WhoamiResponse {
            youare: self.youare,
        }
    }
}

#[derive(Debug)]
pub struct PurgeTombstoneEvent {
    pub ident: Identity,
    pub eventid: Uuid,
}

impl Default for PurgeTombstoneEvent {
    fn default() -> Self {
        Self::new()
    }
}

impl PurgeTombstoneEvent {
    pub fn new() -> Self {
        PurgeTombstoneEvent {
            ident: Identity::from_internal(),
            eventid: Uuid::new_v4(),
        }
    }
}

#[derive(Debug)]
pub struct PurgeRecycledEvent {
    pub ident: Identity,
    pub eventid: Uuid,
}

impl Default for PurgeRecycledEvent {
    fn default() -> Self {
        Self::new()
    }
}

impl PurgeRecycledEvent {
    pub fn new() -> Self {
        PurgeRecycledEvent {
            ident: Identity::from_internal(),
            eventid: Uuid::new_v4(),
        }
    }
}

#[derive(Debug)]
pub struct OnlineBackupEvent {
    pub ident: Identity,
    pub eventid: Uuid,
}

impl Default for OnlineBackupEvent {
    fn default() -> Self {
        Self::new()
    }
}

impl OnlineBackupEvent {
    pub fn new() -> Self {
        OnlineBackupEvent {
            ident: Identity::from_internal(),
            eventid: Uuid::new_v4(),
        }
    }
}

#[derive(Debug)]
pub struct ReviveRecycledEvent {
    pub ident: Identity,
    // This is the filter, as it will be processed.
    pub filter: Filter<FilterValid>,
    // Unlike the others, because of how this works, we don't need the orig filter
    // to be retained, because the filter is the orig filter for this check.
    //
    // It will be duplicated into the modify ident as it exists.
}

impl ReviveRecycledEvent {
    pub fn from_parts(
        ident: Identity,
        filter: &Filter<FilterInvalid>,
        qs: &QueryServerWriteTransaction,
    ) -> Result<Self, OperationError> {
        let filter = filter
            .validate(qs.get_schema())
            .map(|f| f.into_recycled())
            .map_err(OperationError::SchemaViolation)?;
        Ok(ReviveRecycledEvent { ident, filter })
    }

    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
    /// This is a TEST ONLY method and will never be exposed in production.
    #[cfg(test)]
    pub fn new_impersonate_entry(
        e: Arc<Entry<EntrySealed, EntryCommitted>>,
        filter: Filter<FilterInvalid>,
    ) -> Self {
        ReviveRecycledEvent {
            ident: Identity::from_impersonate_entry_readwrite(e),
            filter: filter.into_valid(),
        }
    }

    #[cfg(test)]
    pub(crate) fn new_internal(filter: Filter<FilterValid>) -> Self {
        ReviveRecycledEvent {
            ident: Identity::from_internal(),
            filter,
        }
    }
}