1use 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#[derive(Clone, Debug)]
100pub struct EntryNew; #[derive(Clone, Debug)]
104pub struct EntryCommitted {
105 id: u64,
106}
107
108#[derive(Clone, Debug)]
109pub struct EntryInit;
110
111#[derive(Clone, Debug)]
118pub struct EntryInvalid {
119 cid: Cid,
120 ecstate: EntryChangeState,
121}
122
123#[derive(Clone, Debug)]
125pub struct EntryRefresh {
126 ecstate: EntryChangeState,
127}
128
129#[derive(Clone, Debug)]
131pub struct EntryIncremental {
132 uuid: Uuid,
134 ecstate: EntryChangeState,
135}
136
137#[derive(Clone, Debug)]
143pub struct EntryValid {
144 uuid: Uuid,
146 ecstate: EntryChangeState,
147}
148
149#[derive(Clone, Debug)]
156pub struct EntrySealed {
157 uuid: Uuid,
158 ecstate: EntryChangeState,
159}
160
161#[derive(Clone, Debug)]
167pub struct EntryReduced {
168 uuid: Uuid,
169 effective_access: Option<Box<AccessEffectivePermission>>,
170}
171
172pub 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 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 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
209pub struct Entry<VALID, STATE> {
236 valid: VALID,
237 state: STATE,
238 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 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 valid: EntryInit,
309 state: EntryNew,
310 attrs: Map::new(),
311 }
312 }
313
314 pub fn from_proto_entry(
317 e: &ProtoEntry,
318 qs: &mut QueryServerWriteTransaction,
319 ) -> Result<Self, OperationError> {
320 trace!("from_proto_entry");
321 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 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 #[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 let pe: ProtoEntry = serde_json::from_str(es).map_err(|e| {
374 admin_error!(?e, "SerdeJson Failure");
377 OperationError::SerdeJsonError
378 })?;
379 Self::from_proto_entry(&pe, qs)
381 }
382
383 pub fn assign_cid(
386 mut self,
387 cid: Cid,
388 schema: &dyn SchemaTransaction,
389 ) -> Entry<EntryInvalid, EntryNew> {
390 let ecstate = EntryChangeState::new(&cid, &self.attrs, schema);
396
397 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 pub fn compare(&self, rhs: &Entry<EntrySealed, EntryCommitted>) -> bool {
413 compare_attrs(&self.attrs, &rhs.attrs)
414 }
415
416 #[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 #[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 #[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 #[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 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 pub fn set_ava_set(&mut self, attr: &Attribute, vs: ValueSet) {
506 self.attrs.insert(attr.clone(), vs);
507 }
508
509 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 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 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 let (ecstate, mut attrs) = repl_entry.rehydrate()?;
617
618 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 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 let self_cs = &self.valid.ecstate;
690 let db_cs = db_entry.get_changestate();
691
692 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 _ => 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 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 else {
760 trace!("RI < DE, return RI");
761 let conflict = if at_right.s_uuid == cid.s_uuid {
763 trace!("Origin process conflict entry");
764 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 cnf_ent.set_ava_set(
777 &Attribute::SourceUuid,
778 ValueSetUuidN::new(db_ent.valid.uuid),
779 );
780
781 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 let cv = vs_cid![cid.clone()];
792 let _ = cnf_ent.attrs.insert(Attribute::LastModifiedCid, cv);
793 let cv = vs_cid![cid.clone()];
795 let _ = cnf_ent.attrs.insert(Attribute::CreatedAtCid, cv);
796
797 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 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 _ => 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 debug_assert_eq!(self.valid.uuid, db_ent.valid.uuid);
866
867 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 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 let mut changes = BTreeMap::default();
896 let mut eattrs = Eattrs::default();
897
898 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 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 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 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 }
943 (None, Some(_vs_right)) if take_left => {
944 changes.insert(attr_name.clone(), cid_left.clone());
945 }
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 }
955 (None, None) => {
956 changes.insert(attr_name.clone(), cid_right.clone());
957 }
959 }
960 }
962 (Some(cid_left), None) => {
963 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 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 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 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 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 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 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 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 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 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 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 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 #[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 pub fn to_recycled(mut self) -> Self {
1205 self.add_ava(Attribute::Class, EntryClass::Recycled.into());
1207
1208 Entry {
1212 valid: self.valid,
1213 state: self.state,
1214 attrs: self.attrs,
1215 }
1216 }
1217
1218 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 if let Some(vs) = ValueSetUuidN::from_iter(iter) {
1227 self.set_ava_set(&Attribute::SourceUuid, vs as ValueSet)
1228 };
1229 }
1230
1231 pub fn to_revived(mut self) -> Self {
1233 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 Entry {
1245 valid: self.valid,
1246 state: self.state,
1247 attrs: self.attrs,
1248 }
1249 }
1250}
1251impl Entry<EntryInvalid, EntryNew> {
1254 #[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 #[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 #[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 #[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 #[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 #[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 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 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 #[cfg(test)]
1388 pub fn into_sealed_committed(self) -> Entry<EntrySealed, EntryCommitted> {
1389 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 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 pub fn to_dbentry(&self) -> DbEntry {
1419 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 fn get_name2uuid_cands(&self) -> BTreeSet<String> {
1440 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 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 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 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 pub(crate) fn idx_name2uuid_diff(
1500 pre: Option<&Self>,
1501 post: Option<&Self>,
1502 ) -> (
1503 Option<BTreeSet<String>>,
1505 Option<BTreeSet<String>>,
1507 ) {
1508 match (pre, post) {
1510 (None, None) => {
1511 (None, None)
1513 }
1514 (None, Some(b)) => {
1515 (Some(b.get_name2uuid_cands()), None)
1518 }
1519 (Some(a), None) => {
1520 (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 let add_set: BTreeSet<_> = post_set.difference(&pre_set).cloned().collect();
1529 let rem_set: BTreeSet<_> = pre_set.difference(&post_set).cloned().collect();
1531 (Some(add_set), Some(rem_set))
1532 }
1533 }
1534 }
1535
1536 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 (None, None)
1545 }
1546 (None, Some(b)) => {
1547 (b.get_externalid2uuid(), None)
1549 }
1550 (Some(a), None) => {
1551 (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 (ib, ia)
1561 } else {
1562 (None, None)
1564 }
1565 }
1566 }
1567 }
1568
1569 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 None
1579 }
1580 (None, Some(b)) => {
1581 Some(Ok(b.get_uuid2spn()))
1583 }
1584 (Some(_a), None) => {
1585 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 Some(Ok(ib))
1594 } else {
1595 None
1597 }
1598 }
1599 }
1600 }
1601
1602 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 None
1612 }
1613 (None, Some(b)) => {
1614 Some(Ok(b.get_uuid2rdn()))
1616 }
1617 (Some(_a), None) => {
1618 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 Some(Ok(ib))
1627 } else {
1628 None
1630 }
1631 }
1632 }
1633 }
1634
1635 pub(crate) fn idx_diff<'a>(
1638 idxmeta: &'a HashMap<IdxKey, IdxSlope>,
1639 pre: Option<&Self>,
1640 post: Option<&Self>,
1641 ) -> IdxDiff<'a> {
1642 match (pre, post) {
1647 (None, None) => {
1648 Vec::with_capacity(0)
1650 }
1651 (Some(pre_e), None) => {
1652 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 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 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 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 Vec::with_capacity(0)
1735 }
1736 (Some(pre_vs), None) => {
1737 let changes: Vec<Result<_, _>> = match ikey.itype {
1739 IndexType::Equality => {
1740 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 let changes: Vec<Result<_, _>> = match ikey.itype {
1767 IndexType::Equality => {
1768 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 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 (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 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 } 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 }
1885 };
1886 diff
1888 }
1889 }
1890 })
1891 .collect()
1892 }
1894 }
1895 }
1896
1897 pub fn from_dbentry(db_e: DbEntry, id: u64) -> Option<Self> {
1898 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 .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 #[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 pub fn reduce_attributes(
1955 &self,
1956 allowed_attrs: &BTreeSet<Attribute>,
1957 effective_access: Option<Box<AccessEffectivePermission>>,
1958 ) -> Entry<EntryReduced, EntryCommitted> {
1959 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 pub fn to_tombstone(&self, cid: Cid) -> Entry<EntryInvalid, EntryCommitted> {
1987 let mut ecstate = self.valid.ecstate.clone();
1988 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 ecstate.tombstone(&cid);
2002
2003 Entry {
2004 valid: EntryInvalid { cid, ecstate },
2005 state: self.state.clone(),
2006 attrs: attrs_new,
2007 }
2008 }
2009
2010 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 trace!(?self.attrs, "Entry::validate -> target");
2040
2041 if !self.attribute_pres(Attribute::Class) {
2043 return Err(SchemaError::NoClassFound);
2045 }
2046
2047 if self.attribute_equality(Attribute::Class, &EntryClass::Conflict.into()) {
2048 trace!("Skipping schema validation on conflict entry");
2050 return Ok(());
2051 };
2052
2053 let recycled = self.attribute_equality(Attribute::Class, &EntryClass::Recycled.into());
2055
2056 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 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 let supplements_classes: Vec<_> = classes
2094 .iter()
2095 .flat_map(|cls| cls.systemsupplements.iter().chain(cls.supplements.iter()))
2096 .collect();
2097
2098 let valid_supplements = if supplements_classes.is_empty() {
2100 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 let must: Result<Vec<&SchemaAttribute>, _> = classes
2151 .iter()
2152 .flat_map(|cls| cls.systemmust.iter().chain(cls.must.iter()))
2154 .map(|s| {
2155 schema_attributes.get(s).ok_or(SchemaError::Corrupted)
2158 })
2159 .collect();
2160
2161 let must = must?;
2162
2163 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 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 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 }
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 let may: Result<Map<&Attribute, &SchemaAttribute>, _> = classes
2225 .iter()
2226 .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 Ok((s, schema_attributes.get(s).ok_or(SchemaError::Corrupted)?))
2239 })
2240 .collect();
2241
2242 let may = may?;
2243
2244 self.attrs.iter().try_for_each(|(attr_name, avas)| {
2253 match may.get(attr_name) {
2254 Some(a_schema) => {
2255 a_schema.validate_ava(attr_name, avas)
2258 }
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 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 ecstate.retain(|k, _| schema.is_replicated(k));
2288
2289 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 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 for vs in self.attrs.values_mut() {
2329 vs.trim(trim_cid);
2330 }
2331
2332 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 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 *change_attr != Attribute::LastModifiedCid
2384 })
2385 }
2386 State::Tombstone { at } => at == cid,
2387 }
2388 }
2389
2390 #[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 pub fn to_pe(&self, qs: &mut QueryServerReadTransaction) -> Result<ProtoEntry, OperationError> {
2421 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 .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 let schemas = Vec::with_capacity(0);
2480
2481 Ok(ScimEntryKanidm {
2482 header: ScimEntryHeader {
2483 schemas,
2484 id,
2485 external_id: None,
2487 meta: None,
2490 },
2491 ext_access_check,
2492 attrs,
2493 })
2494 }
2495
2496 pub fn to_ldap(
2498 &self,
2499 qs: &mut QueryServerReadTransaction,
2500 basedn: &str,
2501 all_attrs: bool,
2503 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 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 let attr_names: Vec<(&str, &str)> = if all_attrs {
2528 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 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 let attributes: Vec<_> = attr_names
2548 .into_iter()
2549 .filter_map(|(ldap_a, kani_a)| {
2550 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 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 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 true
2612 }
2613 }
2615
2616 fn set_ava_int(&mut self, attr: Attribute, vs: ValueSet) {
2617 if let Some(existing_vs) = self.attrs.get_mut(&attr) {
2618 let _ = existing_vs.merge(&vs);
2620 } else {
2621 self.attrs.insert(attr, vs);
2623 }
2624 }
2625
2626 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 #[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 .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 pub fn get_ava_names(&self) -> impl Iterator<Item = &str> {
2685 self.attrs.keys().map(|a| a.as_str())
2687 }
2688
2689 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 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 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 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 pub fn get_ava_as_refuuid<A: AsRef<Attribute>>(
2809 &self,
2810 attr: A,
2811 ) -> Option<Box<dyn Iterator<Item = Uuid> + '_>> {
2812 self.get_ava_set(attr).and_then(|vs| vs.as_ref_uuid_iter())
2814 }
2815
2816 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub(crate) fn generate_spn(&self, domain_name: &str) -> Option<ValueSet> {
2971 if let Some(name) = self.get_ava_single_iname(Attribute::Name) {
2972 return Some(ValueSetSpn::new((name.into(), domain_name.into())));
2974 }
2975
2976 let spn_set = self.get_ava_set(Attribute::Spn)?;
2978
2979 if spn_set.syntax() == SyntaxType::SecurityPrincipalName {
2980 Some(spn_set.clone())
2982 } else if let Some(name) = spn_set.to_iname_single() {
2983 Some(ValueSetSpn::new((name.into(), domain_name.into())))
2985 } else {
2986 None
2988 }
2989 }
2990
2991 pub fn attribute_pres<A: AsRef<Attribute>>(&self, attr: A) -> bool {
2993 self.attrs.contains_key(attr.as_ref())
2994 }
2995
2996 pub fn attribute_equality<A: AsRef<Attribute>>(&self, attr: A, value: &PartialValue) -> bool {
2999 match self.attrs.get(attr.as_ref()) {
3004 Some(v_list) => v_list.contains(value),
3005 None => false,
3006 }
3007 }
3008
3009 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 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 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 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 #[inline(always)]
3062 #[instrument(level = "trace", name = "entry::entry_match_no_index", skip(self))]
3063 pub fn entry_match_no_index(&self, filter: &Filter<FilterValidResolved>) -> bool {
3065 self.entry_match_no_index_inner(filter.to_inner())
3066 }
3067
3068 fn entry_match_no_index_inner(&self, filter: &FilterResolved) -> bool {
3072 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 FilterResolved::Or(l, _) => l.iter().any(|f| self.entry_match_no_index_inner(f)),
3083 FilterResolved::And(l, _) => l.iter().all(|f| self.entry_match_no_index_inner(f)),
3085 FilterResolved::Inclusion(_, _) => {
3086 false
3090 }
3091 FilterResolved::AndNot(f, _) => !self.entry_match_no_index_inner(f),
3092 FilterResolved::Invalid(_) => false,
3093 }
3094 }
3095
3096 pub fn filter_from_attrs(&self, attrs: &[Attribute]) -> Option<Filter<FilterInvalid>> {
3099 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 pub fn gen_modlist_assert(
3131 &self,
3132 schema: &dyn SchemaTransaction,
3133 ) -> Result<ModifyList<ModifyInvalid>, SchemaError> {
3134 let mut mods = ModifyList::new();
3138
3139 for (k, vs) in self.attrs.iter() {
3140 if *k == Attribute::Uuid {
3156 continue;
3157 }
3158 {
3160 let r = schema.is_multivalue(k)?;
3161 if !r ||
3164 *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 pub fn mask_recycled_ts(&self) -> Option<&Self> {
3189 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 pub fn mask_recycled(&self) -> Option<&Self> {
3207 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 pub fn mask_tombstone(&self) -> Option<&Self> {
3223 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 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 if self.add_ava_int(attr_ref.clone(), value) {
3254 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 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 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 let can_remove = self
3317 .attrs
3318 .get_mut(attr_ref)
3319 .map(|vs| vs.purge(&self.valid.cid))
3320 .unwrap_or_default();
3322 if can_remove {
3323 self.attrs.remove(attr_ref);
3324 }
3325 }
3326
3327 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 Some(vs)
3336 } else {
3337 let r_vs = vs.clone();
3339 self.attrs.insert(attr_ref.clone(), vs);
3340 Some(r_vs)
3341 }
3342 }
3343
3344 #[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 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 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 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 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 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 compare_attrs(&self.attrs, &rhs.attrs)
3454 }
3455}
3456
3457pub(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 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 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 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 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!(e.attribute_equality(Attribute::UserId, &PartialValue::new_utf8s("william")));
3596 assert!(e.attribute_equality(Attribute::Attr, &PartialValue::new_iutf8("value")));
3597
3598 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 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 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 let r1 = Entry::idx_diff(&idxmeta, None, None);
3683 eprintln!("{r1:?}");
3684 assert_eq!(r1, Vec::with_capacity(0));
3685
3686 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 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 let no_r = Entry::idx_diff(&idxmeta, Some(&e1), Some(&e1));
3718 assert!(no_r.is_empty());
3719
3720 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 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 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 let r = Entry::idx_name2uuid_diff(None, None);
3774 assert_eq!(r, (None, None));
3775
3776 {
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 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 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 assert!(
3828 Entry::idx_name2uuid_diff(Some(&e), Some(&e))
3829 == (Some(Set::new()), Some(Set::new()))
3830 );
3831 }
3832 {
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 assert!(
3854 Entry::idx_name2uuid_diff(Some(&e1), Some(&e2))
3855 == (Some(btreeset!["testperson".to_string()]), Some(Set::new()))
3856 );
3857
3858 assert!(
3860 Entry::idx_name2uuid_diff(Some(&e2), Some(&e1))
3861 == (Some(Set::new()), Some(btreeset!["testperson".to_string()]))
3862 );
3863 }
3864
3865 {
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}