Skip to main content

kanidmd_lib/
entry.rs

1//! Entries are the base unit of object storage in the server. This is one of the three foundational
2//! concepts along with [`filter`]s and [`schema`] that everything else builds upon.
3//!
4//! An [`Entry`] is a collection of attribute-value sets. There are sometimes called attribute value
5//! assertions, or AVAs. The attribute is a "key" and it holds 1 to infinite associated values
6//! with no ordering. An entry has many AVAs. A pseudo example, minus schema and typing:
7//!
8//! ```text
9//! Entry {
10//!   "name": ["william"],
11//!   "uuid": ["..."],
12//!   "mail": ["maila@example.com", "mailb@example.com"],
13//! };
14//! ```
15//!
16//! There are three rules for entries:
17//! * Must have an AVA for UUID containing a single value.
18//! * Any AVA with zero values will be removed.
19//! * AVAs are stored with no sorting.
20//!
21//! For more, see the [`Entry`] type.
22//!
23//! [`Entry`]: struct.Entry.html
24//! [`filter`]: ../filter/index.html
25//! [`schema`]: ../schema/index.html
26
27use crate::{
28    be::{
29        dbentry::{DbEntry, DbEntryVers},
30        dbvalue::DbValueSetV2,
31        IdxKey, IdxSlope,
32    },
33    credential::{apppwd::ApplicationPassword, Credential},
34    filter::{Filter, FilterInvalid, FilterResolved, FilterValidResolved},
35    idm::ldap::ldap_vattr_map,
36    modify::{Modify, ModifyInvalid, ModifyList, ModifyValid},
37    prelude::*,
38    repl::{
39        cid::Cid,
40        entry::EntryChangeState,
41        proto::{ReplEntryV1, ReplIncrementalEntryV1},
42    },
43    schema::{SchemaAttribute, SchemaClass, SchemaTransaction},
44    server::access::AccessEffectivePermission,
45    value::{
46        ApiToken, CredentialType, IndexType, IntentTokenState, Oauth2Session, PartialValue,
47        Session, SyntaxType, Value,
48    },
49    valueset::{self, ScimResolveStatus, ValueSet, ValueSetSpn},
50};
51use compact_jwt::JwsEs256Signer;
52use crypto_glue::s256::Sha256Output;
53use hashbrown::{HashMap, HashSet};
54use kanidm_proto::{
55    internal::{
56        ConsistencyError, Filter as ProtoFilter, ImageValue, OperationError, SchemaError, UiHint,
57    },
58    scim_v1::server::ScimEffectiveAccess,
59    v1::Entry as ProtoEntry,
60};
61use ldap3_proto::simple::{LdapPartialAttribute, LdapSearchResultEntry};
62use std::{
63    cmp::Ordering,
64    collections::{BTreeMap as Map, BTreeMap, BTreeSet},
65    sync::Arc,
66};
67use time::OffsetDateTime;
68use tracing::trace;
69use uuid::Uuid;
70use webauthn_rs::prelude::{
71    AttestationCaList, AttestedPasskey as AttestedPasskeyV4, Passkey as PasskeyV4,
72};
73
74pub type EntryInitNew = Entry<EntryInit, EntryNew>;
75pub type EntryInvalidNew = Entry<EntryInvalid, EntryNew>;
76pub type EntryRefreshNew = Entry<EntryRefresh, EntryNew>;
77pub type EntrySealedNew = Entry<EntrySealed, EntryNew>;
78pub type EntryValidCommitted = Entry<EntryValid, EntryCommitted>;
79pub type EntrySealedCommitted = Entry<EntrySealed, EntryCommitted>;
80pub type EntryInvalidCommitted = Entry<EntryInvalid, EntryCommitted>;
81pub type EntryReducedCommitted = Entry<EntryReduced, EntryCommitted>;
82pub type EntryTuple = (Arc<EntrySealedCommitted>, EntryInvalidCommitted);
83
84pub type EntryIncrementalNew = Entry<EntryIncremental, EntryNew>;
85pub type EntryIncrementalCommitted = Entry<EntryIncremental, EntryCommitted>;
86
87// Entry should have a lifecycle of types. This is Raw (modifiable) and Entry (verified).
88// This way, we can move between them, but only certain actions are possible on either
89// This means modifications happen on Raw, but to move to Entry, you schema normalise.
90// Vice versa, you can for free, move to Raw, but you lose the validation.
91
92// Because this is type system it's "free" in the end, and means we force validation
93// at the correct and required points of the entries life.
94
95// This is specifically important for the commit to the backend, as we only want to
96// commit validated types.
97
98// Has never been in the DB, so doesn't have an ID.
99#[derive(Clone, Debug)]
100pub struct EntryNew; // new
101
102// It's been in the DB, so it has an id
103#[derive(Clone, Debug)]
104pub struct EntryCommitted {
105    id: u64,
106}
107
108#[derive(Clone, Debug)]
109pub struct EntryInit;
110
111/*  |
112 *  | Init comes from a proto entry, it's new.
113 *  | We add the current Cid before we allow mods.
114 *  V
115 */
116
117#[derive(Clone, Debug)]
118pub struct EntryInvalid {
119    cid: Cid,
120    ecstate: EntryChangeState,
121}
122
123// Alternate path - this entry came from a full refresh, and already has an entry change state.
124#[derive(Clone, Debug)]
125pub struct EntryRefresh {
126    ecstate: EntryChangeState,
127}
128
129// Alternate path - this entry came from an incremental replication.
130#[derive(Clone, Debug)]
131pub struct EntryIncremental {
132    // Must have a uuid, else we can't proceed at all.
133    uuid: Uuid,
134    ecstate: EntryChangeState,
135}
136
137/*  |
138 *  | The changes made within this entry are validated by the schema.
139 *  V
140 */
141
142#[derive(Clone, Debug)]
143pub struct EntryValid {
144    // Asserted with schema, so we know it has a UUID now ...
145    uuid: Uuid,
146    ecstate: EntryChangeState,
147}
148
149/*  |
150 *  | The changes are extracted into the changelog as needed, creating a
151 *  | stable database entry.
152 *  V
153 */
154
155#[derive(Clone, Debug)]
156pub struct EntrySealed {
157    uuid: Uuid,
158    ecstate: EntryChangeState,
159}
160
161/*  |
162 *  | The entry has access controls applied to reduce what is yielded to a client
163 *  V
164 */
165
166#[derive(Clone, Debug)]
167pub struct EntryReduced {
168    uuid: Uuid,
169    effective_access: Option<Box<AccessEffectivePermission>>,
170}
171
172// One day this is going to be Map<Attribute, ValueSet> - @yaleman
173// Today is that day - @firstyear
174pub type Eattrs = Map<Attribute, ValueSet>;
175
176pub trait GetUuid {
177    fn get_uuid(&self) -> Uuid;
178}
179
180pub trait Committed {}
181
182impl Committed for EntrySealed {}
183impl Committed for EntryReduced {}
184
185pub(crate) fn compare_attrs(left: &Eattrs, right: &Eattrs) -> bool {
186    // We can't shortcut based on len because cid mod may not be present.
187    // Build the set of all keys between both.
188    let allkeys: BTreeSet<&Attribute> = left
189        .keys()
190        .chain(right.keys())
191        .filter(|k| *k != &Attribute::LastModifiedCid && *k != &Attribute::CreatedAtCid)
192        .collect();
193
194    allkeys.into_iter().all(|k| {
195        // Both must be Some, and both must have the same interiors.
196        let left_vs = left.get(k);
197        let right_vs = right.get(k);
198        let r = match (left_vs, right_vs) {
199            (Some(l), Some(r)) => l.eq(r),
200            _ => false,
201        };
202        if !r {
203            trace!(?k, ?left_vs, ?right_vs, "compare_attrs_allkeys");
204        }
205        r
206    })
207}
208
209/// Entry is the core data storage type of the server. Almost every aspect of the server is
210/// designed to read, handle and manipulate entries.
211///
212/// Entries store attribute value assertions, or AVA. These are sets of key-values.
213///
214/// Entries have a lifecycle within a single operation, and as part of replication.
215/// The lifecycle for operations is defined through state and valid types. Each entry has a pair
216/// Of these types at anytime. The first is the AVA [`schema`] and [`access`] control assertion
217/// state. This is represented by the type `VALID` as one of `EntryValid`, `EntryInvalid` or
218/// `EntryReduced`. Every entry starts as `EntryInvalid`, and when checked by the schema for
219/// correctness, transitions to `EntryValid`. While an entry is `EntryValid` it can not be
220/// altered - you must invalidate it to `EntryInvalid`, then modify, then check again.
221/// An entry that has had access controls applied moves from `EntryValid` to `EntryReduced`,
222/// to show that the AVAs have reduced to the valid read set of the current [`event`] user.
223///
224/// The second type of `STATE` represents the database commit state and internal db ID's. A
225/// new entry that has never been committed is `EntryNew`, but an entry that has been retrieved
226/// from the database is `EntryCommitted`. This affects the operations you can apply IE modify
227/// or delete.
228///
229/// These types exist to prevent at compile time, mishandling of Entries, to ensure they are always
230/// handled with the correct lifecycles and processes.
231///
232/// [`schema`]: ../schema/index.html
233/// [`access`]: ../access/index.html
234/// [`event`]: ../event/index.html
235pub struct Entry<VALID, STATE> {
236    valid: VALID,
237    state: STATE,
238    // We may need to change this to Set to allow borrow of Value -> PartialValue for lookups.
239    attrs: Eattrs,
240}
241
242impl<VALID, STATE> std::fmt::Debug for Entry<VALID, STATE>
243where
244    STATE: std::fmt::Debug,
245    VALID: std::fmt::Debug,
246{
247    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
248        f.debug_struct("Entry<EntrySealed, _>")
249            .field("state", &self.state)
250            .field("valid", &self.valid)
251            .field("attrs", &self.attrs)
252            .finish()
253    }
254}
255
256impl<STATE> std::fmt::Display for Entry<EntrySealed, STATE>
257where
258    STATE: Clone,
259{
260    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
261        write!(f, "{}", self.get_uuid())
262    }
263}
264
265impl<STATE> std::fmt::Display for Entry<EntryInit, STATE>
266where
267    STATE: Clone,
268{
269    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
270        write!(f, "Entry in initial state")
271    }
272}
273
274impl<STATE> Entry<EntryInit, STATE>
275where
276    STATE: Clone,
277{
278    /// Get the uuid of this entry.
279    pub fn get_uuid(&self) -> Option<Uuid> {
280        self.attrs
281            .get(&Attribute::Uuid)
282            .and_then(|vs| vs.to_uuid_single())
283    }
284}
285
286impl Default for Entry<EntryInit, EntryNew> {
287    fn default() -> Self {
288        Self::new()
289    }
290}
291
292impl FromIterator<(Attribute, ValueSet)> for EntryInitNew {
293    fn from_iter<I: IntoIterator<Item = (Attribute, ValueSet)>>(iter: I) -> Self {
294        let attrs = Eattrs::from_iter(iter);
295
296        Entry {
297            valid: EntryInit,
298            state: EntryNew,
299            attrs,
300        }
301    }
302}
303
304impl Entry<EntryInit, EntryNew> {
305    pub fn new() -> Self {
306        Entry {
307            // This means NEVER COMMITTED
308            valid: EntryInit,
309            state: EntryNew,
310            attrs: Map::new(),
311        }
312    }
313
314    /// Consume a Protocol Entry from JSON, and validate and process the data into an internal
315    /// [`Entry`] type.
316    pub fn from_proto_entry(
317        e: &ProtoEntry,
318        qs: &mut QueryServerWriteTransaction,
319    ) -> Result<Self, OperationError> {
320        trace!("from_proto_entry");
321        // Why not the trait? In the future we may want to extend
322        // this with server aware functions for changes of the
323        // incoming data.
324
325        // Somehow we need to take the tree of e attrs, and convert
326        // all ref types to our types ...
327        let map2: Result<Eattrs, OperationError> = e
328            .attrs
329            .iter()
330            .filter(|(_, v)| !v.is_empty())
331            .map(|(k, v)| {
332                trace!(?k, ?v, "attribute");
333                let attr_nk = Attribute::from(k.as_str());
334                // TODO: Make this look up the syntax, then use that
335                // to guide the Valueset.
336
337                let nv = valueset::from_result_value_iter(
338                    v.iter().map(|vr| qs.clone_value(&attr_nk, vr)),
339                );
340                trace!(?nv, "new valueset transform");
341                match nv {
342                    Ok(nvi) => Ok((attr_nk, nvi)),
343                    Err(e) => Err(e),
344                }
345            })
346            .collect();
347
348        let x = map2?;
349
350        Ok(Entry {
351            state: EntryNew,
352            valid: EntryInit,
353            attrs: x,
354        })
355    }
356
357    /// Given a proto entry in JSON formed as a serialised string, processed that string
358    /// into an Entry.
359    #[instrument(level = "debug", skip_all)]
360    pub fn from_proto_entry_str(
361        es: &str,
362        qs: &mut QueryServerWriteTransaction,
363    ) -> Result<Self, OperationError> {
364        if cfg!(test) {
365            if es.len() > 256 {
366                let (dsp_es, _) = es.split_at(255);
367                trace!("Parsing -> {}...", dsp_es);
368            } else {
369                trace!("Parsing -> {}", es);
370            }
371        }
372        // str -> Proto entry
373        let pe: ProtoEntry = serde_json::from_str(es).map_err(|e| {
374            // We probably shouldn't print ES here because that would allow users
375            // to inject content into our logs :)
376            admin_error!(?e, "SerdeJson Failure");
377            OperationError::SerdeJsonError
378        })?;
379        // now call from_proto_entry
380        Self::from_proto_entry(&pe, qs)
381    }
382
383    /// Assign the Change Identifier to this Entry, allowing it to be modified and then
384    /// written to the `Backend`
385    pub fn assign_cid(
386        mut self,
387        cid: Cid,
388        schema: &dyn SchemaTransaction,
389    ) -> Entry<EntryInvalid, EntryNew> {
390        /*
391         * Create the change log. This must be the last thing BEFORE we return!
392         * This is because we need to capture the set_last_changed attribute in
393         * the create transition.
394         */
395        let ecstate = EntryChangeState::new(&cid, &self.attrs, schema);
396
397        // Since the entry is now created, and modified here, we set the initial CID
398        // values.
399        let cv = vs_cid![cid.clone()];
400        let _ = self.attrs.insert(Attribute::LastModifiedCid, cv);
401        let cv = vs_cid![cid.clone()];
402        let _ = self.attrs.insert(Attribute::CreatedAtCid, cv);
403
404        Entry {
405            valid: EntryInvalid { cid, ecstate },
406            state: EntryNew,
407            attrs: self.attrs,
408        }
409    }
410
411    /// Compare this entry to another.
412    pub fn compare(&self, rhs: &Entry<EntrySealed, EntryCommitted>) -> bool {
413        compare_attrs(&self.attrs, &rhs.attrs)
414    }
415
416    /// ⚠️  This function bypasses the db commit and creates invalid replication metadata.
417    /// The entry it creates can never be replicated.
418    /// This is a TEST ONLY method and will never be exposed in production.
419    #[cfg(test)]
420    pub fn into_invalid_new(mut self) -> Entry<EntryInvalid, EntryNew> {
421        let cid = Cid::new_zero();
422        self.set_last_changed(cid.clone());
423
424        let ecstate = EntryChangeState::new_without_schema(&cid, &self.attrs);
425
426        Entry {
427            valid: EntryInvalid { cid, ecstate },
428            state: EntryNew,
429            attrs: self.attrs,
430        }
431    }
432
433    /// ⚠️  This function bypasses the db commit and creates invalid replication metadata.
434    /// The entry it creates can never be replicated.
435    /// This is a TEST ONLY method and will never be exposed in production.
436    #[cfg(test)]
437    pub fn into_valid_new(mut self) -> Entry<EntryValid, EntryNew> {
438        let cid = Cid::new_zero();
439        self.set_last_changed(cid.clone());
440        let ecstate = EntryChangeState::new_without_schema(&cid, &self.attrs);
441
442        Entry {
443            valid: EntryValid {
444                ecstate,
445                uuid: self.get_uuid().expect("Invalid uuid"),
446            },
447            state: EntryNew,
448            attrs: self.attrs,
449        }
450    }
451
452    /// ⚠️  This function bypasses the db commit, assigns fake db ids, and invalid replication metadata.
453    /// The entry it creates can never be committed safely or replicated.
454    /// This is a TEST ONLY method and will never be exposed in production.
455    #[cfg(test)]
456    pub fn into_sealed_committed(mut self) -> Entry<EntrySealed, EntryCommitted> {
457        let cid = Cid::new_zero();
458        self.set_last_changed(cid.clone());
459        let ecstate = EntryChangeState::new_without_schema(&cid, &self.attrs);
460        let uuid = self.get_uuid().unwrap_or_else(Uuid::new_v4);
461        Entry {
462            valid: EntrySealed { uuid, ecstate },
463            state: EntryCommitted { id: 0 },
464            attrs: self.attrs,
465        }
466    }
467
468    /// ⚠️  This function bypasses the db commit and creates invalid replication metadata.
469    /// The entry it creates can never be replicated.
470    /// This is a TEST ONLY method and will never be exposed in production.
471    #[cfg(test)]
472    pub fn into_sealed_new(mut self) -> Entry<EntrySealed, EntryNew> {
473        let cid = Cid::new_zero();
474        self.set_last_changed(cid.clone());
475        let ecstate = EntryChangeState::new_without_schema(&cid, &self.attrs);
476
477        Entry {
478            valid: EntrySealed {
479                uuid: self.get_uuid().expect("Invalid uuid"),
480                ecstate,
481            },
482            state: EntryNew,
483            attrs: self.attrs,
484        }
485    }
486
487    //              ⚠️   replication safety  ⚠️
488    // These functions are SAFE because they occur in the EntryInit
489    // state, which precedes the generation of the initial Create
490    // event for the attribute.
491    /// Add an attribute-value-assertion to this Entry.
492    pub fn add_ava(&mut self, attr: Attribute, value: Value) {
493        self.add_ava_int(attr, value);
494    }
495
496    pub fn pop_ava<A: AsRef<Attribute>>(&mut self, attr: A) -> Option<ValueSet> {
497        self.attrs.remove(attr.as_ref())
498    }
499
500    pub fn remove_ava<A: AsRef<Attribute>>(&mut self, attr: A) {
501        self.pop_ava(attr);
502    }
503
504    /// Set the content of this ava with this valueset, ignoring the previous data.
505    pub fn set_ava_set(&mut self, attr: &Attribute, vs: ValueSet) {
506        self.attrs.insert(attr.clone(), vs);
507    }
508
509    /// Replace the existing content of an attribute set of this Entry, with a new set of Values.
510    pub fn set_ava<T>(&mut self, attr: Attribute, iter: T)
511    where
512        T: IntoIterator<Item = Value>,
513    {
514        self.set_ava_iter_int(attr, iter);
515    }
516
517    pub fn get_ava_mut<A: AsRef<Attribute>>(&mut self, attr: A) -> Option<&mut ValueSet> {
518        self.attrs.get_mut(attr.as_ref())
519    }
520}
521
522impl From<SchemaAttribute> for EntryInitNew {
523    fn from(value: SchemaAttribute) -> Self {
524        EntryInitNew::from(&value)
525    }
526}
527
528impl From<&SchemaAttribute> for EntryInitNew {
529    fn from(s: &SchemaAttribute) -> Self {
530        // Build the Map of the attributes
531        let mut attrs = Eattrs::new();
532        attrs.insert(Attribute::AttributeName, vs_iutf8![s.name.as_str()]);
533        attrs.insert(Attribute::Description, vs_utf8![s.description.to_owned()]);
534        attrs.insert(Attribute::Uuid, vs_uuid![s.uuid]);
535        attrs.insert(Attribute::MultiValue, vs_bool![s.multivalue]);
536        attrs.insert(Attribute::Phantom, vs_bool![s.phantom]);
537        attrs.insert(Attribute::SyncAllowed, vs_bool![s.sync_allowed]);
538        attrs.insert(Attribute::Replicated, vs_bool![s.replicated.into()]);
539        attrs.insert(Attribute::Unique, vs_bool![s.unique]);
540        attrs.insert(Attribute::Indexed, vs_bool![s.indexed]);
541        attrs.insert(Attribute::Syntax, vs_syntax![s.syntax]);
542        attrs.insert(
543            Attribute::Class,
544            vs_iutf8n![
545                EntryClass::Object.into(),
546                EntryClass::System.into(),
547                EntryClass::AttributeType.into()
548            ],
549        );
550
551        // Insert stuff.
552
553        Entry {
554            valid: EntryInit,
555            state: EntryNew,
556            attrs,
557        }
558    }
559}
560
561impl From<SchemaClass> for EntryInitNew {
562    fn from(value: SchemaClass) -> Self {
563        EntryInitNew::from(&value)
564    }
565}
566
567impl From<&SchemaClass> for EntryInitNew {
568    fn from(s: &SchemaClass) -> Self {
569        let mut attrs = Eattrs::new();
570        attrs.insert(Attribute::ClassName, vs_iutf8![s.name.as_str()]);
571        attrs.insert(Attribute::Description, vs_utf8![s.description.to_owned()]);
572        attrs.insert(Attribute::SyncAllowed, vs_bool![s.sync_allowed]);
573        attrs.insert(Attribute::Uuid, vs_uuid![s.uuid]);
574        attrs.insert(
575            Attribute::Class,
576            vs_iutf8n![
577                EntryClass::Object.into(),
578                EntryClass::System.into(),
579                EntryClass::ClassType.into()
580            ],
581        );
582
583        let vs_systemmay = ValueSetIutf8N::from_iter(s.systemmay.iter().map(|sm| sm.as_str()));
584        if let Some(vs) = vs_systemmay {
585            attrs.insert(Attribute::SystemMay, vs);
586        }
587
588        let vs_systemmust = ValueSetIutf8N::from_iter(s.systemmust.iter().map(|sm| sm.as_str()));
589        if let Some(vs) = vs_systemmust {
590            attrs.insert(Attribute::SystemMust, vs);
591        }
592
593        let vs_systemexcludes =
594            ValueSetIutf8N::from_iter(s.systemexcludes.iter().map(|sm| sm.as_str()));
595        if let Some(vs) = vs_systemexcludes {
596            attrs.insert(Attribute::SystemExcludes, vs);
597        }
598
599        let vs_systemsupplements =
600            ValueSetIutf8N::from_iter(s.systemsupplements.iter().map(|sm| sm.as_str()));
601        if let Some(vs) = vs_systemsupplements {
602            attrs.insert(Attribute::SystemSupplements, vs);
603        }
604
605        Entry {
606            valid: EntryInit,
607            state: EntryNew,
608            attrs,
609        }
610    }
611}
612
613impl Entry<EntryRefresh, EntryNew> {
614    pub fn from_repl_entry_v1(repl_entry: ReplEntryV1) -> Result<Self, OperationError> {
615        // From the entry, we have to rebuild the ecstate and the attrs.
616        let (ecstate, mut attrs) = repl_entry.rehydrate()?;
617
618        // During seal, these values will be re-written, but we need them present for
619        // schema validation.
620        let last_mod_cid = ecstate.get_max_cid();
621        let cv = vs_cid![last_mod_cid.clone()];
622        let _ = attrs.insert(Attribute::LastModifiedCid, cv);
623
624        let create_at_cid = ecstate.at();
625        let cv = vs_cid![create_at_cid.clone()];
626        let _ = attrs.insert(Attribute::CreatedAtCid, cv);
627
628        Ok(Entry {
629            valid: EntryRefresh { ecstate },
630            state: EntryNew,
631            attrs,
632        })
633    }
634}
635
636impl<STATE> Entry<EntryRefresh, STATE> {
637    pub fn validate(
638        self,
639        schema: &dyn SchemaTransaction,
640    ) -> Result<Entry<EntryValid, STATE>, SchemaError> {
641        let uuid: Uuid = self
642            .attrs
643            .get(&Attribute::Uuid)
644            .ok_or_else(|| SchemaError::MissingMustAttribute(vec![Attribute::Uuid]))
645            .and_then(|vs| {
646                vs.to_uuid_single()
647                    .ok_or_else(|| SchemaError::MissingMustAttribute(vec![Attribute::Uuid]))
648            })?;
649
650        // Build the new valid entry ...
651        let ne = Entry {
652            valid: EntryValid {
653                uuid,
654                ecstate: self.valid.ecstate,
655            },
656            state: self.state,
657            attrs: self.attrs,
658        };
659
660        ne.validate(schema).map(|()| ne)
661    }
662}
663
664impl<STATE> Entry<EntryIncremental, STATE> {
665    pub fn get_uuid(&self) -> Uuid {
666        self.valid.uuid
667    }
668}
669
670impl Entry<EntryIncremental, EntryNew> {
671    fn stub_ecstate(&self) -> EntryChangeState {
672        self.valid.ecstate.stub()
673    }
674
675    pub fn rehydrate(repl_inc_entry: ReplIncrementalEntryV1) -> Result<Self, OperationError> {
676        let (uuid, ecstate, attrs) = repl_inc_entry.rehydrate()?;
677
678        Ok(Entry {
679            valid: EntryIncremental { uuid, ecstate },
680            state: EntryNew,
681            attrs,
682        })
683    }
684
685    pub(crate) fn is_add_conflict(&self, db_entry: &EntrySealedCommitted) -> bool {
686        use crate::repl::entry::State;
687        debug_assert_eq!(self.valid.uuid, db_entry.valid.uuid);
688        // This is a conflict if the state 'at' is not identical
689        let self_cs = &self.valid.ecstate;
690        let db_cs = db_entry.get_changestate();
691
692        // Can only add conflict on live entries.
693        match (self_cs.current(), db_cs.current()) {
694            (State::Live { at: at_left, .. }, State::Live { at: at_right, .. }) => {
695                at_left != at_right
696            }
697            // Tombstone will always overwrite.
698            _ => false,
699        }
700    }
701
702    pub(crate) fn resolve_add_conflict(
703        &self,
704        cid: &Cid,
705        db_ent: &EntrySealedCommitted,
706    ) -> (Option<EntrySealedNew>, EntryIncrementalCommitted) {
707        use crate::repl::entry::State;
708        debug_assert_eq!(self.valid.uuid, db_ent.valid.uuid);
709        let self_cs = &self.valid.ecstate;
710        let db_cs = db_ent.get_changestate();
711
712        match (self_cs.current(), db_cs.current()) {
713            (
714                State::Live {
715                    at: at_left,
716                    changes: _changes_left,
717                },
718                State::Live {
719                    at: at_right,
720                    changes: _changes_right,
721                },
722            ) => {
723                debug_assert!(at_left != at_right);
724                // Determine which of the entries must become the conflict
725                // and which will now persist. There are three possible cases.
726                //
727                // 1. The incoming ReplIncremental is after DBentry. This means RI is the
728                //    conflicting node. We take no action and just return the db_ent
729                //    as the valid state.
730                //
731                //    Since we are returning the existing database entry, we already have
732                //    locally applies the needed LastModifiedCid and CreatedAtCid. We
733                //    can proceed with no other changes.
734                if at_left > at_right {
735                    trace!("RI > DE, return DE");
736                    (
737                        None,
738                        Entry {
739                            valid: EntryIncremental {
740                                uuid: db_ent.valid.uuid,
741                                ecstate: db_cs.clone(),
742                            },
743                            state: EntryCommitted {
744                                id: db_ent.state.id,
745                            },
746                            attrs: db_ent.attrs.clone(),
747                        },
748                    )
749                }
750                //
751                // 2. The incoming ReplIncremental is before DBentry. This means our
752                //    DE is the conflicting note. There are now two choices:
753                //    a.  We are the origin of the DE, and thus must create the conflict
754                //        entry for replication (to guarantee single create)
755                //    b.  We are not the origin of the DE and so do not create a conflict
756                //        entry.
757                //    In both cases we update the DE with the state of RI after we have
758                //    followed the above logic.
759                else {
760                    trace!("RI < DE, return RI");
761                    // Are we the origin?
762                    let conflict = if at_right.s_uuid == cid.s_uuid {
763                        trace!("Origin process conflict entry");
764                        // We are making a new entry!
765
766                        let mut cnf_ent = Entry {
767                            valid: EntryInvalid {
768                                cid: cid.clone(),
769                                ecstate: db_cs.clone(),
770                            },
771                            state: EntryNew,
772                            attrs: db_ent.attrs.clone(),
773                        };
774
775                        // Move the current uuid to source_uuid
776                        cnf_ent.set_ava_set(
777                            &Attribute::SourceUuid,
778                            ValueSetUuidN::new(db_ent.valid.uuid),
779                        );
780
781                        // We need to make a random uuid in the conflict gen process.
782                        let new_uuid = Uuid::new_v4();
783                        cnf_ent.purge_ava(Attribute::Uuid);
784                        cnf_ent.add_ava(Attribute::Uuid, Value::Uuid(new_uuid));
785                        cnf_ent.add_ava(Attribute::Class, EntryClass::Recycled.into());
786                        cnf_ent.add_ava(Attribute::Class, EntryClass::Conflict.into());
787
788                        // Bypass add_ava here so that we don't update the ecstate with the
789                        // metadata of these attrs.
790                        // Setup the last changed to now.
791                        let cv = vs_cid![cid.clone()];
792                        let _ = cnf_ent.attrs.insert(Attribute::LastModifiedCid, cv);
793                        // Set the created_at to now, since we are creating a new conflict entry here.
794                        let cv = vs_cid![cid.clone()];
795                        let _ = cnf_ent.attrs.insert(Attribute::CreatedAtCid, cv);
796
797                        // Now we have to internally bypass some states.
798                        // This is okay because conflict entries aren't subject
799                        // to schema anyway.
800                        let Entry {
801                            valid: EntryInvalid { cid: _, ecstate },
802                            state,
803                            attrs,
804                        } = cnf_ent;
805
806                        let cnf_ent = Entry {
807                            valid: EntrySealed {
808                                uuid: new_uuid,
809                                ecstate,
810                            },
811                            state,
812                            attrs,
813                        };
814
815                        Some(cnf_ent)
816                    } else {
817                        None
818                    };
819
820                    // Since we are going to make the incoming node, we need to now
821                    // populate it's last-mod and created attributes.
822
823                    let mut attrs = self.attrs.clone();
824                    let ecstate = self_cs.clone();
825
826                    let last_mod_cid = ecstate.get_max_cid();
827                    let cv = vs_cid![last_mod_cid.clone()];
828                    let _ = attrs.insert(Attribute::LastModifiedCid, cv);
829
830                    let create_at_cid = ecstate.at();
831                    let cv = vs_cid![create_at_cid.clone()];
832                    let _ = attrs.insert(Attribute::CreatedAtCid, cv);
833
834                    (
835                        conflict,
836                        Entry {
837                            valid: EntryIncremental {
838                                uuid: self.valid.uuid,
839                                ecstate,
840                            },
841                            state: EntryCommitted {
842                                id: db_ent.state.id,
843                            },
844                            attrs,
845                        },
846                    )
847                }
848            }
849            // Can never get here due to is_add_conflict above. This is because
850            // a tombstone state on either branch will trigger is_add_conflict
851            // causing this to be impossible to reach.
852            _ => unreachable!(),
853        }
854    }
855
856    pub(crate) fn merge_state(
857        &self,
858        db_ent: &EntrySealedCommitted,
859        schema: &dyn SchemaTransaction,
860        trim_cid: &Cid,
861    ) -> EntryIncrementalCommitted {
862        use crate::repl::entry::State;
863
864        // Paranoid check.
865        debug_assert_eq!(self.valid.uuid, db_ent.valid.uuid);
866
867        // First, determine if either side is a tombstone. This is needed so that only
868        // when both sides are live
869        let self_cs = &self.valid.ecstate;
870        let db_cs = db_ent.get_changestate();
871
872        match (self_cs.current(), db_cs.current()) {
873            (
874                State::Live {
875                    at: at_left,
876                    changes: changes_left,
877                },
878                State::Live {
879                    at: at_right,
880                    changes: changes_right,
881                },
882            ) => {
883                debug_assert_eq!(at_left, at_right);
884                // Given the current db entry, compare and merge our attributes to
885                // form a resultant entry attr and ecstate
886                //
887                // To shortcut this we dedup the attr set and then iterate.
888                let mut attr_set: Vec<_> =
889                    changes_left.keys().chain(changes_right.keys()).collect();
890                attr_set.shrink_to_fit();
891                attr_set.sort_unstable();
892                attr_set.dedup();
893
894                // Make a new ecstate and attrs set.
895                let mut changes = BTreeMap::default();
896                let mut eattrs = Eattrs::default();
897
898                // Now we have the set of attrs from both sides. Lets see what state they are in!
899                for attr_name in attr_set.into_iter() {
900                    match (changes_left.get(attr_name), changes_right.get(attr_name)) {
901                        (Some(cid_left), Some(cid_right)) => {
902                            // This is the normal / usual and most "fun" case. Here we need to determine
903                            // which side is latest and then do a valueset merge. This is also
904                            // needing schema awareness depending on the attribute!
905                            //
906                            // The behaviour is very dependent on the state of the attributes and
907                            // if they exist.
908                            let take_left = cid_left > cid_right;
909
910                            match (self.attrs.get(attr_name), db_ent.attrs.get(attr_name)) {
911                                (Some(vs_left), Some(vs_right)) if take_left => {
912                                    changes.insert(attr_name.clone(), cid_left.clone());
913                                    if let Some(merged_attr_state) =
914                                        vs_left.repl_merge_valueset(vs_right, trim_cid)
915                                    {
916                                        // NOTE: This is for special attr types that need to merge
917                                        // rather than choose content.
918                                        eattrs.insert(attr_name.clone(), merged_attr_state);
919                                    } else {
920                                        eattrs.insert(attr_name.clone(), vs_left.clone());
921                                    }
922                                }
923                                (Some(vs_left), Some(vs_right)) => {
924                                    changes.insert(attr_name.clone(), cid_right.clone());
925                                    if let Some(merged_attr_state) =
926                                        vs_right.repl_merge_valueset(vs_left, trim_cid)
927                                    {
928                                        // NOTE: This is for special attr types that need to merge
929                                        // rather than choose content.
930                                        eattrs.insert(attr_name.clone(), merged_attr_state);
931                                    } else {
932                                        eattrs.insert(attr_name.clone(), vs_right.clone());
933                                    }
934                                }
935                                (Some(vs_left), None) if take_left => {
936                                    changes.insert(attr_name.clone(), cid_left.clone());
937                                    eattrs.insert(attr_name.clone(), vs_left.clone());
938                                }
939                                (Some(_vs_left), None) => {
940                                    changes.insert(attr_name.clone(), cid_right.clone());
941                                    // Taking right, nothing to do due to no attr.
942                                }
943                                (None, Some(_vs_right)) if take_left => {
944                                    changes.insert(attr_name.clone(), cid_left.clone());
945                                    // Taking left, nothing to do due to no attr.
946                                }
947                                (None, Some(vs_right)) => {
948                                    changes.insert(attr_name.clone(), cid_right.clone());
949                                    eattrs.insert(attr_name.clone(), vs_right.clone());
950                                }
951                                (None, None) if take_left => {
952                                    changes.insert(attr_name.clone(), cid_left.clone());
953                                    // Taking left, nothing to do due to no attr.
954                                }
955                                (None, None) => {
956                                    changes.insert(attr_name.clone(), cid_right.clone());
957                                    // Taking right, nothing to do due to no attr.
958                                }
959                            }
960                            // End attr merging
961                        }
962                        (Some(cid_left), None) => {
963                            // Keep the value on the left.
964                            changes.insert(attr_name.clone(), cid_left.clone());
965                            if let Some(valueset) = self.attrs.get(attr_name) {
966                                eattrs.insert(attr_name.clone(), valueset.clone());
967                            }
968                        }
969                        (None, Some(cid_right)) => {
970                            // Keep the value on the right.
971                            changes.insert(attr_name.clone(), cid_right.clone());
972                            if let Some(valueset) = db_ent.attrs.get(attr_name) {
973                                eattrs.insert(attr_name.clone(), valueset.clone());
974                            }
975                        }
976                        (None, None) => {
977                            // Should be impossible! At least one side or the other must have a change.
978                            debug_assert!(false);
979                        }
980                    }
981                }
982
983                let mut ecstate = EntryChangeState::build(State::Live {
984                    at: at_left.clone(),
985                    changes,
986                });
987
988                // Similar to the process of "seal", remove anything that isn't
989                // replicated from the ecstate (should be a no-op), and then update
990                // the created/mod cid's.
991                ecstate.retain(|k, _| schema.is_replicated(k));
992
993                let cv = vs_cid![ecstate.get_max_cid().clone()];
994                let _ = eattrs.insert(Attribute::LastModifiedCid, cv);
995
996                let cv = vs_cid![ecstate.at().clone()];
997                let _ = eattrs.insert(Attribute::CreatedAtCid, cv);
998
999                Entry {
1000                    valid: EntryIncremental {
1001                        uuid: self.valid.uuid,
1002                        ecstate,
1003                    },
1004                    state: EntryCommitted {
1005                        id: db_ent.state.id,
1006                    },
1007                    attrs: eattrs,
1008                }
1009            }
1010            (State::Tombstone { at: left_at }, State::Live { .. }) => {
1011                // We have to generate the attrs here, since on replication
1012                // we just send the tombstone ecstate rather than attrs. Our
1013                // db stub also lacks these attributes too.
1014                let mut attrs_new: Eattrs = Map::new();
1015                let class_ava = vs_iutf8n![EntryClass::Object.into(), EntryClass::Tombstone.into()];
1016                let last_mod_ava = vs_cid![left_at.clone()];
1017                let created_ava = vs_cid![left_at.clone()];
1018
1019                attrs_new.insert(Attribute::Uuid, vs_uuid![self.valid.uuid]);
1020                attrs_new.insert(Attribute::Class, class_ava);
1021                attrs_new.insert(Attribute::LastModifiedCid, last_mod_ava);
1022                attrs_new.insert(Attribute::CreatedAtCid, created_ava);
1023
1024                Entry {
1025                    valid: EntryIncremental {
1026                        uuid: self.valid.uuid,
1027                        ecstate: self.valid.ecstate.clone(),
1028                    },
1029                    state: EntryCommitted {
1030                        id: db_ent.state.id,
1031                    },
1032                    attrs: attrs_new,
1033                }
1034            }
1035            (State::Live { .. }, State::Tombstone { .. }) => {
1036                // Our current DB entry is a tombstone - ignore the incoming live
1037                // entry and just retain our DB tombstone.
1038                //
1039                // Note we don't need to gen the attrs here since if a stub was made then
1040                // we'd be live:live. To be in live:ts, then our db entry MUST exist and
1041                // must be a ts.
1042
1043                Entry {
1044                    valid: EntryIncremental {
1045                        uuid: db_ent.valid.uuid,
1046                        ecstate: db_ent.valid.ecstate.clone(),
1047                    },
1048                    state: EntryCommitted {
1049                        id: db_ent.state.id,
1050                    },
1051                    attrs: db_ent.attrs.clone(),
1052                }
1053            }
1054            (State::Tombstone { at: left_at }, State::Tombstone { at: right_at }) => {
1055                // WARNING - this differs from the other tombstone check cases
1056                // lower of the two AT values. This way replicas always have the
1057                // earliest TS value. It's a rare case but needs handling.
1058
1059                let (at, ecstate) = if left_at < right_at {
1060                    (left_at, self.valid.ecstate.clone())
1061                } else {
1062                    (right_at, db_ent.valid.ecstate.clone())
1063                };
1064
1065                let mut attrs_new: Eattrs = Map::new();
1066                let class_ava = vs_iutf8n![EntryClass::Object.into(), EntryClass::Tombstone.into()];
1067                let last_mod_ava = vs_cid![at.clone()];
1068                let created_ava = vs_cid![at.clone()];
1069
1070                attrs_new.insert(Attribute::Uuid, vs_uuid![db_ent.valid.uuid]);
1071                attrs_new.insert(Attribute::Class, class_ava);
1072                attrs_new.insert(Attribute::LastModifiedCid, last_mod_ava);
1073                attrs_new.insert(Attribute::CreatedAtCid, created_ava);
1074
1075                Entry {
1076                    valid: EntryIncremental {
1077                        uuid: db_ent.valid.uuid,
1078                        ecstate,
1079                    },
1080                    state: EntryCommitted {
1081                        id: db_ent.state.id,
1082                    },
1083                    attrs: attrs_new,
1084                }
1085            }
1086        }
1087    }
1088}
1089
1090impl Entry<EntryIncremental, EntryCommitted> {
1091    pub(crate) fn validate_repl(self, schema: &dyn SchemaTransaction) -> EntryValidCommitted {
1092        // Unlike the other method of schema validation, we can't return an error
1093        // here when schema fails - we need to in-place move the entry to a
1094        // conflict state so that the replication can proceed.
1095
1096        let mut ne = Entry {
1097            valid: EntryValid {
1098                uuid: self.valid.uuid,
1099                ecstate: self.valid.ecstate,
1100            },
1101            state: self.state,
1102            attrs: self.attrs,
1103        };
1104
1105        if let Err(e) = ne.validate(schema) {
1106            warn!(uuid = ?self.valid.uuid, err = ?e, "Entry failed schema check, moving to a conflict state");
1107            ne.add_ava_int(Attribute::Class, EntryClass::Recycled.into());
1108            ne.add_ava_int(Attribute::Class, EntryClass::Conflict.into());
1109
1110            ne.set_ava_int(
1111                Attribute::SourceUuid,
1112                ValueSetUuidN::new(self.valid.uuid) as ValueSet,
1113            );
1114        }
1115        ne
1116    }
1117}
1118
1119impl<STATE> Entry<EntryInvalid, STATE> {
1120    pub(crate) fn get_uuid(&self) -> Option<Uuid> {
1121        self.attrs
1122            .get(&Attribute::Uuid)
1123            .and_then(|vs| vs.to_uuid_single())
1124    }
1125
1126    /// Validate that this entry and its attribute-value sets are conformant to the system's'
1127    /// schema and the relevant syntaxes.
1128    pub fn validate(
1129        self,
1130        schema: &dyn SchemaTransaction,
1131    ) -> Result<Entry<EntryValid, STATE>, SchemaError> {
1132        let uuid: Uuid = self
1133            .attrs
1134            .get(&Attribute::Uuid)
1135            .ok_or_else(|| SchemaError::MissingMustAttribute(vec![Attribute::Uuid]))
1136            .and_then(|vs| {
1137                vs.to_uuid_single()
1138                    .ok_or_else(|| SchemaError::MissingMustAttribute(vec![Attribute::Uuid]))
1139            })?;
1140
1141        // Build the new valid entry ...
1142        let ne = Entry {
1143            valid: EntryValid {
1144                uuid,
1145                ecstate: self.valid.ecstate,
1146            },
1147            state: self.state,
1148            attrs: self.attrs,
1149        };
1150
1151        ne.validate(schema).map(|()| ne)
1152    }
1153
1154    /// Access a reference set in a directly mutable form. This is "safe" because
1155    /// referential integrity will check the values added are valid, and because
1156    /// this is strongly typed it can't violate syntax.
1157    pub(crate) fn get_ava_refer_mut<A: AsRef<Attribute>>(
1158        &mut self,
1159        attr: A,
1160    ) -> Option<&mut BTreeSet<Uuid>> {
1161        self.get_ava_mut(attr).and_then(|vs| vs.as_refer_set_mut())
1162    }
1163
1164    pub(crate) fn get_ava_mut<A: AsRef<Attribute>>(&mut self, attr: A) -> Option<&mut ValueSet> {
1165        let attr_ref = attr.as_ref();
1166        self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
1167        self.attrs.get_mut(attr.as_ref())
1168    }
1169}
1170
1171impl<VALID, STATE> Clone for Entry<VALID, STATE>
1172where
1173    VALID: Clone,
1174    STATE: Clone,
1175{
1176    // Dirty modifiable state. Works on any other state to dirty them.
1177    fn clone(&self) -> Entry<VALID, STATE> {
1178        Entry {
1179            valid: self.valid.clone(),
1180            state: self.state.clone(),
1181            attrs: self.attrs.clone(),
1182        }
1183    }
1184}
1185
1186impl Entry<EntryInvalid, EntryCommitted> {
1187    /// ⚠️  This function bypasses the schema validation and can panic if uuid is not found.
1188    /// The entry it creates can never be committed safely or replicated.
1189    /// This is a TEST ONLY method and will never be exposed in production.
1190    #[cfg(test)]
1191    pub fn into_valid_new(self) -> Entry<EntryValid, EntryNew> {
1192        let uuid = self.get_uuid().expect("Invalid uuid");
1193        Entry {
1194            valid: EntryValid {
1195                uuid,
1196                ecstate: self.valid.ecstate,
1197            },
1198            state: EntryNew,
1199            attrs: self.attrs,
1200        }
1201    }
1202
1203    /// Convert this entry into a recycled entry, that is "in the recycle bin".
1204    pub fn to_recycled(mut self) -> Self {
1205        // This will put the modify ahead of the recycle transition.
1206        self.add_ava(Attribute::Class, EntryClass::Recycled.into());
1207
1208        // Change state repl doesn't need this flag
1209        // self.valid.ecstate.recycled(&self.valid.cid);
1210
1211        Entry {
1212            valid: self.valid,
1213            state: self.state,
1214            attrs: self.attrs,
1215        }
1216    }
1217
1218    /// Convert this entry into a conflict, declaring what entries it conflicted against.
1219    pub fn to_conflict<T>(&mut self, iter: T)
1220    where
1221        T: IntoIterator<Item = Uuid>,
1222    {
1223        self.add_ava(Attribute::Class, EntryClass::Recycled.into());
1224        self.add_ava(Attribute::Class, EntryClass::Conflict.into());
1225        // Add all the source uuids we conflicted against.
1226        if let Some(vs) = ValueSetUuidN::from_iter(iter) {
1227            self.set_ava_set(&Attribute::SourceUuid, vs as ValueSet)
1228        };
1229    }
1230
1231    /// Extract this entry from the recycle bin into a live state.
1232    pub fn to_revived(mut self) -> Self {
1233        // This will put the modify ahead of the revive transition.
1234        self.remove_ava(Attribute::Class, &EntryClass::Recycled.into());
1235        self.remove_ava(Attribute::Class, &EntryClass::Conflict.into());
1236
1237        self.purge_ava(Attribute::CascadeDeleted);
1238        self.purge_ava(Attribute::SourceUuid);
1239        self.purge_ava(Attribute::RecycledDirectMemberOf);
1240
1241        // Change state repl doesn't need this flag
1242        // self.valid.ecstate.revive(&self.valid.cid);
1243
1244        Entry {
1245            valid: self.valid,
1246            state: self.state,
1247            attrs: self.attrs,
1248        }
1249    }
1250}
1251// Both invalid states can be reached from "entry -> invalidate"
1252
1253impl Entry<EntryInvalid, EntryNew> {
1254    /// This function steps back from EntryInvalid to EntryInit.
1255    /// This is a TEST ONLY method and will never be exposed in production.
1256    #[cfg(test)]
1257    pub fn into_init_new(self) -> Entry<EntryInit, EntryNew> {
1258        Entry {
1259            valid: EntryInit,
1260            state: EntryNew,
1261            attrs: self.attrs,
1262        }
1263    }
1264
1265    /// ⚠️  This function bypasses the schema validation and can panic if uuid is not found.
1266    /// The entry it creates can never be committed safely or replicated.
1267    /// This is a TEST ONLY method and will never be exposed in production.
1268    #[cfg(test)]
1269    pub fn into_valid_new(self) -> Entry<EntryValid, EntryNew> {
1270        let uuid = self.get_uuid().expect("Invalid uuid");
1271        Entry {
1272            valid: EntryValid {
1273                uuid,
1274                ecstate: self.valid.ecstate,
1275            },
1276            state: EntryNew,
1277            attrs: self.attrs,
1278        }
1279    }
1280
1281    /// ⚠️  This function bypasses the db commit, assigns fake db ids, and assigns an invalid uuid.
1282    /// The entry it creates can never be committed safely or replicated.
1283    /// This is a TEST ONLY method and will never be exposed in production.
1284    #[cfg(test)]
1285    pub fn into_sealed_committed(self) -> Entry<EntrySealed, EntryCommitted> {
1286        let uuid = self.get_uuid().unwrap_or_else(Uuid::new_v4);
1287        Entry {
1288            valid: EntrySealed {
1289                uuid,
1290                ecstate: self.valid.ecstate,
1291            },
1292            state: EntryCommitted { id: 0 },
1293            attrs: self.attrs,
1294        }
1295    }
1296
1297    /// ⚠️  This function bypasses the schema validation and assigns a fake uuid.
1298    /// The entry it creates can never be committed safely or replicated.
1299    /// This is a TEST ONLY method and will never be exposed in production.
1300    #[cfg(test)]
1301    pub fn into_valid_committed(self) -> Entry<EntryValid, EntryCommitted> {
1302        let uuid = self.get_uuid().unwrap_or_else(Uuid::new_v4);
1303        Entry {
1304            valid: EntryValid {
1305                uuid,
1306                ecstate: self.valid.ecstate,
1307            },
1308            state: EntryCommitted { id: 0 },
1309            attrs: self.attrs,
1310        }
1311    }
1312}
1313
1314impl Entry<EntryInvalid, EntryCommitted> {
1315    /// ⚠️  This function bypasses the schema validation and assigns a fake uuid.
1316    /// The entry it creates can never be committed safely or replicated.
1317    /// This is a TEST ONLY method and will never be exposed in production.
1318    #[cfg(test)]
1319    pub fn into_sealed_committed(self) -> Entry<EntrySealed, EntryCommitted> {
1320        let uuid = self.get_uuid().unwrap_or_else(Uuid::new_v4);
1321        Entry {
1322            valid: EntrySealed {
1323                uuid,
1324                ecstate: self.valid.ecstate,
1325            },
1326            state: self.state,
1327            attrs: self.attrs,
1328        }
1329    }
1330}
1331
1332impl Entry<EntrySealed, EntryNew> {
1333    /// ⚠️  This function bypasses schema validation and assigns an invalid uuid.
1334    /// The entry it creates can never be committed safely or replicated.
1335    /// This is a TEST ONLY method and will never be exposed in production.
1336    #[cfg(test)]
1337    pub fn into_sealed_committed(self) -> Entry<EntrySealed, EntryCommitted> {
1338        Entry {
1339            valid: self.valid,
1340            state: EntryCommitted { id: 0 },
1341            attrs: self.attrs,
1342        }
1343    }
1344
1345    /// Given this validated and sealed entry, process it with a `Backend` ID number so that it
1346    /// can be then serialised to the database.
1347    pub fn into_sealed_committed_id(self, id: u64) -> Entry<EntrySealed, EntryCommitted> {
1348        Entry {
1349            valid: self.valid,
1350            state: EntryCommitted { id },
1351            attrs: self.attrs,
1352        }
1353    }
1354
1355    pub fn compare(&self, rhs: &Entry<EntrySealed, EntryNew>) -> bool {
1356        compare_attrs(&self.attrs, &rhs.attrs)
1357    }
1358}
1359
1360type IdxDiff<'a> =
1361    Vec<Result<(&'a Attribute, IndexType, String), (&'a Attribute, IndexType, String)>>;
1362
1363impl<VALID> Entry<VALID, EntryCommitted> {
1364    /// If this entry has ever been committed to disk, retrieve its database id number.
1365    pub fn get_id(&self) -> u64 {
1366        self.state.id
1367    }
1368}
1369
1370impl<STATE> Entry<EntrySealed, STATE> {
1371    pub fn into_init(self) -> Entry<EntryInit, STATE> {
1372        Entry {
1373            valid: EntryInit,
1374            state: self.state,
1375            attrs: self.attrs,
1376        }
1377    }
1378}
1379
1380impl Entry<EntrySealed, EntryCommitted> {
1381    #[cfg(test)]
1382    pub(crate) fn get_last_changed(&self) -> Cid {
1383        self.valid.ecstate.get_max_cid().clone()
1384    }
1385
1386    /// State transititon to allow self to self for certain test macros.
1387    #[cfg(test)]
1388    pub fn into_sealed_committed(self) -> Entry<EntrySealed, EntryCommitted> {
1389        // NO-OP to satisfy macros.
1390        self
1391    }
1392
1393    pub(crate) fn stub_sealed_committed_id(
1394        id: u64,
1395        ctx_ent: &EntryIncrementalNew,
1396    ) -> EntrySealedCommitted {
1397        let uuid = ctx_ent.get_uuid();
1398        let ecstate = ctx_ent.stub_ecstate();
1399
1400        Entry {
1401            valid: EntrySealed { uuid, ecstate },
1402            state: EntryCommitted { id },
1403            attrs: Default::default(),
1404        }
1405    }
1406
1407    /// Insert a claim to this entry. This claim can NOT be persisted to disk, this is only
1408    /// used during a single Event session.
1409    pub fn insert_claim(&mut self, value: &str) {
1410        self.add_ava_int(Attribute::Claim, Value::new_iutf8(value));
1411    }
1412
1413    pub fn compare(&self, rhs: &Entry<EntrySealed, EntryCommitted>) -> bool {
1414        compare_attrs(&self.attrs, &rhs.attrs)
1415    }
1416
1417    /// Serialise this entry to its Database format ready for storage.
1418    pub fn to_dbentry(&self) -> DbEntry {
1419        // In the future this will do extra work to process uuid
1420        // into "attributes" suitable for dbentry storage.
1421        DbEntry {
1422            ent: DbEntryVers::V3 {
1423                changestate: self.valid.ecstate.to_db_changestate(),
1424                attrs: self
1425                    .attrs
1426                    .iter()
1427                    .map(|(k, vs)| {
1428                        let dbvs: DbValueSetV2 = vs.to_db_valueset_v2();
1429                        (k.clone(), dbvs)
1430                    })
1431                    .collect(),
1432            },
1433        }
1434    }
1435
1436    #[inline]
1437    /// Given this entry, extract the set of strings that can uniquely identify this for authentication
1438    /// purposes. These strings are then indexed.
1439    fn get_name2uuid_cands(&self) -> BTreeSet<String> {
1440        // The cands are:
1441        // * spn
1442        // * name
1443        // * gidnumber
1444
1445        let cands = [Attribute::Spn, Attribute::Name, Attribute::GidNumber];
1446        cands
1447            .iter()
1448            .filter_map(|cand| {
1449                self.attrs
1450                    .get(cand)
1451                    .map(|vs| vs.to_proto_string_clone_iter())
1452            })
1453            .flatten()
1454            .collect()
1455    }
1456
1457    #[inline]
1458    /// Given this entry, extract the set of strings that can externally identify this
1459    /// entry for sync purposes. These strings are then indexed.
1460    fn get_externalid2uuid(&self) -> Option<String> {
1461        self.attrs
1462            .get(&Attribute::SyncExternalId)
1463            .and_then(|vs| vs.to_proto_string_single())
1464    }
1465
1466    #[inline]
1467    /// Given this entry, extract its primary security principal name, or if not present
1468    /// extract its name, and if that's not present, extract its uuid.
1469    pub(crate) fn get_uuid2spn(&self) -> Value {
1470        self.attrs
1471            .get(&Attribute::Spn)
1472            .and_then(|vs| vs.to_value_single())
1473            .or_else(|| {
1474                self.attrs
1475                    .get(&Attribute::Name)
1476                    .and_then(|vs| vs.to_value_single())
1477            })
1478            .unwrap_or_else(|| Value::Uuid(self.get_uuid()))
1479    }
1480
1481    #[inline]
1482    /// Given this entry, determine its relative distinguished named for LDAP compatibility.
1483    ///
1484    /// See also - `get_display_id`
1485    pub(crate) fn get_uuid2rdn(&self) -> String {
1486        self.attrs
1487            .get(&Attribute::Spn)
1488            .and_then(|vs| vs.to_proto_string_single().map(|v| format!("spn={v}")))
1489            .or_else(|| {
1490                self.attrs
1491                    .get(&Attribute::Name)
1492                    .and_then(|vs| vs.to_proto_string_single().map(|v| format!("name={v}")))
1493            })
1494            .unwrap_or_else(|| format!("uuid={}", self.get_uuid().as_hyphenated()))
1495    }
1496
1497    /// Generate the required values for a name2uuid index. IE this is
1498    /// ALL possible names this entry COULD be known uniquely by!
1499    pub(crate) fn idx_name2uuid_diff(
1500        pre: Option<&Self>,
1501        post: Option<&Self>,
1502    ) -> (
1503        // Add
1504        Option<BTreeSet<String>>,
1505        // Remove
1506        Option<BTreeSet<String>>,
1507    ) {
1508        // needs to return gid for posix conversion
1509        match (pre, post) {
1510            (None, None) => {
1511                // No action required
1512                (None, None)
1513            }
1514            (None, Some(b)) => {
1515                // We are adding this entry (or restoring it),
1516                // so we need to add the values.
1517                (Some(b.get_name2uuid_cands()), None)
1518            }
1519            (Some(a), None) => {
1520                // Removing the entry, remove all values.
1521                (None, Some(a.get_name2uuid_cands()))
1522            }
1523            (Some(a), Some(b)) => {
1524                let pre_set = a.get_name2uuid_cands();
1525                let post_set = b.get_name2uuid_cands();
1526
1527                // what is in post, but not pre (added)
1528                let add_set: BTreeSet<_> = post_set.difference(&pre_set).cloned().collect();
1529                // what is in pre, but not post (removed)
1530                let rem_set: BTreeSet<_> = pre_set.difference(&post_set).cloned().collect();
1531                (Some(add_set), Some(rem_set))
1532            }
1533        }
1534    }
1535
1536    /// Generate the required values for externalid2uuid.
1537    pub(crate) fn idx_externalid2uuid_diff(
1538        pre: Option<&Self>,
1539        post: Option<&Self>,
1540    ) -> (Option<String>, Option<String>) {
1541        match (pre, post) {
1542            (None, None) => {
1543                // no action
1544                (None, None)
1545            }
1546            (None, Some(b)) => {
1547                // add
1548                (b.get_externalid2uuid(), None)
1549            }
1550            (Some(a), None) => {
1551                // remove
1552                (None, a.get_externalid2uuid())
1553            }
1554            (Some(a), Some(b)) => {
1555                let ia = a.get_externalid2uuid();
1556                let ib = b.get_externalid2uuid();
1557                if ia != ib {
1558                    // Note, we swap these since ib is the new post state
1559                    // we want to add, and ia is what we remove.
1560                    (ib, ia)
1561                } else {
1562                    // no action
1563                    (None, None)
1564                }
1565            }
1566        }
1567    }
1568
1569    /// Generate a differential between a previous and current entry state, and what changes this
1570    /// means for the current set of spn's for this uuid.
1571    pub(crate) fn idx_uuid2spn_diff(
1572        pre: Option<&Self>,
1573        post: Option<&Self>,
1574    ) -> Option<Result<Value, ()>> {
1575        match (pre, post) {
1576            (None, None) => {
1577                // no action
1578                None
1579            }
1580            (None, Some(b)) => {
1581                // add
1582                Some(Ok(b.get_uuid2spn()))
1583            }
1584            (Some(_a), None) => {
1585                // remove
1586                Some(Err(()))
1587            }
1588            (Some(a), Some(b)) => {
1589                let ia = a.get_uuid2spn();
1590                let ib = b.get_uuid2spn();
1591                if ia != ib {
1592                    // Add (acts as replace)
1593                    Some(Ok(ib))
1594                } else {
1595                    // no action
1596                    None
1597                }
1598            }
1599        }
1600    }
1601
1602    /// Generate a differential between a previous and current entry state, and what changes this
1603    /// means for the current set of LDAP relative distinguished names.
1604    pub(crate) fn idx_uuid2rdn_diff(
1605        pre: Option<&Self>,
1606        post: Option<&Self>,
1607    ) -> Option<Result<String, ()>> {
1608        match (pre, post) {
1609            (None, None) => {
1610                // no action
1611                None
1612            }
1613            (None, Some(b)) => {
1614                // add
1615                Some(Ok(b.get_uuid2rdn()))
1616            }
1617            (Some(_a), None) => {
1618                // remove
1619                Some(Err(()))
1620            }
1621            (Some(a), Some(b)) => {
1622                let ia = a.get_uuid2rdn();
1623                let ib = b.get_uuid2rdn();
1624                if ia != ib {
1625                    // Add (acts as replace)
1626                    Some(Ok(ib))
1627                } else {
1628                    // no action
1629                    None
1630                }
1631            }
1632        }
1633    }
1634
1635    /// Given the previous and current state of this entry, determine the indexing differential
1636    /// that needs to be applied. i.e. what indexes must be created, modified and removed.
1637    pub(crate) fn idx_diff<'a>(
1638        idxmeta: &'a HashMap<IdxKey, IdxSlope>,
1639        pre: Option<&Self>,
1640        post: Option<&Self>,
1641    ) -> IdxDiff<'a> {
1642        // We yield a list of Result, where Ok() means "add",
1643        // and Err() means "remove".
1644        // the value inside the result, is a tuple of attr, itype, idx_key
1645
1646        match (pre, post) {
1647            (None, None) => {
1648                // if both are none, yield empty list.
1649                Vec::with_capacity(0)
1650            }
1651            (Some(pre_e), None) => {
1652                // If we are none (?), yield our pre-state as removals.
1653                idxmeta
1654                    .keys()
1655                    .flat_map(|ikey| {
1656                        match pre_e.get_ava_set(&ikey.attr) {
1657                            None => Vec::with_capacity(0),
1658                            Some(vs) => {
1659                                let changes: Vec<Result<_, _>> = match ikey.itype {
1660                                    IndexType::Equality => {
1661                                        // We generate these keys out of the valueset now.
1662                                        vs.generate_idx_eq_keys()
1663                                            .into_iter()
1664                                            .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1665                                            .collect()
1666                                    }
1667                                    IndexType::Presence => {
1668                                        vec![Err((&ikey.attr, ikey.itype, "_".to_string()))]
1669                                    }
1670                                    IndexType::SubString => vs
1671                                        .generate_idx_sub_keys()
1672                                        .into_iter()
1673                                        .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1674                                        .collect(),
1675                                    IndexType::Ordering => vs
1676                                        .generate_idx_ord_keys()
1677                                        .into_iter()
1678                                        .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1679                                        .collect(),
1680                                };
1681                                changes
1682                            }
1683                        }
1684                    })
1685                    .collect()
1686            }
1687            (None, Some(post_e)) => {
1688                // If the pre-state is none, yield our additions.
1689                idxmeta
1690                    .keys()
1691                    .flat_map(|ikey| {
1692                        match post_e.get_ava_set(&ikey.attr) {
1693                            None => Vec::with_capacity(0),
1694                            Some(vs) => {
1695                                let changes: Vec<Result<_, _>> = match ikey.itype {
1696                                    IndexType::Equality => vs
1697                                        .generate_idx_eq_keys()
1698                                        .into_iter()
1699                                        .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1700                                        .collect(),
1701                                    IndexType::Presence => {
1702                                        vec![Ok((&ikey.attr, ikey.itype, "_".to_string()))]
1703                                    }
1704                                    IndexType::SubString => vs
1705                                        .generate_idx_sub_keys()
1706                                        .into_iter()
1707                                        .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1708                                        .collect(),
1709                                    IndexType::Ordering => vs
1710                                        .generate_idx_ord_keys()
1711                                        .into_iter()
1712                                        .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1713                                        .collect(),
1714                                };
1715                                // For each value
1716                                //
1717                                changes
1718                            }
1719                        }
1720                    })
1721                    .collect()
1722            }
1723            (Some(pre_e), Some(post_e)) => {
1724                assert_eq!(pre_e.state.id, post_e.state.id);
1725                idxmeta
1726                    .keys()
1727                    .flat_map(|ikey| {
1728                        match (
1729                            pre_e.get_ava_set(&ikey.attr),
1730                            post_e.get_ava_set(&ikey.attr),
1731                        ) {
1732                            (None, None) => {
1733                                // Neither have it, do nothing.
1734                                Vec::with_capacity(0)
1735                            }
1736                            (Some(pre_vs), None) => {
1737                                // It existed before, but not anymore
1738                                let changes: Vec<Result<_, _>> = match ikey.itype {
1739                                    IndexType::Equality => {
1740                                        // Turn each idx_key to the tuple of
1741                                        // changes.
1742                                        pre_vs
1743                                            .generate_idx_eq_keys()
1744                                            .into_iter()
1745                                            .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1746                                            .collect()
1747                                    }
1748                                    IndexType::Presence => {
1749                                        vec![Err((&ikey.attr, ikey.itype, "_".to_string()))]
1750                                    }
1751                                    IndexType::SubString => pre_vs
1752                                        .generate_idx_sub_keys()
1753                                        .into_iter()
1754                                        .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1755                                        .collect(),
1756                                    IndexType::Ordering => pre_vs
1757                                        .generate_idx_ord_keys()
1758                                        .into_iter()
1759                                        .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1760                                        .collect(),
1761                                };
1762                                changes
1763                            }
1764                            (None, Some(post_vs)) => {
1765                                // It was added now.
1766                                let changes: Vec<Result<_, _>> = match ikey.itype {
1767                                    IndexType::Equality => {
1768                                        // Turn each idx_key to the tuple of
1769                                        // changes.
1770                                        post_vs
1771                                            .generate_idx_eq_keys()
1772                                            .into_iter()
1773                                            .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1774                                            .collect()
1775                                    }
1776                                    IndexType::Presence => {
1777                                        vec![Ok((&ikey.attr, ikey.itype, "_".to_string()))]
1778                                    }
1779                                    IndexType::SubString => post_vs
1780                                        .generate_idx_sub_keys()
1781                                        .into_iter()
1782                                        .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1783                                        .collect(),
1784                                    IndexType::Ordering => post_vs
1785                                        .generate_idx_ord_keys()
1786                                        .into_iter()
1787                                        .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1788                                        .collect(),
1789                                };
1790                                changes
1791                            }
1792                            (Some(pre_vs), Some(post_vs)) => {
1793                                // it exists in both, we need to work out the difference within the attr.
1794                                let (mut pre_idx_keys, mut post_idx_keys) = match ikey.itype {
1795                                    IndexType::Equality => (
1796                                        pre_vs.generate_idx_eq_keys(),
1797                                        post_vs.generate_idx_eq_keys(),
1798                                    ),
1799                                    IndexType::Presence => {
1800                                        // No action - we still are "present", so nothing to do!
1801                                        (Vec::with_capacity(0), Vec::with_capacity(0))
1802                                    }
1803                                    IndexType::SubString => (
1804                                        pre_vs.generate_idx_sub_keys(),
1805                                        post_vs.generate_idx_sub_keys(),
1806                                    ),
1807                                    IndexType::Ordering => (
1808                                        pre_vs.generate_idx_ord_keys(),
1809                                        post_vs.generate_idx_ord_keys(),
1810                                    ),
1811                                };
1812
1813                                let sz = if pre_idx_keys.len() > post_idx_keys.len() {
1814                                    pre_idx_keys.len()
1815                                } else {
1816                                    post_idx_keys.len()
1817                                };
1818
1819                                let mut added_vs = Vec::with_capacity(sz);
1820                                let mut removed_vs = Vec::with_capacity(sz);
1821
1822                                if sz > 0 {
1823                                    pre_idx_keys.sort_unstable();
1824                                    post_idx_keys.sort_unstable();
1825
1826                                    let mut pre_iter = pre_idx_keys.iter();
1827                                    let mut post_iter = post_idx_keys.iter();
1828
1829                                    let mut pre = pre_iter.next();
1830                                    let mut post = post_iter.next();
1831
1832                                    loop {
1833                                        match (pre, post) {
1834                                            (Some(a), Some(b)) => {
1835                                                match a.cmp(b) {
1836                                                    Ordering::Less => {
1837                                                        removed_vs.push(a.clone());
1838                                                        pre = pre_iter.next();
1839                                                    }
1840                                                    Ordering::Equal => {
1841                                                        // In both - no action needed.
1842                                                        pre = pre_iter.next();
1843                                                        post = post_iter.next();
1844                                                    }
1845                                                    Ordering::Greater => {
1846                                                        added_vs.push(b.clone());
1847                                                        post = post_iter.next();
1848                                                    }
1849                                                }
1850                                            }
1851                                            (Some(a), None) => {
1852                                                removed_vs.push(a.clone());
1853                                                pre = pre_iter.next();
1854                                            }
1855                                            (None, Some(b)) => {
1856                                                added_vs.push(b.clone());
1857                                                post = post_iter.next();
1858                                            }
1859                                            (None, None) => {
1860                                                break;
1861                                            }
1862                                        }
1863                                    }
1864                                } // end sz > 0
1865
1866                                let mut diff =
1867                                    Vec::with_capacity(removed_vs.len() + added_vs.len());
1868
1869                                match ikey.itype {
1870                                    IndexType::SubString
1871                                    | IndexType::Ordering
1872                                    | IndexType::Equality => {
1873                                        removed_vs
1874                                            .into_iter()
1875                                            .map(|idx_key| Err((&ikey.attr, ikey.itype, idx_key)))
1876                                            .for_each(|v| diff.push(v));
1877                                        added_vs
1878                                            .into_iter()
1879                                            .map(|idx_key| Ok((&ikey.attr, ikey.itype, idx_key)))
1880                                            .for_each(|v| diff.push(v));
1881                                    }
1882                                    IndexType::Presence => {
1883                                        // No action - we still are "present", so nothing to do!
1884                                    }
1885                                };
1886                                // Return the diff
1887                                diff
1888                            }
1889                        }
1890                    })
1891                    .collect()
1892                // End diff of the entries
1893            }
1894        }
1895    }
1896
1897    pub fn from_dbentry(db_e: DbEntry, id: u64) -> Option<Self> {
1898        // Convert attrs from db format to value
1899
1900        let (attrs, ecstate) = match db_e.ent {
1901            DbEntryVers::V3 { changestate, attrs } => {
1902                let ecstate = EntryChangeState::from_db_changestate(changestate);
1903
1904                let r_attrs = attrs
1905                    .into_iter()
1906                    // Skip anything empty as new VS can't deal with it.
1907                    .filter(|(_k, vs)| !vs.is_empty())
1908                    .map(|(k, dbvs)| {
1909                        valueset::from_db_valueset_v2(dbvs)
1910                            .map(|vs: ValueSet| (k, vs))
1911                            .map_err(|e| {
1912                                error!(?e, "from_dbentry failed");
1913                            })
1914                    })
1915                    .collect::<Result<Eattrs, ()>>()
1916                    .ok()?;
1917
1918                (r_attrs, ecstate)
1919            }
1920        };
1921
1922        let uuid = attrs
1923            .get(&Attribute::Uuid)
1924            .and_then(|vs| vs.to_uuid_single())?;
1925
1926        Some(Entry {
1927            valid: EntrySealed { uuid, ecstate },
1928            state: EntryCommitted { id },
1929            attrs,
1930        })
1931    }
1932
1933    /// ⚠️  This function bypasses the access control validation logic and should NOT
1934    /// be used without special care and attention to ensure that no private data
1935    /// is leaked incorrectly to clients. Generally this is ONLY used inside of
1936    /// the access control processing functions which correctly applies the reduction
1937    /// steps.
1938    ///
1939    /// This is a TEST ONLY method and will never be exposed in production.
1940    #[cfg(test)]
1941    pub(crate) fn into_reduced(self) -> Entry<EntryReduced, EntryCommitted> {
1942        Entry {
1943            valid: EntryReduced {
1944                uuid: self.valid.uuid,
1945                effective_access: None,
1946            },
1947            state: self.state,
1948            attrs: self.attrs,
1949        }
1950    }
1951
1952    /// Given a set of attributes that are allowed to be seen on this entry, process and remove
1953    /// all other values that are NOT allowed in this query.
1954    pub fn reduce_attributes(
1955        &self,
1956        allowed_attrs: &BTreeSet<Attribute>,
1957        effective_access: Option<Box<AccessEffectivePermission>>,
1958    ) -> Entry<EntryReduced, EntryCommitted> {
1959        // Remove all attrs from our tree that are NOT in the allowed set.
1960        let f_attrs: Map<_, _> = self
1961            .attrs
1962            .iter()
1963            .filter_map(|(k, v)| {
1964                if allowed_attrs.contains(k) {
1965                    Some((k.clone(), v.clone()))
1966                } else {
1967                    None
1968                }
1969            })
1970            .collect();
1971
1972        let valid = EntryReduced {
1973            uuid: self.valid.uuid,
1974            effective_access,
1975        };
1976        let state = self.state.clone();
1977
1978        Entry {
1979            valid,
1980            state,
1981            attrs: f_attrs,
1982        }
1983    }
1984
1985    /// Convert this recycled entry, into a tombstone ready for reaping.
1986    pub fn to_tombstone(&self, cid: Cid) -> Entry<EntryInvalid, EntryCommitted> {
1987        let mut ecstate = self.valid.ecstate.clone();
1988        // Duplicate this to a tombstone entry
1989        let mut attrs_new: Eattrs = Map::new();
1990
1991        let class_ava = vs_iutf8n![EntryClass::Object.into(), EntryClass::Tombstone.into()];
1992        let last_mod_ava = vs_cid![cid.clone()];
1993        let created_ava = vs_cid![cid.clone()];
1994
1995        attrs_new.insert(Attribute::Uuid, vs_uuid![self.get_uuid()]);
1996        attrs_new.insert(Attribute::Class, class_ava);
1997        attrs_new.insert(Attribute::LastModifiedCid, last_mod_ava);
1998        attrs_new.insert(Attribute::CreatedAtCid, created_ava);
1999
2000        // ⚠️  No return from this point!
2001        ecstate.tombstone(&cid);
2002
2003        Entry {
2004            valid: EntryInvalid { cid, ecstate },
2005            state: self.state.clone(),
2006            attrs: attrs_new,
2007        }
2008    }
2009
2010    /// Given a current transaction change identifier, mark this entry as valid and committed.
2011    pub fn into_valid(self, ecstate: EntryChangeState) -> Entry<EntryValid, EntryCommitted> {
2012        Entry {
2013            valid: EntryValid {
2014                uuid: self.valid.uuid,
2015                ecstate,
2016            },
2017            state: self.state,
2018            attrs: self.attrs,
2019        }
2020    }
2021
2022    pub fn verify(
2023        &self,
2024        schema: &dyn SchemaTransaction,
2025        results: &mut Vec<Result<(), ConsistencyError>>,
2026    ) {
2027        self.valid
2028            .ecstate
2029            .verify(schema, &self.attrs, self.state.id, results);
2030    }
2031}
2032
2033impl<STATE> Entry<EntryValid, STATE> {
2034    fn validate(&self, schema: &dyn SchemaTransaction) -> Result<(), SchemaError> {
2035        let schema_classes = schema.get_classes();
2036        let schema_attributes = schema.get_attributes();
2037
2038        // Now validate it!
2039        trace!(?self.attrs, "Entry::validate -> target");
2040
2041        // First, check we have class on the object ....
2042        if !self.attribute_pres(Attribute::Class) {
2043            // lrequest_error!("Missing attribute class");
2044            return Err(SchemaError::NoClassFound);
2045        }
2046
2047        if self.attribute_equality(Attribute::Class, &EntryClass::Conflict.into()) {
2048            // Conflict entries are exempt from schema enforcement. Return true.
2049            trace!("Skipping schema validation on conflict entry");
2050            return Ok(());
2051        };
2052
2053        // Are we in the recycle bin? We soften some checks if we are.
2054        let recycled = self.attribute_equality(Attribute::Class, &EntryClass::Recycled.into());
2055
2056        // Do we have extensible? We still validate syntax of attrs but don't
2057        // check for valid object structures.
2058        let extensible =
2059            self.attribute_equality(Attribute::Class, &EntryClass::ExtensibleObject.into());
2060
2061        let entry_classes = self.get_ava_set(Attribute::Class).ok_or_else(|| {
2062            admin_debug!("Attribute '{}' missing from entry", Attribute::Class);
2063            SchemaError::NoClassFound
2064        })?;
2065        let mut invalid_classes = Vec::with_capacity(0);
2066
2067        let mut classes: Vec<&SchemaClass> = Vec::with_capacity(entry_classes.len());
2068
2069        // We need to keep the btreeset of entry classes here so we can check the
2070        // requires and excludes.
2071        let entry_classes = if let Some(ec) = entry_classes.as_iutf8_set() {
2072            ec.iter()
2073                .for_each(|s| match schema_classes.get(s.as_str()) {
2074                    Some(x) => classes.push(x),
2075                    None => {
2076                        admin_debug!("invalid class: {:?}", s);
2077                        invalid_classes.push(s.to_string())
2078                    }
2079                });
2080            ec
2081        } else {
2082            admin_debug!("corrupt class attribute");
2083            return Err(SchemaError::NoClassFound);
2084        };
2085
2086        if !invalid_classes.is_empty() {
2087            return Err(SchemaError::InvalidClass(invalid_classes));
2088        };
2089
2090        // Now determine the set of excludes and requires we have, and then
2091        // assert we don't violate them.
2092
2093        let supplements_classes: Vec<_> = classes
2094            .iter()
2095            .flat_map(|cls| cls.systemsupplements.iter().chain(cls.supplements.iter()))
2096            .collect();
2097
2098        // So long as one supplement is present we can continue.
2099        let valid_supplements = if supplements_classes.is_empty() {
2100            // No need to check.
2101            true
2102        } else {
2103            supplements_classes
2104                .iter()
2105                .any(|class| entry_classes.contains(class.as_str()))
2106        };
2107
2108        if !valid_supplements {
2109            warn!(
2110                "Validation error, the following possible supplement classes are missing - {:?}",
2111                supplements_classes
2112            );
2113            let supplements_classes = supplements_classes.iter().map(|s| s.to_string()).collect();
2114            return Err(SchemaError::SupplementsNotSatisfied(supplements_classes));
2115        }
2116
2117        let excludes_classes: Vec<_> = classes
2118            .iter()
2119            .flat_map(|cls| cls.systemexcludes.iter().chain(cls.excludes.iter()))
2120            .collect();
2121
2122        let mut invalid_excludes = Vec::with_capacity(0);
2123
2124        excludes_classes.iter().for_each(|class| {
2125            if entry_classes.contains(class.as_str()) {
2126                invalid_excludes.push(class.to_string())
2127            }
2128        });
2129
2130        if !invalid_excludes.is_empty() {
2131            admin_warn!(
2132                "Validation error, the following excluded classes are present - {:?}",
2133                invalid_excludes
2134            );
2135            return Err(SchemaError::ExcludesNotSatisfied(invalid_excludes));
2136        }
2137
2138        // What this is really doing is taking a set of classes, and building an
2139        // "overall" class that describes this exact object for checking. IE we
2140        // build a super must/may set from the small class must/may sets.
2141
2142        //   for each class
2143        //      add systemmust/must and systemmay/may to their lists
2144        //      add anything from must also into may
2145
2146        // Now from the set of valid classes make a list of must/may
2147        //
2148        // NOTE: We still need this on extensible, because we still need to satisfy
2149        // our other must conditions as well!
2150        let must: Result<Vec<&SchemaAttribute>, _> = classes
2151            .iter()
2152            // Join our class systemmmust + must into one iter
2153            .flat_map(|cls| cls.systemmust.iter().chain(cls.must.iter()))
2154            .map(|s| {
2155                // This should NOT fail - if it does, it means our schema is
2156                // in an invalid state!
2157                schema_attributes.get(s).ok_or(SchemaError::Corrupted)
2158            })
2159            .collect();
2160
2161        let must = must?;
2162
2163        // Check that all must are inplace
2164        //   for each attr in must, check it's present on our ent
2165        let mut missing_must = Vec::with_capacity(0);
2166        for attr in must.iter() {
2167            let avas = self.get_ava_set(&attr.name);
2168            if avas.is_none() {
2169                missing_must.push(attr.name.clone());
2170            }
2171        }
2172
2173        if !missing_must.is_empty() {
2174            admin_warn!(
2175                "Validation error, the following required ({}) (must) attributes are missing - {:?}",
2176                self.get_display_id(), missing_must
2177            );
2178            // We if are in the recycle bin, we don't hard error here. This can occur when
2179            // a migration occurs and we delete an acp, and then the related group. Because
2180            // this would trigger refint which purges the acp_receiver_group, then this
2181            // must value becomes unsatisfiable. So here we soften the check for recycled
2182            // entries because they are in a "nebulous" state anyway.
2183            if !recycled {
2184                return Err(SchemaError::MissingMustAttribute(missing_must));
2185            }
2186        }
2187
2188        if extensible {
2189            self.attrs.iter().try_for_each(|(attr_name, avas)| {
2190                    match schema_attributes.get(attr_name) {
2191                        Some(a_schema) => {
2192                            // Now, for each type we do a *full* check of the syntax
2193                            // and validity of the ava.
2194                            if a_schema.phantom {
2195                                admin_warn!(
2196                                    "Rejecting attempt to add phantom attribute to extensible object: {}",
2197                                    attr_name
2198                                );
2199                                Err(SchemaError::PhantomAttribute(attr_name.to_string()))
2200                            } else {
2201                                a_schema.validate_ava(attr_name, avas)
2202                                // .map_err(|e| lrequest_error!("Failed to validate: {}", attr_name);)
2203                            }
2204                        }
2205                        None => {
2206                            admin_error!(
2207                                "Invalid Attribute {}, undefined in schema_attributes",
2208                                attr_name.to_string()
2209                            );
2210                            Err(SchemaError::InvalidAttribute(
2211                                attr_name.to_string()
2212                            ))
2213                        }
2214                    }
2215                })?;
2216        } else {
2217            // Note - we do NOT need to check phantom attributes here because they are
2218            // not allowed to exist in the class, which means a phantom attribute can't
2219            // be in the may/must set, and would FAIL our normal checks anyway.
2220
2221            // The set of "may" is a combination of may and must, since we have already
2222            // asserted that all must requirements are fulfilled. This allows us to
2223            // perform extended attribute checking in a single pass.
2224            let may: Result<Map<&Attribute, &SchemaAttribute>, _> = classes
2225                .iter()
2226                // Join our class systemmmust + must + systemmay + may into one.
2227                .flat_map(|cls| {
2228                    trace!(?cls);
2229                    cls.systemmust
2230                        .iter()
2231                        .chain(cls.must.iter())
2232                        .chain(cls.systemmay.iter())
2233                        .chain(cls.may.iter())
2234                })
2235                .map(|s| {
2236                    // This should NOT fail - if it does, it means our schema is
2237                    // in an invalid state!
2238                    Ok((s, schema_attributes.get(s).ok_or(SchemaError::Corrupted)?))
2239                })
2240                .collect();
2241
2242            let may = may?;
2243
2244            // TODO #70: Error needs to say what is missing
2245            // We need to return *all* missing attributes, not just the first error
2246            // we find. This will probably take a rewrite of the function definition
2247            // to return a result<_, vec<schemaerror>> and for the schema errors to take
2248            // information about what is invalid. It's pretty nontrivial.
2249
2250            // Check that any other attributes are in may
2251            //   for each attr on the object, check it's in the may+must set
2252            self.attrs.iter().try_for_each(|(attr_name, avas)| {
2253                    match may.get(attr_name) {
2254                        Some(a_schema) => {
2255                            // Now, for each type we do a *full* check of the syntax
2256                            // and validity of the ava.
2257                            a_schema.validate_ava(attr_name, avas)
2258                            // .map_err(|e| lrequest_error!("Failed to validate: {}", attr_name);
2259                        }
2260                        None => {
2261                            admin_error!(
2262                                "{} {} - not found in the list of valid attributes for this set of classes {:?} - valid attributes are {:?}",
2263
2264                                attr_name.as_str(),
2265                                self.get_display_id(),
2266                                entry_classes.iter().collect::<Vec<_>>(),
2267                                may.keys().collect::<Vec<_>>()
2268                            );
2269                            Err(SchemaError::AttributeNotValidForClass(
2270                                attr_name.to_string()
2271                            ))
2272                        }
2273                    }
2274                })?;
2275        }
2276
2277        // Well, we got here, so okay!
2278        Ok(())
2279    }
2280
2281    pub fn seal(mut self, schema: &dyn SchemaTransaction) -> Entry<EntrySealed, STATE> {
2282        let EntryValid { uuid, mut ecstate } = self.valid;
2283
2284        // Remove anything from the ecstate that is not a replicated attribute in the schema.
2285        // This is to allow ecstate equality to work, but also to just prevent ruv updates and
2286        // replicating things that only touched or changed phantom attrs.
2287        ecstate.retain(|k, _| schema.is_replicated(k));
2288
2289        // Update the last changed time.
2290        let last_mod_cid = ecstate.get_max_cid();
2291        let cv = vs_cid![last_mod_cid.clone()];
2292        let _ = self.attrs.insert(Attribute::LastModifiedCid, cv);
2293
2294        // Update created-at time. This is needed for migrations currently. It could
2295        // be alternately in the entry create path, but it makes more sense here as
2296        // we get the create_at time from the replication metadata
2297        let create_at_cid = ecstate.at();
2298        let cv = vs_cid![create_at_cid.clone()];
2299        let _ = self.attrs.insert(Attribute::CreatedAtCid, cv);
2300
2301        Entry {
2302            valid: EntrySealed { uuid, ecstate },
2303            state: self.state,
2304            attrs: self.attrs,
2305        }
2306    }
2307
2308    pub fn get_uuid(&self) -> Uuid {
2309        self.valid.uuid
2310    }
2311}
2312
2313impl<STATE> GetUuid for Entry<EntrySealed, STATE>
2314where
2315    STATE: Clone,
2316{
2317    fn get_uuid(&self) -> Uuid {
2318        self.valid.uuid
2319    }
2320}
2321
2322impl<STATE> Entry<EntrySealed, STATE>
2323where
2324    STATE: Clone,
2325{
2326    pub fn invalidate(mut self, cid: Cid, trim_cid: &Cid) -> Entry<EntryInvalid, STATE> {
2327        // Trim attributes that require it. For most this is a no-op.
2328        for vs in self.attrs.values_mut() {
2329            vs.trim(trim_cid);
2330        }
2331
2332        // During migration to the new modified/created cid system, we need to account
2333        // for entries that don't have this yet. Normally we would apply this in seal()
2334        // to the current CID. At this point we enter in the expected value from the
2335        // entry. Note, we don't set last mod to cid yet, we leave that to seal() so that
2336        // if this entry is excluded later in the change, we haven't tainted anything, or
2337        // so that if the change only applies to non-replicated attrs we haven't mucked
2338        // up the value.
2339        let last_mod_cid = self.valid.ecstate.get_max_cid();
2340        let cv = vs_cid![last_mod_cid.clone()];
2341        let _ = self.attrs.insert(Attribute::LastModifiedCid, cv);
2342
2343        let create_at_cid = self.valid.ecstate.at();
2344        let cv = vs_cid![create_at_cid.clone()];
2345        let _ = self.attrs.insert(Attribute::CreatedAtCid, cv);
2346
2347        Entry {
2348            valid: EntryInvalid {
2349                cid,
2350                ecstate: self.valid.ecstate,
2351            },
2352            state: self.state,
2353            attrs: self.attrs,
2354        }
2355    }
2356
2357    pub fn get_uuid(&self) -> Uuid {
2358        self.valid.uuid
2359    }
2360
2361    pub fn get_changestate(&self) -> &EntryChangeState {
2362        &self.valid.ecstate
2363    }
2364
2365    /// Determine if any attribute of this entry changed excluding the attribute named.
2366    /// This allows for detection of entry changes unless the change was to a specific
2367    /// attribute.
2368    pub(crate) fn entry_changed_excluding_attribute<A: AsRef<Attribute>>(
2369        &self,
2370        attr: A,
2371        cid: &Cid,
2372    ) -> bool {
2373        let attr_ref = attr.as_ref();
2374
2375        use crate::repl::entry::State;
2376
2377        match self.get_changestate().current() {
2378            State::Live { at: _, changes } => {
2379                changes.iter().any(|(change_attr, change_id)| {
2380                    change_id >= cid &&
2381                    *change_attr != *attr_ref &&
2382                    // This always changes, and could throw off other detections.
2383                    *change_attr != Attribute::LastModifiedCid
2384                })
2385            }
2386            State::Tombstone { at } => at == cid,
2387        }
2388    }
2389
2390    /// ⚠️  - Invalidate an entry by resetting it's change state to time-zero. This entry
2391    /// can never be replicated after this.
2392    /// This is a TEST ONLY method and will never be exposed in production.
2393    #[cfg(test)]
2394    pub(crate) fn into_invalid(mut self) -> Entry<EntryInvalid, STATE> {
2395        let cid = Cid::new_zero();
2396        self.set_last_changed(cid.clone());
2397
2398        let ecstate = EntryChangeState::new_without_schema(&cid, &self.attrs);
2399
2400        Entry {
2401            valid: EntryInvalid { cid, ecstate },
2402            state: self.state,
2403            attrs: self.attrs,
2404        }
2405    }
2406}
2407
2408impl GetUuid for Entry<EntryReduced, EntryCommitted> {
2409    fn get_uuid(&self) -> Uuid {
2410        self.valid.uuid
2411    }
2412}
2413
2414impl Entry<EntryReduced, EntryCommitted> {
2415    pub fn get_uuid(&self) -> Uuid {
2416        self.valid.uuid
2417    }
2418
2419    /// Transform this reduced entry into a JSON protocol form that can be sent to clients.
2420    pub fn to_pe(&self, qs: &mut QueryServerReadTransaction) -> Result<ProtoEntry, OperationError> {
2421        // Turn values -> Strings.
2422        let attrs: Result<_, _> = self
2423            .attrs
2424            .iter()
2425            .map(|(k, vs)| qs.resolve_valueset(vs).map(|pvs| (k.to_string(), pvs)))
2426            .collect();
2427        Ok(ProtoEntry { attrs: attrs? })
2428    }
2429
2430    pub fn to_scim_kanidm<'a, TXN>(
2431        &self,
2432        read_txn: &mut TXN,
2433    ) -> Result<ScimEntryKanidm, OperationError>
2434    where
2435        TXN: QueryServerTransaction<'a>,
2436    {
2437        let result: Result<BTreeMap<Attribute, ScimValueKanidm>, OperationError> = self
2438            .attrs
2439            .iter()
2440            // We want to skip some attributes as they are already in the header.
2441            .filter(|(k, _vs)| **k != Attribute::Uuid)
2442            .filter_map(|(k, vs)| {
2443                let opt_resolve_status = vs.to_scim_value();
2444                let res_opt_scim_value = match opt_resolve_status {
2445                    None => Ok(None),
2446                    Some(ScimResolveStatus::Resolved(scim_value_kani)) => Ok(Some(scim_value_kani)),
2447                    Some(ScimResolveStatus::NeedsResolution(scim_value_interim)) => {
2448                        read_txn.resolve_scim_interim(scim_value_interim)
2449                    }
2450                };
2451                res_opt_scim_value
2452                    .transpose()
2453                    .map(|scim_res| scim_res.map(|scim_value| (k.clone(), scim_value)))
2454            })
2455            .collect();
2456
2457        let attrs = result?;
2458
2459        let ext_access_check = self.valid.effective_access.as_ref().map(|eff_acc| {
2460            let ident = eff_acc.ident;
2461            let delete = eff_acc.delete;
2462            let search = (&eff_acc.search).into();
2463            let modify_present = (&eff_acc.modify_pres).into();
2464            let modify_remove = (&eff_acc.modify_rem).into();
2465
2466            ScimEffectiveAccess {
2467                ident,
2468                delete,
2469                search,
2470                modify_present,
2471                modify_remove,
2472            }
2473        });
2474
2475        let id = self.get_uuid();
2476
2477        // Not sure how I want to handle this yet, I think we need some schema changes
2478        // to achieve this.
2479        let schemas = Vec::with_capacity(0);
2480
2481        Ok(ScimEntryKanidm {
2482            header: ScimEntryHeader {
2483                schemas,
2484                id,
2485                // TODO: Should be spn / name or uuid.
2486                external_id: None,
2487                // TODO - this one will be useful in future, but we need to change
2488                // entry to store some extra metadata.
2489                meta: None,
2490            },
2491            ext_access_check,
2492            attrs,
2493        })
2494    }
2495
2496    /// Transform this reduced entry into an LDAP form that can be sent to clients.
2497    pub fn to_ldap(
2498        &self,
2499        qs: &mut QueryServerReadTransaction,
2500        basedn: &str,
2501        // Did the client request all attributes?
2502        all_attrs: bool,
2503        // Did the ldap client request any sperific attribute names? If so,
2504        // we need to remap everything to match.
2505        l_attrs: &[String],
2506    ) -> Result<LdapSearchResultEntry, OperationError> {
2507        let rdn = qs.uuid_to_rdn(self.get_uuid())?;
2508
2509        let dn = format!("{rdn},{basedn}");
2510
2511        // Everything in our attrs set is "what was requested". So we can transform that now
2512        // so they are all in "ldap forms" which makes our next stage a bit easier.
2513
2514        // Stage 1 - transform our results to a map of kani attr -> ldap value.
2515        let attr_map: Result<Map<&str, Vec<Vec<u8>>>, _> = self
2516            .attrs
2517            .iter()
2518            .map(|(k, vs)| {
2519                qs.resolve_valueset_ldap(vs, basedn)
2520                    .map(|pvs| (k.as_str(), pvs))
2521            })
2522            .collect();
2523        let attr_map = attr_map?;
2524
2525        // Stage 2 - transform and get all our attr - names out that we need to return.
2526        //                  ldap a, kani a
2527        let attr_names: Vec<(&str, &str)> = if all_attrs {
2528            // Join the set of attr keys, and our requested attrs.
2529            self.attrs
2530                .keys()
2531                .map(|k| (k.as_str(), k.as_str()))
2532                .chain(
2533                    l_attrs
2534                        .iter()
2535                        .map(|k| (k.as_str(), ldap_vattr_map(k.as_str()).unwrap_or(k.as_str()))),
2536                )
2537                .collect()
2538        } else {
2539            // Just get the requested ones.
2540            l_attrs
2541                .iter()
2542                .map(|k| (k.as_str(), ldap_vattr_map(k.as_str()).unwrap_or(k.as_str())))
2543                .collect()
2544        };
2545
2546        // Doing this to avoid duplicate attribute values per the LDAP spec
2547        let attributes: Vec<_> = attr_names
2548            .into_iter()
2549            .filter_map(|(ldap_a, kani_a)| {
2550                // In some special cases, we may need to transform or rewrite the values.
2551                match ldap_a {
2552                    LDAP_ATTR_DN => Some(LdapPartialAttribute {
2553                        atype: LDAP_ATTR_DN.to_string(),
2554                        vals: vec![dn.as_bytes().to_vec()],
2555                    }),
2556                    LDAP_ATTR_ENTRYDN => Some(LdapPartialAttribute {
2557                        atype: LDAP_ATTR_ENTRYDN.to_string(),
2558                        vals: vec![dn.as_bytes().to_vec()],
2559                    }),
2560                    LDAP_ATTR_MAIL_PRIMARY | LDAP_ATTR_EMAIL_PRIMARY => {
2561                        attr_map.get(kani_a).map(|pvs| LdapPartialAttribute {
2562                            atype: ldap_a.to_string(),
2563                            vals: pvs
2564                                .first()
2565                                .map(|first| vec![first.clone()])
2566                                .unwrap_or_default(),
2567                        })
2568                    }
2569                    LDAP_ATTR_MAIL_ALTERNATIVE | LDAP_ATTR_EMAIL_ALTERNATIVE => {
2570                        attr_map.get(kani_a).map(|pvs| LdapPartialAttribute {
2571                            atype: ldap_a.to_string(),
2572                            vals: pvs
2573                                .split_first()
2574                                .map(|(_, rest)| rest.to_vec())
2575                                .unwrap_or_default(),
2576                        })
2577                    }
2578                    ATTR_HOME_DIRECTORY => Some(LdapPartialAttribute {
2579                        atype: ATTR_HOME_DIRECTORY.to_string(),
2580                        vals: vec![format!("/home/{}", self.get_uuid()).into_bytes()],
2581                    }),
2582                    _ => attr_map.get(kani_a).map(|pvs| LdapPartialAttribute {
2583                        atype: ldap_a.to_string(),
2584                        vals: pvs.clone(),
2585                    }),
2586                }
2587            })
2588            .collect();
2589
2590        Ok(LdapSearchResultEntry { dn, attributes })
2591    }
2592}
2593
2594impl<VALID, STATE> Entry<VALID, STATE> {
2595    /// This internally adds an AVA to the entry. If the entry was newly added, then true is returned.
2596    /// If the value already existed, or was unable to be added, false is returned. Alternately,
2597    /// you can think of this boolean as "if a write occurred to the structure", true indicating that
2598    /// a change occurred.
2599    fn add_ava_int(&mut self, attr: Attribute, value: Value) -> bool {
2600        if let Some(vs) = self.attrs.get_mut(&attr) {
2601            let r = vs.insert_checked(value);
2602            debug_assert!(r.is_ok());
2603            // Default to the value not being present if wrong typed.
2604            r.unwrap_or(false)
2605        } else {
2606            #[allow(clippy::expect_used)]
2607            let vs = valueset::from_value_iter(std::iter::once(value))
2608                .expect("Unable to fail - non-zero iter, and single value type!");
2609            self.attrs.insert(attr, vs);
2610            // The attribute did not exist before.
2611            true
2612        }
2613        // Doesn't matter if it already exists, equality will replace.
2614    }
2615
2616    fn set_ava_int(&mut self, attr: Attribute, vs: ValueSet) {
2617        if let Some(existing_vs) = self.attrs.get_mut(&attr) {
2618            // This is the suboptimal path. This can only exist in rare cases.
2619            let _ = existing_vs.merge(&vs);
2620        } else {
2621            // Normally this is what's taken.
2622            self.attrs.insert(attr, vs);
2623        }
2624    }
2625
2626    /// Overwrite the current set of values for an attribute, with this new set.
2627    fn set_ava_iter_int<T>(&mut self, attr: Attribute, iter: T)
2628    where
2629        T: IntoIterator<Item = Value>,
2630    {
2631        let Ok(vs) = valueset::from_value_iter(iter.into_iter()) else {
2632            trace!("set_ava_iter_int - empty from_value_iter, skipping");
2633            return;
2634        };
2635
2636        debug!(?attr, ?vs);
2637
2638        self.set_ava_int(attr, vs)
2639    }
2640
2641    /// Update the last_changed flag of this entry to the given change identifier.
2642    #[cfg(test)]
2643    fn set_last_changed(&mut self, cid: Cid) {
2644        let cv = vs_cid![cid.clone()];
2645        let _ = self.attrs.insert(Attribute::LastModifiedCid, cv);
2646        let cv = vs_cid![cid];
2647        let _ = self.attrs.insert(Attribute::CreatedAtCid, cv);
2648    }
2649
2650    pub(crate) fn get_display_id(&self) -> String {
2651        self.attrs
2652            .get(&Attribute::Spn)
2653            .map(|vs| vs.to_proto_string_clone_iter())
2654            .or_else(|| {
2655                self.attrs
2656                    .get(&Attribute::Name)
2657                    .map(|vs| vs.to_proto_string_clone_iter())
2658            })
2659            .or_else(|| {
2660                self.attrs
2661                    .get(&Attribute::Uuid)
2662                    .map(|vs| vs.to_proto_string_clone_iter())
2663            })
2664            // Take the first value
2665            .and_then(|mut string_iter| string_iter.next())
2666            .unwrap_or_else(|| "no entry id available".to_string())
2667    }
2668
2669    pub fn has_class(&self, class: &EntryClass) -> bool {
2670        self.get_ava_set(Attribute::Class)
2671            .and_then(|vs| vs.as_iutf8_set())
2672            .map(|set| {
2673                let class_name: &str = class.into();
2674                set.contains(class_name)
2675            })
2676            .unwrap_or_default()
2677    }
2678
2679    pub fn attr_keys(&self) -> impl Iterator<Item = &Attribute> {
2680        self.attrs.keys()
2681    }
2682
2683    /// Get an iterator over the current set of attribute names that this entry contains.
2684    pub fn get_ava_names(&self) -> impl Iterator<Item = &str> {
2685        // Get the set of all attribute names in the entry
2686        self.attrs.keys().map(|a| a.as_str())
2687    }
2688
2689    /// Get an iterator over the current set of values for an attribute name.
2690    pub fn get_ava(&self) -> &Eattrs {
2691        &self.attrs
2692    }
2693
2694    pub fn get_ava_iter(&self) -> impl Iterator<Item = (&Attribute, &ValueSet)> {
2695        self.attrs.iter()
2696    }
2697
2698    /// Return a reference to the current set of values that are associated to this attribute.
2699    pub fn get_ava_set<A: AsRef<Attribute>>(&self, attr: A) -> Option<&ValueSet> {
2700        self.attrs.get(attr.as_ref())
2701    }
2702
2703    pub fn get_ava_refer<A: AsRef<Attribute>>(&self, attr: A) -> Option<&BTreeSet<Uuid>> {
2704        self.get_ava_set(attr).and_then(|vs| vs.as_refer_set())
2705    }
2706
2707    pub fn get_ava_refer_single<A: AsRef<Attribute>>(&self, attr: A) -> Option<Uuid> {
2708        self.get_ava_set(attr).and_then(|vs| vs.to_refer_single())
2709    }
2710
2711    pub fn get_ava_as_iutf8_iter<A: AsRef<Attribute>>(
2712        &self,
2713        attr: A,
2714    ) -> Option<impl Iterator<Item = &str>> {
2715        self.get_ava_set(attr).and_then(|vs| vs.as_iutf8_iter())
2716    }
2717
2718    pub fn get_ava_as_iutf8<A: AsRef<Attribute>>(&self, attr: A) -> Option<&BTreeSet<String>> {
2719        self.get_ava_set(attr).and_then(|vs| vs.as_iutf8_set())
2720    }
2721
2722    pub fn get_ava_as_image<A: AsRef<Attribute>>(&self, attr: A) -> Option<&HashSet<ImageValue>> {
2723        self.get_ava_set(attr).and_then(|vs| vs.as_imageset())
2724    }
2725
2726    pub fn get_ava_single_image<A: AsRef<Attribute>>(&self, attr: A) -> Option<ImageValue> {
2727        let images = self.get_ava_set(attr).and_then(|vs| vs.as_imageset())?;
2728        images.iter().next().cloned()
2729    }
2730
2731    pub fn get_ava_single_credential_type<A: AsRef<Attribute>>(
2732        &self,
2733        attr: A,
2734    ) -> Option<CredentialType> {
2735        self.get_ava_set(attr)
2736            .and_then(|vs| vs.to_credentialtype_single())
2737    }
2738
2739    pub fn get_ava_as_oauthscopes<A: AsRef<Attribute>>(
2740        &self,
2741        attr: A,
2742    ) -> Option<impl Iterator<Item = &str>> {
2743        self.get_ava_set(attr)
2744            .and_then(|vs| vs.as_oauthscope_iter())
2745    }
2746
2747    pub fn get_ava_as_oauthscopemaps<A: AsRef<Attribute>>(
2748        &self,
2749        attr: A,
2750    ) -> Option<&std::collections::BTreeMap<Uuid, std::collections::BTreeSet<String>>> {
2751        self.get_ava_set(attr).and_then(|vs| vs.as_oauthscopemap())
2752    }
2753
2754    pub fn get_ava_as_intenttokens<A: AsRef<Attribute>>(
2755        &self,
2756        attr: A,
2757    ) -> Option<&std::collections::BTreeMap<String, IntentTokenState>> {
2758        self.get_ava_set(attr)
2759            .and_then(|vs| vs.as_intenttoken_map())
2760    }
2761
2762    pub fn get_ava_as_session_map<A: AsRef<Attribute>>(
2763        &self,
2764        attr: A,
2765    ) -> Option<&std::collections::BTreeMap<Uuid, Session>> {
2766        self.get_ava_set(attr).and_then(|vs| vs.as_session_map())
2767    }
2768
2769    pub fn get_ava_as_apitoken_map<A: AsRef<Attribute>>(
2770        &self,
2771        attr: A,
2772    ) -> Option<&std::collections::BTreeMap<Uuid, ApiToken>> {
2773        self.get_ava_set(attr).and_then(|vs| vs.as_apitoken_map())
2774    }
2775
2776    pub fn get_ava_as_oauth2session_map<A: AsRef<Attribute>>(
2777        &self,
2778        attr: A,
2779    ) -> Option<&std::collections::BTreeMap<Uuid, Oauth2Session>> {
2780        self.get_ava_set(attr)
2781            .and_then(|vs| vs.as_oauth2session_map())
2782    }
2783
2784    pub fn get_ava_as_s256_set<A: AsRef<Attribute>>(
2785        &self,
2786        attr: A,
2787    ) -> Option<&std::collections::BTreeSet<Sha256Output>> {
2788        self.get_ava_set(attr).and_then(|vs| vs.as_s256_set())
2789    }
2790
2791    /// If possible, return an iterator over the set of values transformed into a `&str`.
2792    pub fn get_ava_iter_iname<A: AsRef<Attribute>>(
2793        &self,
2794        attr: A,
2795    ) -> Option<impl Iterator<Item = &str>> {
2796        self.get_ava_set(attr).and_then(|vs| vs.as_iname_iter())
2797    }
2798
2799    /// If possible, return an iterator over the set of values transformed into a `&str`.
2800    pub fn get_ava_iter_iutf8<A: AsRef<Attribute>>(
2801        &self,
2802        attr: A,
2803    ) -> Option<impl Iterator<Item = &str>> {
2804        self.get_ava_set(attr).and_then(|vs| vs.as_iutf8_iter())
2805    }
2806
2807    /// If possible, return an iterator over the set of values transformed into a `Uuid`.
2808    pub fn get_ava_as_refuuid<A: AsRef<Attribute>>(
2809        &self,
2810        attr: A,
2811    ) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
2812        // If any value is NOT a reference, it's filtered out.
2813        self.get_ava_set(attr).and_then(|vs| vs.as_ref_uuid_iter())
2814    }
2815
2816    /// If possible, return an iterator over the set of ssh key values transformed into a `&str`.
2817    pub fn get_ava_iter_sshpubkeys<A: AsRef<Attribute>>(
2818        &self,
2819        attr: A,
2820    ) -> Option<impl Iterator<Item = String> + '_> {
2821        self.get_ava_set(attr)
2822            .and_then(|vs| vs.as_sshpubkey_string_iter())
2823    }
2824
2825    // These are special types to allow returning typed values from
2826    // an entry, if we "know" what we expect to receive.
2827
2828    /// Return a single value of this attributes name, or `None` if it is NOT present, or
2829    /// there are multiple values present (ambiguous).
2830    pub fn get_ava_single<A: AsRef<Attribute>>(&self, attr: A) -> Option<Value> {
2831        self.get_ava_set(attr).and_then(|vs| vs.to_value_single())
2832    }
2833
2834    pub fn get_ava_single_proto_string<A: AsRef<Attribute>>(&self, attr: A) -> Option<String> {
2835        self.get_ava_set(attr)
2836            .and_then(|vs| vs.to_proto_string_single())
2837    }
2838
2839    /// Return a single bool, if valid to transform this value into a boolean.
2840    pub fn get_ava_single_bool<A: AsRef<Attribute>>(&self, attr: A) -> Option<bool> {
2841        self.get_ava_set(attr).and_then(|vs| vs.to_bool_single())
2842    }
2843
2844    /// Return a single uint32, if valid to transform this value.
2845    pub fn get_ava_single_uint32<A: AsRef<Attribute>>(&self, attr: A) -> Option<u32> {
2846        self.get_ava_set(attr).and_then(|vs| vs.to_uint32_single())
2847    }
2848
2849    /// Return a single syntax type, if valid to transform this value.
2850    pub fn get_ava_single_syntax<A: AsRef<Attribute>>(&self, attr: A) -> Option<SyntaxType> {
2851        self.get_ava_set(attr)
2852            .and_then(|vs| vs.to_syntaxtype_single())
2853    }
2854
2855    /// Return a single credential, if valid to transform this value.
2856    pub fn get_ava_single_credential<A: AsRef<Attribute>>(&self, attr: A) -> Option<&Credential> {
2857        self.get_ava_set(attr)
2858            .and_then(|vs| vs.to_credential_single())
2859    }
2860
2861    /// Get the set of passkeys on this account, if any are present.
2862    pub fn get_ava_passkeys<A: AsRef<Attribute>>(
2863        &self,
2864        attr: A,
2865    ) -> Option<&BTreeMap<Uuid, (String, PasskeyV4)>> {
2866        self.get_ava_set(attr).and_then(|vs| vs.as_passkey_map())
2867    }
2868
2869    /// Get the set of devicekeys on this account, if any are present.
2870    pub fn get_ava_attestedpasskeys<A: AsRef<Attribute>>(
2871        &self,
2872        attr: A,
2873    ) -> Option<&BTreeMap<Uuid, (String, AttestedPasskeyV4)>> {
2874        self.get_ava_set(attr)
2875            .and_then(|vs| vs.as_attestedpasskey_map())
2876    }
2877
2878    /// Get the set of uihints on this account, if any are present.
2879    pub fn get_ava_uihint<A: AsRef<Attribute>>(&self, attr: A) -> Option<&BTreeSet<UiHint>> {
2880        self.get_ava_set(attr).and_then(|vs| vs.as_uihint_set())
2881    }
2882
2883    /// Return a single secret value, if valid to transform this value.
2884    pub fn get_ava_single_secret<A: AsRef<Attribute>>(&self, attr: A) -> Option<&str> {
2885        self.get_ava_set(attr).and_then(|vs| vs.to_secret_single())
2886    }
2887
2888    /// Return a single datetime, if valid to transform this value.
2889    pub fn get_ava_single_datetime<A: AsRef<Attribute>>(&self, attr: A) -> Option<OffsetDateTime> {
2890        self.get_ava_set(attr)
2891            .and_then(|vs| vs.to_datetime_single())
2892    }
2893
2894    /// Return a single `&str`, if valid to transform this value.
2895    pub(crate) fn get_ava_single_utf8<A: AsRef<Attribute>>(&self, attr: A) -> Option<&str> {
2896        self.get_ava_set(attr).and_then(|vs| vs.to_utf8_single())
2897    }
2898
2899    /// Return a single `&str`, if valid to transform this value.
2900    pub(crate) fn get_ava_single_iutf8<A: AsRef<Attribute>>(&self, attr: A) -> Option<&str> {
2901        self.get_ava_set(attr).and_then(|vs| vs.to_iutf8_single())
2902    }
2903
2904    /// Return a single `&str`, if valid to transform this value.
2905    pub(crate) fn get_ava_single_iname<A: AsRef<Attribute>>(&self, attr: A) -> Option<&str> {
2906        self.get_ava_set(attr).and_then(|vs| vs.to_iname_single())
2907    }
2908
2909    /// Return a single `&Url`, if valid to transform this value.
2910    pub fn get_ava_single_url<A: AsRef<Attribute>>(&self, attr: A) -> Option<&Url> {
2911        self.get_ava_set(attr).and_then(|vs| vs.to_url_single())
2912    }
2913
2914    pub fn get_ava_single_uuid<A: AsRef<Attribute>>(&self, attr: A) -> Option<Uuid> {
2915        self.get_ava_set(attr).and_then(|vs| vs.to_uuid_single())
2916    }
2917
2918    pub fn get_ava_single_refer<A: AsRef<Attribute>>(&self, attr: A) -> Option<Uuid> {
2919        self.get_ava_set(attr).and_then(|vs| vs.to_refer_single())
2920    }
2921
2922    pub fn get_ava_mail_primary<A: AsRef<Attribute>>(&self, attr: A) -> Option<&str> {
2923        self.get_ava_set(attr)
2924            .and_then(|vs| vs.to_email_address_primary_str())
2925    }
2926
2927    pub fn get_ava_iter_mail<A: AsRef<Attribute>>(
2928        &self,
2929        attr: A,
2930    ) -> Option<impl Iterator<Item = &str>> {
2931        self.get_ava_set(attr).and_then(|vs| vs.as_email_str_iter())
2932    }
2933
2934    /// Return a single protocol filter, if valid to transform this value.
2935    pub fn get_ava_single_protofilter<A: AsRef<Attribute>>(&self, attr: A) -> Option<&ProtoFilter> {
2936        self.get_ava_set(attr)
2937            .and_then(|vs| vs.to_json_filter_single())
2938    }
2939
2940    pub fn get_ava_single_private_binary<A: AsRef<Attribute>>(&self, attr: A) -> Option<&[u8]> {
2941        self.get_ava_set(attr)
2942            .and_then(|vs| vs.to_private_binary_single())
2943    }
2944
2945    pub fn get_ava_single_jws_key_es256<A: AsRef<Attribute>>(
2946        &self,
2947        attr: A,
2948    ) -> Option<&JwsEs256Signer> {
2949        self.get_ava_set(attr)
2950            .and_then(|vs| vs.to_jws_key_es256_single())
2951    }
2952
2953    pub fn get_ava_webauthn_attestation_ca_list<A: AsRef<Attribute>>(
2954        &self,
2955        attr: A,
2956    ) -> Option<&AttestationCaList> {
2957        self.get_ava_set(attr)
2958            .and_then(|vs| vs.as_webauthn_attestation_ca_list())
2959    }
2960
2961    pub fn get_ava_application_password<A: AsRef<Attribute>>(
2962        &self,
2963        attr: A,
2964    ) -> Option<&BTreeMap<Uuid, Vec<ApplicationPassword>>> {
2965        self.get_ava_set(attr)
2966            .and_then(|vs| vs.as_application_password_map())
2967    }
2968
2969    /// Return a single security principle name, if valid to transform this value.
2970    pub(crate) fn generate_spn(&self, domain_name: &str) -> Option<ValueSet> {
2971        if let Some(name) = self.get_ava_single_iname(Attribute::Name) {
2972            // There is a name attribute, lets return it.
2973            return Some(ValueSetSpn::new((name.into(), domain_name.into())));
2974        }
2975
2976        // Some entries may not have a name. There are now three paths.
2977        let spn_set = self.get_ava_set(Attribute::Spn)?;
2978
2979        if spn_set.syntax() == SyntaxType::SecurityPrincipalName {
2980            // - we already have a valid spn
2981            Some(spn_set.clone())
2982        } else if let Some(name) = spn_set.to_iname_single() {
2983            // - we have an iname stashed into the spn attr for generation.
2984            Some(ValueSetSpn::new((name.into(), domain_name.into())))
2985        } else {
2986            // - We have no way to proceed
2987            None
2988        }
2989    }
2990
2991    /// Assert if an attribute of this name is present on this entry.
2992    pub fn attribute_pres<A: AsRef<Attribute>>(&self, attr: A) -> bool {
2993        self.attrs.contains_key(attr.as_ref())
2994    }
2995
2996    /// Assert if an attribute of this name is present, and one of its values contains
2997    /// an exact match of this partial value.
2998    pub fn attribute_equality<A: AsRef<Attribute>>(&self, attr: A, value: &PartialValue) -> bool {
2999        // we assume based on schema normalisation on the way in
3000        // that the equality here of the raw values MUST be correct.
3001        // We also normalise filters, to ensure that their values are
3002        // syntax valid and will correctly match here with our indexes.
3003        match self.attrs.get(attr.as_ref()) {
3004            Some(v_list) => v_list.contains(value),
3005            None => false,
3006        }
3007    }
3008
3009    /// Assert if an attribute of this name is present, and one of it's values contains
3010    /// the following substring, if possible to perform the substring comparison.
3011    pub fn attribute_substring<A: AsRef<Attribute>>(
3012        &self,
3013        attr: A,
3014        subvalue: &PartialValue,
3015    ) -> bool {
3016        self.get_ava_set(attr)
3017            .map(|vset| vset.substring(subvalue))
3018            .unwrap_or(false)
3019    }
3020
3021    /// Assert if an attribute of this name is present, and one of its values startswith
3022    /// the following string, if possible to perform the comparison.
3023    pub fn attribute_startswith<A: AsRef<Attribute>>(
3024        &self,
3025        attr: A,
3026        subvalue: &PartialValue,
3027    ) -> bool {
3028        self.get_ava_set(attr)
3029            .map(|vset| vset.startswith(subvalue))
3030            .unwrap_or(false)
3031    }
3032
3033    /// Assert if an attribute of this name is present, and one of its values startswith
3034    /// the following string, if possible to perform the comparison.
3035    pub fn attribute_endswith<A: AsRef<Attribute>>(
3036        &self,
3037        attr: A,
3038        subvalue: &PartialValue,
3039    ) -> bool {
3040        self.get_ava_set(attr)
3041            .map(|vset| vset.endswith(subvalue))
3042            .unwrap_or(false)
3043    }
3044
3045    /// Assert if an attribute of this name is present, and one of its values is less than
3046    /// the following partial value
3047    pub fn attribute_lessthan<A: AsRef<Attribute>>(
3048        &self,
3049        attr: A,
3050        subvalue: &PartialValue,
3051    ) -> bool {
3052        self.get_ava_set(attr)
3053            .map(|vset| vset.lessthan(subvalue))
3054            .unwrap_or(false)
3055    }
3056
3057    // Since EntryValid/Invalid is just about class adherence, not Value correctness, we
3058    // can now apply filters to invalid entries - why? Because even if they aren't class
3059    // valid, we still have strict typing checks between the filter -> entry to guarantee
3060    // they should be functional. We'll never match something that isn't syntactically valid.
3061    #[inline(always)]
3062    #[instrument(level = "trace", name = "entry::entry_match_no_index", skip(self))]
3063    /// Test if the following filter applies to and matches this entry.
3064    pub fn entry_match_no_index(&self, filter: &Filter<FilterValidResolved>) -> bool {
3065        self.entry_match_no_index_inner(filter.to_inner())
3066    }
3067
3068    // This is private, but exists on all types, so that valid and normal can then
3069    // expose the simpler wrapper for entry_match_no_index only.
3070    // Assert if this filter matches the entry (no index)
3071    fn entry_match_no_index_inner(&self, filter: &FilterResolved) -> bool {
3072        // Go through the filter components and check them in the entry.
3073        // This is recursive!!!!
3074        match filter {
3075            FilterResolved::Eq(attr, value, _) => self.attribute_equality(attr, value),
3076            FilterResolved::Cnt(attr, subvalue, _) => self.attribute_substring(attr, subvalue),
3077            FilterResolved::Stw(attr, subvalue, _) => self.attribute_startswith(attr, subvalue),
3078            FilterResolved::Enw(attr, subvalue, _) => self.attribute_endswith(attr, subvalue),
3079            FilterResolved::Pres(attr, _) => self.attribute_pres(attr),
3080            FilterResolved::LessThan(attr, subvalue, _) => self.attribute_lessthan(attr, subvalue),
3081            // Check with ftweedal about or filter zero len correctness.
3082            FilterResolved::Or(l, _) => l.iter().any(|f| self.entry_match_no_index_inner(f)),
3083            // Check with ftweedal about and filter zero len correctness.
3084            FilterResolved::And(l, _) => l.iter().all(|f| self.entry_match_no_index_inner(f)),
3085            FilterResolved::Inclusion(_, _) => {
3086                // An inclusion doesn't make sense on an entry in isolation!
3087                // Inclusions are part of exists queries, on search they mean
3088                // nothing!
3089                false
3090            }
3091            FilterResolved::AndNot(f, _) => !self.entry_match_no_index_inner(f),
3092            FilterResolved::Invalid(_) => false,
3093        }
3094    }
3095
3096    /// Given this entry, generate a filter containing the requested attributes strings as
3097    /// equality components.
3098    pub fn filter_from_attrs(&self, attrs: &[Attribute]) -> Option<Filter<FilterInvalid>> {
3099        // Because we are a valid entry, a filter we create still may not
3100        // be valid because the internal server entry templates are still
3101        // created by humans! Plus double checking something already valid
3102        // is not bad ...
3103        //
3104        // Generate a filter from the attributes requested and defined.
3105        // Basically, this is a series of nested and's (which will be
3106        // optimised down later: but if someone wants to solve flatten() ...)
3107
3108        // Take name: (a, b), name: (c, d) -> (name, a), (name, b), (name, c), (name, d)
3109
3110        let mut pairs: Vec<(Attribute, PartialValue)> = Vec::with_capacity(0);
3111
3112        for attr in attrs {
3113            {
3114                let values = self.attrs.get(attr)?;
3115                values
3116                    .to_partialvalue_iter()
3117                    .for_each(|pv| pairs.push((attr.clone(), pv)))
3118            }
3119        }
3120
3121        let res: Vec<FC> = pairs
3122            .into_iter()
3123            .map(|(attr, pv)| FC::Eq(attr, pv))
3124            .collect();
3125        Some(filter_all!(f_and(res)))
3126    }
3127
3128    /// Given this entry, generate a modification list that would "assert"
3129    /// another entry is in the same/identical attribute state.
3130    pub fn gen_modlist_assert(
3131        &self,
3132        schema: &dyn SchemaTransaction,
3133    ) -> Result<ModifyList<ModifyInvalid>, SchemaError> {
3134        // Create a modlist from this entry. We make this assuming we want the entry
3135        // to have this one as a subset of values. This means if we have single
3136        // values, we'll replace, if they are multivalue, we present them.
3137        let mut mods = ModifyList::new();
3138
3139        for (k, vs) in self.attrs.iter() {
3140            // WHY?! We skip uuid here because it is INVALID for a UUID
3141            // to be in a modlist, and the base.rs plugin will fail if it
3142            // is there. This actually doesn't matter, because to apply the
3143            // modlist in these situations we already know the entry MUST
3144            // exist with that UUID, we only need to conform it's other
3145            // attributes into the same state.
3146            //
3147            // In the future, if we make uuid a real entry type, then this
3148            // check can "go away" because uuid will never exist as an ava.
3149            //
3150            // NOTE: Remove this check when uuid becomes a real attribute.
3151            // UUID is now a real attribute, but it also has an ava for db_entry
3152            // conversion - so what do? If we remove it here, we could have CSN issue with
3153            // repl on uuid conflict, but it probably shouldn't be an ava either ...
3154            // as a result, I think we need to keep this continue line to not cause issues.
3155            if *k == Attribute::Uuid {
3156                continue;
3157            }
3158            // Get the schema attribute type out.
3159            {
3160                let r = schema.is_multivalue(k)?;
3161                // As this is single value, purge then present to maintain this
3162                // invariant.
3163                if !r ||
3164                    // we need to be able to express REMOVAL of attributes, so we
3165                    // purge here for migrations of certain system attributes.
3166                    *k == Attribute::AcpReceiverGroup ||
3167                    *k == Attribute::AcpCreateAttr ||
3168                    *k == Attribute::AcpCreateClass ||
3169                    *k == Attribute::AcpModifyPresentAttr ||
3170                    *k == Attribute::AcpModifyRemovedAttr ||
3171                    *k == Attribute::AcpModifyClass ||
3172                    *k == Attribute::SystemMust ||
3173                    *k == Attribute::SystemMay
3174                {
3175                    mods.push_mod(Modify::Purged(k.clone()));
3176                }
3177            }
3178            for v in vs.to_value_iter() {
3179                mods.push_mod(Modify::Present(k.clone(), v.clone()));
3180            }
3181        }
3182
3183        Ok(mods)
3184    }
3185
3186    /// Determine if this entry is recycled or a tombstone, and map that to "None". This allows
3187    /// filter_map to effectively remove entries that should not be considered as "alive".
3188    pub fn mask_recycled_ts(&self) -> Option<&Self> {
3189        // Only when cls has ts/rc then None, else always Some(self).
3190        match self.attrs.get(&Attribute::Class) {
3191            Some(cls) => {
3192                if cls.contains(&EntryClass::Tombstone.to_partialvalue())
3193                    || cls.contains(&EntryClass::Recycled.to_partialvalue())
3194                {
3195                    None
3196                } else {
3197                    Some(self)
3198                }
3199            }
3200            None => Some(self),
3201        }
3202    }
3203
3204    /// Determine if this entry is recycled, and map that to "None". This allows
3205    /// filter_map to effectively remove entries that are recycled in some cases.
3206    pub fn mask_recycled(&self) -> Option<&Self> {
3207        // Only when cls has ts/rc then None, else lways Some(self).
3208        match self.attrs.get(&Attribute::Class) {
3209            Some(cls) => {
3210                if cls.contains(&EntryClass::Recycled.to_partialvalue()) {
3211                    None
3212                } else {
3213                    Some(self)
3214                }
3215            }
3216            None => Some(self),
3217        }
3218    }
3219
3220    /// Determine if this entry is a tombstone, and map that to "None". This allows
3221    /// filter_map to effectively remove entries that are tombstones in some cases.
3222    pub fn mask_tombstone(&self) -> Option<&Self> {
3223        // Only when cls has ts/rc then None, else lways Some(self).
3224        match self.attrs.get(&Attribute::Class) {
3225            Some(cls) => {
3226                if cls.contains(&EntryClass::Tombstone.to_partialvalue()) {
3227                    None
3228                } else {
3229                    Some(self)
3230                }
3231            }
3232            None => Some(self),
3233        }
3234    }
3235}
3236
3237impl<STATE> Entry<EntryInvalid, STATE>
3238where
3239    STATE: Clone,
3240{
3241    // This should always work? It's only on validate that we'll build
3242    // a list of syntax violations ...
3243    // If this already exists, we silently drop the event. This is because
3244    // we need this to be *state* based where we assert presence.
3245    pub fn add_ava(&mut self, attr: Attribute, value: Value) {
3246        self.valid.ecstate.change_ava(&self.valid.cid, &attr);
3247        self.add_ava_int(attr, value);
3248    }
3249
3250    pub fn add_ava_if_not_exist<A: AsRef<Attribute>>(&mut self, attr: A, value: Value) {
3251        let attr_ref = attr.as_ref();
3252        // This returns true if the value WAS changed! See add_ava_int.
3253        if self.add_ava_int(attr_ref.clone(), value) {
3254            // In this case, we ONLY update the changestate if the value was already present!
3255            self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3256        }
3257    }
3258
3259    fn assert_ava<A: AsRef<Attribute>>(
3260        &mut self,
3261        attr: A,
3262        value: &PartialValue,
3263    ) -> Result<(), OperationError> {
3264        self.valid
3265            .ecstate
3266            .change_ava(&self.valid.cid, attr.as_ref());
3267
3268        if self.attribute_equality(attr, value) {
3269            Ok(())
3270        } else {
3271            Err(OperationError::ModifyAssertionFailed)
3272        }
3273    }
3274
3275    /// Remove an attribute-value pair from this entry. If the ava doesn't exist, we
3276    /// don't do anything else since we are asserting the absence of a value.
3277    pub(crate) fn remove_ava<A: AsRef<Attribute>>(&mut self, attr: A, value: &PartialValue) {
3278        let attr_ref = attr.as_ref();
3279        self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3280
3281        let rm = if let Some(vs) = self.attrs.get_mut(attr_ref) {
3282            vs.remove(value, &self.valid.cid)
3283        } else {
3284            false
3285        };
3286        if rm {
3287            self.attrs.remove(attr_ref);
3288        };
3289    }
3290
3291    pub(crate) fn remove_avas<A: AsRef<Attribute>>(
3292        &mut self,
3293        attr: A,
3294        values: &BTreeSet<PartialValue>,
3295    ) {
3296        let attr_ref = attr.as_ref();
3297        self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3298
3299        let rm = if let Some(vs) = self.attrs.get_mut(attr_ref) {
3300            values.iter().any(|k| vs.remove(k, &self.valid.cid))
3301        } else {
3302            false
3303        };
3304        if rm {
3305            self.attrs.remove(attr_ref);
3306        };
3307    }
3308
3309    /// Remove all values of this attribute from the entry. If it doesn't exist, this
3310    /// asserts that no content of that attribute exist.
3311    pub(crate) fn purge_ava<A: AsRef<Attribute>>(&mut self, attr: A) {
3312        let attr_ref = attr.as_ref();
3313        self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3314        // self.valid.eclog.purge_ava(&self.valid.cid, attr);
3315
3316        let can_remove = self
3317            .attrs
3318            .get_mut(attr_ref)
3319            .map(|vs| vs.purge(&self.valid.cid))
3320            // Default to false since a missing attr can't be removed!
3321            .unwrap_or_default();
3322        if can_remove {
3323            self.attrs.remove(attr_ref);
3324        }
3325    }
3326
3327    /// Remove this value set from the entry, returning the value set at the time of removal.
3328    pub fn pop_ava<A: AsRef<Attribute>>(&mut self, attr: A) -> Option<ValueSet> {
3329        let attr_ref = attr.as_ref();
3330        self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3331
3332        let mut vs = self.attrs.remove(attr_ref)?;
3333        if vs.purge(&self.valid.cid) {
3334            // Can return as is.
3335            Some(vs)
3336        } else {
3337            // This type may need special handling. Clone and reinsert.
3338            let r_vs = vs.clone();
3339            self.attrs.insert(attr_ref.clone(), vs);
3340            Some(r_vs)
3341        }
3342    }
3343
3344    /// Unlike pop or purge, this does NOT respect the attributes purge settings, meaning
3345    /// that this can break replication by force clearing the state of an attribute. It's
3346    /// useful for things like "session" to test the grace window by removing the revoked
3347    /// sessions from the value set that you otherwise, could not.
3348    #[cfg(test)]
3349    pub(crate) fn force_trim_ava<A: AsRef<Attribute>>(&mut self, attr: A) -> Option<ValueSet> {
3350        self.valid
3351            .ecstate
3352            .change_ava(&self.valid.cid, attr.as_ref());
3353        self.attrs.remove(attr.as_ref())
3354    }
3355
3356    /// Replace the content of this attribute with the values from this
3357    /// iterator. If the iterator is empty, the attribute is purged.
3358    pub fn set_ava<T>(&mut self, attr: &Attribute, iter: T)
3359    where
3360        T: Clone + IntoIterator<Item = Value>,
3361    {
3362        self.purge_ava(attr);
3363        self.set_ava_iter_int(attr.clone(), iter)
3364    }
3365
3366    /// Replace the content of this attribute with a new value set. Effectively this is
3367    /// a a "purge and set".
3368    pub fn set_ava_set(&mut self, attr: &Attribute, vs: ValueSet) {
3369        self.purge_ava(attr);
3370        if let Some(existing_vs) = self.attrs.get_mut(attr) {
3371            let _ = existing_vs.merge(&vs);
3372        } else {
3373            self.attrs.insert(attr.clone(), vs);
3374        }
3375    }
3376
3377    /// Merge the content from the new ValueSet into the existing ValueSet. If no existing
3378    /// ValueSet is present, then these data are inserted.
3379    pub fn merge_ava_set(&mut self, attr: &Attribute, vs: ValueSet) -> Result<(), OperationError> {
3380        self.valid.ecstate.change_ava(&self.valid.cid, attr);
3381        if let Some(existing_vs) = self.attrs.get_mut(attr) {
3382            debug!(?attr, ?existing_vs, ?vs);
3383            existing_vs.merge(&vs)
3384        } else {
3385            self.attrs.insert(attr.clone(), vs);
3386            Ok(())
3387        }
3388    }
3389
3390    pub(crate) fn migrate_ava<A: AsRef<Attribute>>(
3391        &mut self,
3392        attr: A,
3393    ) -> Result<(), OperationError> {
3394        let attr_ref = attr.as_ref();
3395        // In theory we should update the change state, but this causes issues if we
3396        // are altering a tombstone, which *may* happen.
3397
3398        // self.valid.ecstate.change_ava(&self.valid.cid, attr_ref);
3399
3400        let maybe_vs = if let Some(vs) = self.attrs.get(attr_ref) {
3401            vs.migrate()?
3402        } else {
3403            None
3404        };
3405
3406        if let Some(vs) = maybe_vs {
3407            self.attrs.insert(attr_ref.clone(), vs);
3408        }
3409
3410        Ok(())
3411    }
3412
3413    /// Apply the content of this modlist to this entry, enforcing the expressed state.
3414    pub fn apply_modlist(
3415        &mut self,
3416        modlist: &ModifyList<ModifyValid>,
3417    ) -> Result<(), OperationError> {
3418        for modify in modlist {
3419            match modify {
3420                Modify::Present(attr, value) => {
3421                    self.add_ava(attr.clone(), value.clone());
3422                }
3423                Modify::Removed(attr, value) => {
3424                    self.remove_ava(attr, value);
3425                }
3426                Modify::Purged(attr) => {
3427                    self.purge_ava(attr);
3428                }
3429                Modify::Assert(attr, value) => {
3430                    self.assert_ava(attr, value).inspect_err(|_e| {
3431                        error!("Modification assertion was not met. {} {:?}", attr, value);
3432                    })?;
3433                }
3434                Modify::Set(attr, valueset) => self.set_ava_set(attr, valueset.clone()),
3435            }
3436        }
3437        Ok(())
3438    }
3439}
3440
3441impl<VALID, STATE> PartialEq for Entry<VALID, STATE> {
3442    fn eq(&self, rhs: &Entry<VALID, STATE>) -> bool {
3443        // This may look naive - but it is correct. This is because
3444        // all items that end up in an item MUST have passed through
3445        // schema validation and normalisation so we can assume that
3446        // all rules were applied correctly. Thus we can just simply
3447        // do a char-compare like this.
3448        //
3449        // Of course, this is only true on the "Valid" types ... the others
3450        // are not guaranteed to support this ... but more likely that will
3451        // just end in eager false-results. We'll never say something is true
3452        // that should NOT be.
3453        compare_attrs(&self.attrs, &rhs.attrs)
3454    }
3455}
3456
3457/// This is a helper function to create an entry from an iterator of attribute-value pairs. This is a replacement for the old `entry_init!`` macro
3458pub(crate) fn entry_init_fn<T>(args: T) -> EntryInitNew
3459where
3460    T: IntoIterator<Item = (Attribute, Value)>,
3461{
3462    let mut entry: EntryInitNew = Entry::new();
3463    args.into_iter().for_each(|(k, v)| entry.add_ava(k, v));
3464    entry
3465}
3466
3467#[cfg(test)]
3468mod tests {
3469    use crate::prelude::*;
3470    use std::collections::BTreeSet as Set;
3471
3472    use hashbrown::HashMap;
3473
3474    use crate::{
3475        be::{IdxKey, IdxSlope},
3476        entry::{Entry, EntryInit, EntryInvalid, EntryNew},
3477        modify::{Modify, ModifyList},
3478        value::{IndexType, PartialValue, Value},
3479    };
3480
3481    #[test]
3482    fn test_entry_basic() {
3483        let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3484
3485        e.add_ava(Attribute::UserId, Value::from("william"));
3486    }
3487
3488    #[test]
3489    fn test_entry_dup_value() {
3490        // Schema doesn't matter here because we are duplicating a value
3491        // it should fail!
3492
3493        // We still probably need schema here anyway to validate what we
3494        // are adding ... Or do we validate after the changes are made in
3495        // total?
3496        let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3497        e.add_ava(Attribute::UserId, Value::from("william"));
3498        e.add_ava(Attribute::UserId, Value::from("william"));
3499
3500        let values = e.get_ava_set(Attribute::UserId).expect("Failed to get ava");
3501        // Should only be one value!
3502        assert_eq!(values.len(), 1)
3503    }
3504
3505    #[test]
3506    fn test_entry_pres() {
3507        let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3508        e.add_ava(Attribute::UserId, Value::from("william"));
3509
3510        assert!(e.attribute_pres(Attribute::UserId));
3511        assert!(!e.attribute_pres(Attribute::Name));
3512    }
3513
3514    #[test]
3515    fn test_entry_equality() {
3516        let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3517
3518        e.add_ava(Attribute::UserId, Value::from("william"));
3519
3520        assert!(e.attribute_equality(Attribute::UserId, &PartialValue::new_utf8s("william")));
3521        assert!(!e.attribute_equality(Attribute::UserId, &PartialValue::new_utf8s("test")));
3522        assert!(!e.attribute_equality(Attribute::NonExist, &PartialValue::new_utf8s("william")));
3523        // Also test non-matching attr syntax
3524        assert!(!e.attribute_equality(Attribute::UserId, &PartialValue::new_iutf8("william")));
3525    }
3526
3527    #[test]
3528    fn test_entry_substring() {
3529        let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3530
3531        e.add_ava(Attribute::UserId, Value::from("william"));
3532
3533        assert!(e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("william")));
3534        assert!(e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("will")));
3535        assert!(e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("liam")));
3536        assert!(e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("lli")));
3537        assert!(!e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("llim")));
3538        assert!(!e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("bob")));
3539        assert!(!e.attribute_substring(Attribute::UserId, &PartialValue::new_utf8s("wl")));
3540
3541        assert!(e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("will")));
3542        assert!(!e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("liam")));
3543        assert!(!e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("lli")));
3544        assert!(!e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("llim")));
3545        assert!(!e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("bob")));
3546        assert!(!e.attribute_startswith(Attribute::UserId, &PartialValue::new_utf8s("wl")));
3547
3548        assert!(e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("liam")));
3549        assert!(!e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("will")));
3550        assert!(!e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("lli")));
3551        assert!(!e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("llim")));
3552        assert!(!e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("bob")));
3553        assert!(!e.attribute_endswith(Attribute::UserId, &PartialValue::new_utf8s("wl")));
3554    }
3555
3556    #[test]
3557    fn test_entry_lessthan() {
3558        let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3559
3560        let pv2 = PartialValue::new_uint32(2);
3561        let pv8 = PartialValue::new_uint32(8);
3562        let pv10 = PartialValue::new_uint32(10);
3563        let pv15 = PartialValue::new_uint32(15);
3564
3565        e1.add_ava(Attribute::TestAttr, Value::new_uint32(10));
3566
3567        assert!(!e1.attribute_lessthan(Attribute::TestAttr, &pv2));
3568        assert!(!e1.attribute_lessthan(Attribute::TestAttr, &pv8));
3569        assert!(!e1.attribute_lessthan(Attribute::TestAttr, &pv10));
3570        assert!(e1.attribute_lessthan(Attribute::TestAttr, &pv15));
3571
3572        e1.add_ava(Attribute::TestAttr, Value::new_uint32(8));
3573
3574        assert!(!e1.attribute_lessthan(Attribute::TestAttr, &pv2));
3575        assert!(!e1.attribute_lessthan(Attribute::TestAttr, &pv8));
3576        assert!(e1.attribute_lessthan(Attribute::TestAttr, &pv10));
3577        assert!(e1.attribute_lessthan(Attribute::TestAttr, &pv15));
3578    }
3579
3580    #[test]
3581    fn test_entry_apply_modlist() {
3582        // Test application of changes to an entry.
3583        let mut e: Entry<EntryInvalid, EntryNew> = Entry::new().into_invalid_new();
3584
3585        e.add_ava(Attribute::UserId, Value::from("william"));
3586
3587        let present_single_mods = ModifyList::new_valid_list(vec![Modify::Present(
3588            Attribute::Attr,
3589            Value::new_iutf8("value"),
3590        )]);
3591
3592        assert!(e.apply_modlist(&present_single_mods).is_ok());
3593
3594        // Assert the changes are there
3595        assert!(e.attribute_equality(Attribute::UserId, &PartialValue::new_utf8s("william")));
3596        assert!(e.attribute_equality(Attribute::Attr, &PartialValue::new_iutf8("value")));
3597
3598        // Assert present for multivalue
3599        let present_multivalue_mods = ModifyList::new_valid_list(vec![
3600            Modify::Present(Attribute::Class, Value::new_iutf8n("test")),
3601            Modify::Present(Attribute::Class, Value::new_iutf8n("multi_test")),
3602        ]);
3603
3604        assert!(e.apply_modlist(&present_multivalue_mods).is_ok());
3605
3606        assert!(e.attribute_equality(Attribute::Class, &PartialValue::new_iutf8("test")));
3607        assert!(e.attribute_equality(Attribute::Class, &PartialValue::new_iutf8("multi_test")));
3608
3609        // Assert purge on single/multi/empty value
3610        let purge_single_mods = ModifyList::new_valid_list(vec![Modify::Purged(Attribute::Attr)]);
3611
3612        assert!(e.apply_modlist(&purge_single_mods).is_ok());
3613
3614        assert!(!e.attribute_pres(Attribute::Attr));
3615
3616        let purge_multi_mods = ModifyList::new_valid_list(vec![Modify::Purged(Attribute::Class)]);
3617
3618        assert!(e.apply_modlist(&purge_multi_mods).is_ok());
3619
3620        assert!(!e.attribute_pres(Attribute::Class));
3621
3622        let purge_empty_mods = purge_single_mods;
3623
3624        assert!(e.apply_modlist(&purge_empty_mods).is_ok());
3625
3626        // Assert removed on value that exists and doesn't exist
3627        let remove_mods = ModifyList::new_valid_list(vec![Modify::Removed(
3628            Attribute::Attr,
3629            PartialValue::new_iutf8("value"),
3630        )]);
3631
3632        assert!(e.apply_modlist(&present_single_mods).is_ok());
3633        assert!(e.attribute_equality(Attribute::Attr, &PartialValue::new_iutf8("value")));
3634        assert!(e.apply_modlist(&remove_mods).is_ok());
3635        assert!(!e.attrs.contains_key(&Attribute::Attr));
3636
3637        let remove_empty_mods = remove_mods;
3638
3639        assert!(e.apply_modlist(&remove_empty_mods).is_ok());
3640
3641        assert!(!e.attrs.contains_key(&Attribute::Attr));
3642    }
3643
3644    #[test]
3645    fn test_entry_idx_diff() {
3646        let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3647        e1.add_ava(Attribute::UserId, Value::from("william"));
3648        let mut e1_mod = e1.clone();
3649        e1_mod.add_ava(Attribute::Extra, Value::from("test"));
3650
3651        let e1 = e1.into_sealed_committed();
3652        let e1_mod = e1_mod.into_sealed_committed();
3653
3654        let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3655        e2.add_ava(Attribute::UserId, Value::from("claire"));
3656        let e2 = e2.into_sealed_committed();
3657
3658        let mut idxmeta = HashMap::with_capacity(8);
3659        idxmeta.insert(
3660            IdxKey {
3661                attr: Attribute::UserId,
3662                itype: IndexType::Equality,
3663            },
3664            IdxSlope::MAX,
3665        );
3666        idxmeta.insert(
3667            IdxKey {
3668                attr: Attribute::UserId,
3669                itype: IndexType::Presence,
3670            },
3671            IdxSlope::MAX,
3672        );
3673        idxmeta.insert(
3674            IdxKey {
3675                attr: Attribute::Extra,
3676                itype: IndexType::Equality,
3677            },
3678            IdxSlope::MAX,
3679        );
3680
3681        // When we do None, None, we get nothing back.
3682        let r1 = Entry::idx_diff(&idxmeta, None, None);
3683        eprintln!("{r1:?}");
3684        assert_eq!(r1, Vec::with_capacity(0));
3685
3686        // Check generating a delete diff
3687        let mut del_r = Entry::idx_diff(&idxmeta, Some(&e1), None);
3688        del_r.sort_unstable();
3689        eprintln!("del_r {del_r:?}");
3690        assert!(
3691            del_r[0]
3692                == Err((
3693                    &Attribute::UserId,
3694                    IndexType::Equality,
3695                    "william".to_string()
3696                ))
3697        );
3698        assert!(del_r[1] == Err((&Attribute::UserId, IndexType::Presence, "_".to_string())));
3699
3700        // Check generating an add diff
3701        let mut add_r = Entry::idx_diff(&idxmeta, None, Some(&e1));
3702        add_r.sort_unstable();
3703        eprintln!("{add_r:?}");
3704        assert!(
3705            add_r[0]
3706                == Ok((
3707                    &Attribute::UserId,
3708                    IndexType::Equality,
3709                    "william".to_string()
3710                ))
3711        );
3712        assert!(add_r[1] == Ok((&Attribute::UserId, IndexType::Presence, "_".to_string())));
3713
3714        // Check the mod cases now
3715
3716        // Check no changes
3717        let no_r = Entry::idx_diff(&idxmeta, Some(&e1), Some(&e1));
3718        assert!(no_r.is_empty());
3719
3720        // Check "adding" an attribute.
3721        let add_a_r = Entry::idx_diff(&idxmeta, Some(&e1), Some(&e1_mod));
3722        assert!(add_a_r[0] == Ok((&Attribute::Extra, IndexType::Equality, "test".to_string())));
3723
3724        // Check "removing" an attribute.
3725        let del_a_r = Entry::idx_diff(&idxmeta, Some(&e1_mod), Some(&e1));
3726        assert!(del_a_r[0] == Err((&Attribute::Extra, IndexType::Equality, "test".to_string())));
3727
3728        // Change an attribute.
3729        let mut chg_r = Entry::idx_diff(&idxmeta, Some(&e1), Some(&e2));
3730        chg_r.sort_unstable();
3731        eprintln!("{chg_r:?}");
3732        assert!(
3733            chg_r[1]
3734                == Err((
3735                    &Attribute::UserId,
3736                    IndexType::Equality,
3737                    "william".to_string()
3738                ))
3739        );
3740
3741        assert!(
3742            chg_r[0]
3743                == Ok((
3744                    &Attribute::UserId,
3745                    IndexType::Equality,
3746                    "claire".to_string()
3747                ))
3748        );
3749    }
3750
3751    #[test]
3752    fn test_entry_mask_recycled_ts() {
3753        let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3754        e1.add_ava(Attribute::Class, EntryClass::Person.to_value());
3755        let e1 = e1.into_sealed_committed();
3756        assert!(e1.mask_recycled_ts().is_some());
3757
3758        let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3759        e2.add_ava(Attribute::Class, EntryClass::Person.to_value());
3760        e2.add_ava(Attribute::Class, EntryClass::Recycled.into());
3761        let e2 = e2.into_sealed_committed();
3762        assert!(e2.mask_recycled_ts().is_none());
3763
3764        let mut e3: Entry<EntryInit, EntryNew> = Entry::new();
3765        e3.add_ava(Attribute::Class, EntryClass::Tombstone.into());
3766        let e3 = e3.into_sealed_committed();
3767        assert!(e3.mask_recycled_ts().is_none());
3768    }
3769
3770    #[test]
3771    fn test_entry_idx_name2uuid_diff() {
3772        // none, none,
3773        let r = Entry::idx_name2uuid_diff(None, None);
3774        assert_eq!(r, (None, None));
3775
3776        // none, some - test adding an entry gives back add sets
3777        {
3778            let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3779            e.add_ava(Attribute::Class, EntryClass::Person.to_value());
3780            let e = e.into_sealed_committed();
3781
3782            assert!(Entry::idx_name2uuid_diff(None, Some(&e)) == (Some(Set::new()), None));
3783        }
3784
3785        {
3786            let mut e: Entry<EntryInit, EntryNew> = Entry::new();
3787            e.add_ava(Attribute::Class, EntryClass::Person.to_value());
3788            e.add_ava(Attribute::GidNumber, Value::new_uint32(1300));
3789            e.add_ava(Attribute::Name, Value::new_iname("testperson"));
3790            e.add_ava(
3791                Attribute::Spn,
3792                Value::new_spn_str("testperson", "example.com"),
3793            );
3794            e.add_ava(
3795                Attribute::Uuid,
3796                Value::Uuid(uuid!("9fec0398-c46c-4df4-9df5-b0016f7d563f")),
3797            );
3798            let e = e.into_sealed_committed();
3799
3800            // Note the uuid isn't present!
3801            assert!(
3802                Entry::idx_name2uuid_diff(None, Some(&e))
3803                    == (
3804                        Some(btreeset![
3805                            "1300".to_string(),
3806                            "testperson".to_string(),
3807                            "testperson@example.com".to_string()
3808                        ]),
3809                        None
3810                    )
3811            );
3812            // some, none,
3813            // Check delete, swap the order of args
3814            assert!(
3815                Entry::idx_name2uuid_diff(Some(&e), None)
3816                    == (
3817                        None,
3818                        Some(btreeset![
3819                            "1300".to_string(),
3820                            "testperson".to_string(),
3821                            "testperson@example.com".to_string()
3822                        ])
3823                    )
3824            );
3825
3826            // some, some (same), should be empty changes.
3827            assert!(
3828                Entry::idx_name2uuid_diff(Some(&e), Some(&e))
3829                    == (Some(Set::new()), Some(Set::new()))
3830            );
3831        }
3832        // some, some (diff)
3833
3834        {
3835            let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3836            e1.add_ava(Attribute::Class, EntryClass::Person.to_value());
3837            e1.add_ava(
3838                Attribute::Spn,
3839                Value::new_spn_str("testperson", "example.com"),
3840            );
3841            let e1 = e1.into_sealed_committed();
3842
3843            let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3844            e2.add_ava(Attribute::Class, EntryClass::Person.to_value());
3845            e2.add_ava(Attribute::Name, Value::new_iname("testperson"));
3846            e2.add_ava(
3847                Attribute::Spn,
3848                Value::new_spn_str("testperson", "example.com"),
3849            );
3850            let e2 = e2.into_sealed_committed();
3851
3852            // One attr added
3853            assert!(
3854                Entry::idx_name2uuid_diff(Some(&e1), Some(&e2))
3855                    == (Some(btreeset!["testperson".to_string()]), Some(Set::new()))
3856            );
3857
3858            // One removed
3859            assert!(
3860                Entry::idx_name2uuid_diff(Some(&e2), Some(&e1))
3861                    == (Some(Set::new()), Some(btreeset!["testperson".to_string()]))
3862            );
3863        }
3864
3865        // Value changed, remove old, add new.
3866        {
3867            let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3868            e1.add_ava(Attribute::Class, EntryClass::Person.to_value());
3869            e1.add_ava(
3870                Attribute::Spn,
3871                Value::new_spn_str("testperson", "example.com"),
3872            );
3873            let e1 = e1.into_sealed_committed();
3874
3875            let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3876            e2.add_ava(Attribute::Class, EntryClass::Person.to_value());
3877            e2.add_ava(
3878                Attribute::Spn,
3879                Value::new_spn_str("renameperson", "example.com"),
3880            );
3881            let e2 = e2.into_sealed_committed();
3882
3883            assert!(
3884                Entry::idx_name2uuid_diff(Some(&e1), Some(&e2))
3885                    == (
3886                        Some(btreeset!["renameperson@example.com".to_string()]),
3887                        Some(btreeset!["testperson@example.com".to_string()])
3888                    )
3889            );
3890        }
3891    }
3892
3893    #[test]
3894    fn test_entry_idx_uuid2spn_diff() {
3895        assert!(Entry::idx_uuid2spn_diff(None, None).is_none());
3896
3897        let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3898        e1.add_ava(
3899            Attribute::Spn,
3900            Value::new_spn_str("testperson", "example.com"),
3901        );
3902        let e1 = e1.into_sealed_committed();
3903
3904        let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3905        e2.add_ava(
3906            Attribute::Spn,
3907            Value::new_spn_str("renameperson", "example.com"),
3908        );
3909        let e2 = e2.into_sealed_committed();
3910
3911        assert!(
3912            Entry::idx_uuid2spn_diff(None, Some(&e1))
3913                == Some(Ok(Value::new_spn_str("testperson", "example.com")))
3914        );
3915        assert!(Entry::idx_uuid2spn_diff(Some(&e1), None) == Some(Err(())));
3916        assert!(Entry::idx_uuid2spn_diff(Some(&e1), Some(&e1)).is_none());
3917        assert!(
3918            Entry::idx_uuid2spn_diff(Some(&e1), Some(&e2))
3919                == Some(Ok(Value::new_spn_str("renameperson", "example.com")))
3920        );
3921    }
3922
3923    #[test]
3924    fn test_entry_idx_uuid2rdn_diff() {
3925        assert!(Entry::idx_uuid2rdn_diff(None, None).is_none());
3926
3927        let mut e1: Entry<EntryInit, EntryNew> = Entry::new();
3928        e1.add_ava(
3929            Attribute::Spn,
3930            Value::new_spn_str("testperson", "example.com"),
3931        );
3932        let e1 = e1.into_sealed_committed();
3933
3934        let mut e2: Entry<EntryInit, EntryNew> = Entry::new();
3935        e2.add_ava(
3936            Attribute::Spn,
3937            Value::new_spn_str("renameperson", "example.com"),
3938        );
3939        let e2 = e2.into_sealed_committed();
3940
3941        assert!(
3942            Entry::idx_uuid2rdn_diff(None, Some(&e1))
3943                == Some(Ok("spn=testperson@example.com".to_string()))
3944        );
3945        assert!(Entry::idx_uuid2rdn_diff(Some(&e1), None) == Some(Err(())));
3946        assert!(Entry::idx_uuid2rdn_diff(Some(&e1), Some(&e1)).is_none());
3947        assert!(
3948            Entry::idx_uuid2rdn_diff(Some(&e1), Some(&e2))
3949                == Some(Ok("spn=renameperson@example.com".to_string()))
3950        );
3951    }
3952}