1use crate::{be::IdxKey, migration_data, prelude::*, valueset::ValueSet};
15use concread::cowcell::*;
16use hashbrown::{HashMap, HashSet};
17use std::collections::BTreeSet;
18use tracing::trace;
19use uuid::Uuid;
20
21pub struct Schema {
38 classes: CowCell<HashMap<AttrString, SchemaClass>>,
39 attributes: CowCell<HashMap<Attribute, SchemaAttribute>>,
40 unique_cache: CowCell<Vec<Attribute>>,
41 ref_cache: CowCell<HashMap<Attribute, SchemaAttribute>>,
42}
43
44pub struct SchemaWriteTransaction<'a> {
48 classes: CowCellWriteTxn<'a, HashMap<AttrString, SchemaClass>>,
49 attributes: CowCellWriteTxn<'a, HashMap<Attribute, SchemaAttribute>>,
50
51 unique_cache: CowCellWriteTxn<'a, Vec<Attribute>>,
52 ref_cache: CowCellWriteTxn<'a, HashMap<Attribute, SchemaAttribute>>,
53}
54
55pub struct SchemaReadTransaction {
57 classes: CowCellReadTxn<HashMap<AttrString, SchemaClass>>,
58 attributes: CowCellReadTxn<HashMap<Attribute, SchemaAttribute>>,
59
60 unique_cache: CowCellReadTxn<Vec<Attribute>>,
61 ref_cache: CowCellReadTxn<HashMap<Attribute, SchemaAttribute>>,
62}
63
64#[derive(Debug, Clone, Copy, Default)]
65pub enum Replicated {
66 #[default]
67 True,
68 False,
69}
70
71impl From<Replicated> for bool {
72 fn from(value: Replicated) -> bool {
73 match value {
74 Replicated::True => true,
75 Replicated::False => false,
76 }
77 }
78}
79
80impl From<bool> for Replicated {
81 fn from(value: bool) -> Self {
82 match value {
83 true => Replicated::True,
84 false => Replicated::False,
85 }
86 }
87}
88
89#[derive(Debug, Clone, Default)]
97pub struct SchemaAttribute {
98 pub name: Attribute,
99 pub uuid: Uuid,
100 pub description: String,
101 pub multivalue: bool,
103 pub unique: bool,
105 pub phantom: bool,
109 pub sync_allowed: bool,
112
113 pub replicated: Replicated,
115 pub indexed: bool,
117 pub syntax: SyntaxType,
119}
120
121impl SchemaAttribute {
122 pub fn try_from(value: &Entry<EntrySealed, EntryCommitted>) -> Result<Self, OperationError> {
123 let uuid = value.get_uuid();
127
128 if !value.attribute_equality(Attribute::Class, &EntryClass::AttributeType.into()) {
130 admin_error!(
131 "class {} not present - {:?}",
132 EntryClass::AttributeType,
133 uuid
134 );
135 return Err(OperationError::InvalidSchemaState(format!(
136 "missing {}",
137 EntryClass::AttributeType
138 )));
139 }
140
141 let name = value
143 .get_ava_single_iutf8(Attribute::AttributeName)
144 .map(|s| s.into())
145 .ok_or_else(|| {
146 admin_error!("missing {} - {:?}", Attribute::AttributeName, uuid);
147 OperationError::InvalidSchemaState("missing attributename".to_string())
148 })?;
149 let description = value
151 .get_ava_single_utf8(Attribute::Description)
152 .map(|s| s.to_string())
153 .ok_or_else(|| {
154 admin_error!("missing {} - {}", Attribute::Description, name);
155 OperationError::InvalidSchemaState("missing description".to_string())
156 })?;
157
158 let multivalue = value
160 .get_ava_single_bool(Attribute::MultiValue)
161 .ok_or_else(|| {
162 admin_error!("missing {} - {}", Attribute::MultiValue, name);
163 OperationError::InvalidSchemaState("missing multivalue".to_string())
164 })?;
165
166 let unique = value
167 .get_ava_single_bool(Attribute::Unique)
168 .ok_or_else(|| {
169 admin_error!("missing {} - {}", Attribute::Unique, name);
170 OperationError::InvalidSchemaState("missing unique".to_string())
171 })?;
172
173 let phantom = value
174 .get_ava_single_bool(Attribute::Phantom)
175 .unwrap_or_default();
176
177 let sync_allowed = value
178 .get_ava_single_bool(Attribute::SyncAllowed)
179 .unwrap_or_default();
180
181 let replicated = value
184 .get_ava_single_bool(Attribute::Replicated)
185 .map(Replicated::from)
186 .unwrap_or_default();
187
188 let indexed = value
189 .get_ava_single_bool(Attribute::Indexed)
190 .unwrap_or_default();
191
192 let syntax = value
194 .get_ava_single_syntax(Attribute::Syntax)
195 .ok_or_else(|| {
196 admin_error!("missing {} - {}", Attribute::Syntax, name);
197 OperationError::InvalidSchemaState(format!("missing {}", Attribute::Syntax))
198 })?;
199
200 trace!(?name, ?indexed);
201
202 Ok(SchemaAttribute {
203 name,
204 uuid,
205 description,
206 multivalue,
207 unique,
208 phantom,
209 sync_allowed,
210 replicated,
211 indexed,
212 syntax,
213 })
214 }
215
216 pub fn validate_partialvalue(
220 &self,
221 a: &Attribute,
222 v: &PartialValue,
223 ) -> Result<(), SchemaError> {
224 let r = match self.syntax {
225 SyntaxType::Boolean => matches!(v, PartialValue::Bool(_)),
226 SyntaxType::SyntaxId => matches!(v, PartialValue::Syntax(_)),
227 SyntaxType::IndexId => matches!(v, PartialValue::Index(_)),
228 SyntaxType::Uuid | SyntaxType::UuidN => {
229 matches!(v, PartialValue::Uuid(_))
230 }
231 SyntaxType::ReferenceUuidN | SyntaxType::ReferenceUuid => {
232 matches!(v, PartialValue::Refer(_))
233 }
234 SyntaxType::Utf8StringInsensitiveN | SyntaxType::Utf8StringInsensitive => {
235 matches!(v, PartialValue::Iutf8(_))
236 }
237 SyntaxType::Utf8StringInameN | SyntaxType::Utf8StringIname => {
238 matches!(v, PartialValue::Iname(_))
239 }
240 SyntaxType::Utf8String => matches!(v, PartialValue::Utf8(_)),
241 SyntaxType::JsonFilter => matches!(v, PartialValue::JsonFilt(_)),
242 SyntaxType::Credential => matches!(v, PartialValue::Cred(_)),
243 SyntaxType::SecretUtf8String => matches!(v, PartialValue::SecretValue),
244 SyntaxType::SshKey => matches!(v, PartialValue::SshKey(_)),
245 SyntaxType::SecurityPrincipalName => matches!(v, PartialValue::Spn(_, _)),
246 SyntaxType::Uint32 => matches!(v, PartialValue::Uint32(_)),
247 SyntaxType::Int64 => matches!(v, PartialValue::Int64(_)),
248 SyntaxType::Uint64 => matches!(v, PartialValue::Uint64(_)),
249 SyntaxType::Cid => matches!(v, PartialValue::Cid(_)),
250 SyntaxType::NsUniqueId => matches!(v, PartialValue::Nsuniqueid(_)),
251 SyntaxType::DateTime => matches!(v, PartialValue::DateTime(_)),
252 SyntaxType::EmailAddress => matches!(v, PartialValue::EmailAddress(_)),
253 SyntaxType::UrlN | SyntaxType::Url => matches!(v, PartialValue::Url(_)),
254 SyntaxType::OauthScope => matches!(v, PartialValue::OauthScope(_)),
255 SyntaxType::OauthScopeMap => matches!(v, PartialValue::Refer(_)),
256 SyntaxType::OauthClaimMap => {
257 matches!(v, PartialValue::Iutf8(_))
258 || matches!(v, PartialValue::Refer(_))
259 || matches!(v, PartialValue::OauthClaimValue(_, _, _))
260 || matches!(v, PartialValue::OauthClaim(_, _))
261 }
262 SyntaxType::PrivateBinary => matches!(v, PartialValue::PrivateBinary),
263 SyntaxType::IntentToken => matches!(v, PartialValue::IntentToken(_)),
264 SyntaxType::Passkey => matches!(v, PartialValue::Passkey(_)),
265 SyntaxType::AttestedPasskey => matches!(v, PartialValue::AttestedPasskey(_)),
266 SyntaxType::Session => matches!(v, PartialValue::Refer(_)),
268 SyntaxType::ApiToken => matches!(v, PartialValue::Refer(_)),
269 SyntaxType::Oauth2Session => matches!(v, PartialValue::Refer(_)),
270 SyntaxType::JwsKeyEs256 => matches!(v, PartialValue::Iutf8(_)),
272 SyntaxType::JwsKeyRs256 => matches!(v, PartialValue::Iutf8(_)),
273 SyntaxType::UiHint => matches!(v, PartialValue::UiHint(_)),
274 SyntaxType::EcKeyPrivate => matches!(v, PartialValue::SecretValue),
275 SyntaxType::TotpSecret => matches!(v, PartialValue::Utf8(_)),
277 SyntaxType::AuditLogString => matches!(v, PartialValue::Utf8(_)),
278 SyntaxType::Image => matches!(v, PartialValue::Utf8(_)),
279 SyntaxType::CredentialType => matches!(v, PartialValue::CredentialType(_)),
280
281 SyntaxType::HexString | SyntaxType::Certificate | SyntaxType::KeyInternal => {
282 matches!(v, PartialValue::HexString(_))
283 }
284
285 SyntaxType::WebauthnAttestationCaList => false,
286 SyntaxType::ApplicationPassword => {
287 matches!(v, PartialValue::Uuid(_)) || matches!(v, PartialValue::Refer(_))
288 }
289 SyntaxType::Sha256 => matches!(v, PartialValue::Sha256(_)),
290 SyntaxType::Json | SyntaxType::Message => false,
293 };
294 if r {
295 Ok(())
296 } else {
297 error!(
298 ?a,
299 ?self,
300 ?v,
301 "validate_partialvalue InvalidAttributeSyntax"
302 );
303 Err(SchemaError::InvalidAttributeSyntax(a.to_string()))
304 }
305 }
306
307 pub fn validate_value(&self, a: &Attribute, v: &Value) -> Result<(), SchemaError> {
308 let r = v.validate()
309 && match self.syntax {
310 SyntaxType::Boolean => matches!(v, Value::Bool(_)),
311 SyntaxType::SyntaxId => matches!(v, Value::Syntax(_)),
312 SyntaxType::IndexId => matches!(v, Value::Index(_)),
313 SyntaxType::Uuid => matches!(v, Value::Uuid(_)),
314 SyntaxType::ReferenceUuidN => {
315 matches!(v, Value::ReferN(_))
316 }
317 SyntaxType::ReferenceUuid => {
318 matches!(v, Value::Refer(_))
319 }
320 SyntaxType::Utf8StringInsensitiveN => {
321 matches!(v, Value::Iutf8N(_))
322 }
328 SyntaxType::Utf8StringInsensitive => {
329 matches!(v, Value::Iutf8(_))
330 }
331 SyntaxType::Utf8StringInameN => {
332 matches!(v, Value::InameN(_))
333 }
334 SyntaxType::Utf8StringIname => {
335 matches!(v, Value::Iname(_))
336 }
337 SyntaxType::Utf8String => matches!(v, Value::Utf8(_)),
338 SyntaxType::JsonFilter => matches!(v, Value::JsonFilt(_)),
339 SyntaxType::Credential => matches!(v, Value::Cred(_, _)),
340 SyntaxType::SecretUtf8String => matches!(v, Value::SecretValue(_)),
341 SyntaxType::SshKey => matches!(v, Value::SshKey(_, _)),
342 SyntaxType::SecurityPrincipalName => matches!(v, Value::Spn(_, _)),
343 SyntaxType::Uint32 => matches!(v, Value::Uint32(_)),
344 SyntaxType::Int64 => matches!(v, Value::Int64(_)),
345 SyntaxType::Uint64 => matches!(v, Value::Uint64(_)),
346 SyntaxType::Cid => matches!(v, Value::Cid(_)),
347 SyntaxType::NsUniqueId => matches!(v, Value::Nsuniqueid(_)),
348 SyntaxType::DateTime => matches!(v, Value::DateTime(_)),
349 SyntaxType::EmailAddress => matches!(v, Value::EmailAddress(_, _)),
350 SyntaxType::UrlN => matches!(v, Value::UrlN(_)),
351 SyntaxType::Url => matches!(v, Value::Url(_)),
352 SyntaxType::OauthScope => matches!(v, Value::OauthScope(_)),
353 SyntaxType::OauthScopeMap => matches!(v, Value::OauthScopeMap(_, _)),
354 SyntaxType::OauthClaimMap => {
355 matches!(v, Value::OauthClaimValue(_, _, _))
356 || matches!(v, Value::OauthClaimMap(_, _))
357 }
358 SyntaxType::PrivateBinary => matches!(v, Value::PrivateBinary(_)),
359 SyntaxType::IntentToken => matches!(v, Value::IntentToken(_, _)),
360 SyntaxType::Passkey => matches!(v, Value::Passkey(_, _, _)),
361 SyntaxType::AttestedPasskey => matches!(v, Value::AttestedPasskey(_, _, _)),
362 SyntaxType::Session => matches!(v, Value::Session(_, _)),
363 SyntaxType::ApiToken => matches!(v, Value::ApiToken(_, _)),
364 SyntaxType::Oauth2Session => matches!(v, Value::Oauth2Session(_, _)),
365 SyntaxType::JwsKeyEs256 => matches!(v, Value::JwsKeyEs256(_)),
366 SyntaxType::JwsKeyRs256 => matches!(v, Value::JwsKeyRs256(_)),
367 SyntaxType::UiHint => matches!(v, Value::UiHint(_)),
368 SyntaxType::TotpSecret => matches!(v, Value::TotpSecret(_, _)),
369 SyntaxType::AuditLogString => matches!(v, Value::Utf8(_)),
370 SyntaxType::Image => matches!(v, Value::Image(_)),
371 SyntaxType::CredentialType => matches!(v, Value::CredentialType(_)),
372 SyntaxType::WebauthnAttestationCaList => {
373 matches!(v, Value::WebauthnAttestationCaList(_))
374 }
375 SyntaxType::KeyInternal => matches!(v, Value::KeyInternal { .. }),
376 SyntaxType::HexString => matches!(v, Value::HexString(_)),
377 SyntaxType::Certificate => matches!(v, Value::Certificate(_)),
378 SyntaxType::ApplicationPassword => matches!(v, Value::ApplicationPassword(..)),
379 SyntaxType::Json => matches!(v, Value::Json(_)),
380 SyntaxType::Sha256 => matches!(v, Value::Sha256(_)),
381 SyntaxType::EcKeyPrivate => matches!(v, Value::SecretValue(_)),
382 SyntaxType::UuidN | SyntaxType::Message => false,
383 };
384 if r {
385 Ok(())
386 } else {
387 error!(
388 ?a,
389 ?self,
390 ?v,
391 "validate_value failure - InvalidAttributeSyntax"
392 );
393 Err(SchemaError::InvalidAttributeSyntax(a.to_string()))
394 }
395 }
396
397 pub fn validate_ava(&self, a: &Attribute, ava: &ValueSet) -> Result<(), SchemaError> {
398 trace!("Checking for valid {:?} -> {:?}", self.name, ava);
399 if !self.multivalue && ava.len() > 1 {
401 error!("Ava len > 1 on single value attribute!");
403 return Err(SchemaError::InvalidAttributeSyntax(a.to_string()));
404 };
405 let valid = if DOMAIN_TGT_LEVEL <= DOMAIN_LEVEL_1_12 {
410 match self.syntax {
411 SyntaxType::Uuid => {
414 SyntaxType::UuidN == ava.syntax() || SyntaxType::Uuid == ava.syntax()
415 }
416 SyntaxType::Utf8StringInsensitive => {
417 SyntaxType::Utf8StringInsensitiveN == ava.syntax()
418 || SyntaxType::Utf8StringInsensitive == ava.syntax()
419 }
420 SyntaxType::ReferenceUuid => {
421 SyntaxType::ReferenceUuidN == ava.syntax()
422 || SyntaxType::ReferenceUuid == ava.syntax()
423 }
424 SyntaxType::Utf8StringIname => {
425 SyntaxType::Utf8StringInameN == ava.syntax()
426 || SyntaxType::Utf8StringIname == ava.syntax()
427 }
428 SyntaxType::Url => {
429 SyntaxType::UrlN == ava.syntax() || SyntaxType::Url == ava.syntax()
430 }
431 _ => self.syntax == ava.syntax(),
432 }
433 } else {
434 self.syntax == ava.syntax()
435 };
436
437 if valid && ava.validate(self) {
438 Ok(())
439 } else {
440 error!(
441 ?a,
442 "validate_ava - InvalidAttributeSyntax for {:?}", self.syntax
443 );
444 Err(SchemaError::InvalidAttributeSyntax(a.to_string()))
445 }
446 }
447}
448
449#[derive(Debug, Clone, Default)]
467pub struct SchemaClass {
468 pub name: AttrString,
469 pub uuid: Uuid,
470 pub description: String,
471 pub sync_allowed: bool,
472 pub systemmay: Vec<Attribute>,
474 pub may: Vec<Attribute>,
475 pub systemmust: Vec<Attribute>,
476 pub must: Vec<Attribute>,
477 pub systemsupplements: Vec<AttrString>,
482 pub supplements: Vec<AttrString>,
483 pub systemexcludes: Vec<AttrString>,
485 pub excludes: Vec<AttrString>,
486}
487
488impl SchemaClass {
489 pub fn try_from(value: &Entry<EntrySealed, EntryCommitted>) -> Result<Self, OperationError> {
490 let uuid = value.get_uuid();
492 if !value.attribute_equality(Attribute::Class, &EntryClass::ClassType.into()) {
494 error!("class classtype not present - {:?}", uuid);
495 return Err(OperationError::InvalidSchemaState(
496 "missing classtype".to_string(),
497 ));
498 }
499
500 let name = value
502 .get_ava_single_iutf8(Attribute::ClassName)
503 .map(AttrString::from)
504 .ok_or_else(|| {
505 error!("missing {} - {:?}", Attribute::ClassName, uuid);
506 OperationError::InvalidSchemaState(format!("missing {}", Attribute::ClassName))
507 })?;
508
509 let description = value
511 .get_ava_single_utf8(Attribute::Description)
512 .map(String::from)
513 .ok_or_else(|| {
514 error!("missing {} - {}", Attribute::Description, name);
515 OperationError::InvalidSchemaState(format!("missing {}", Attribute::Description))
516 })?;
517
518 let sync_allowed = value
519 .get_ava_single_bool(Attribute::SyncAllowed)
520 .unwrap_or(false);
521
522 let systemmay = value
524 .get_ava_iter_iutf8(Attribute::SystemMay)
525 .into_iter()
526 .flat_map(|iter| iter.map(Attribute::from))
527 .collect();
528 let systemmust = value
529 .get_ava_iter_iutf8(Attribute::SystemMust)
530 .into_iter()
531 .flat_map(|iter| iter.map(Attribute::from))
532 .collect();
533 let may = value
534 .get_ava_iter_iutf8(Attribute::May)
535 .into_iter()
536 .flat_map(|iter| iter.map(Attribute::from))
537 .collect();
538 let must = value
539 .get_ava_iter_iutf8(Attribute::Must)
540 .into_iter()
541 .flat_map(|iter| iter.map(Attribute::from))
542 .collect();
543
544 let systemsupplements = value
545 .get_ava_iter_iutf8(Attribute::SystemSupplements)
546 .map(|i| i.map(|v| v.into()).collect())
547 .unwrap_or_default();
548 let supplements = value
549 .get_ava_iter_iutf8(Attribute::Supplements)
550 .map(|i| i.map(|v| v.into()).collect())
551 .unwrap_or_default();
552 let systemexcludes = value
553 .get_ava_iter_iutf8(Attribute::SystemExcludes)
554 .map(|i| i.map(|v| v.into()).collect())
555 .unwrap_or_default();
556 let excludes = value
557 .get_ava_iter_iutf8(Attribute::Excludes)
558 .map(|i| i.map(|v| v.into()).collect())
559 .unwrap_or_default();
560
561 Ok(SchemaClass {
562 name,
563 uuid,
564 description,
565 sync_allowed,
566 systemmay,
567 may,
568 systemmust,
569 must,
570 systemsupplements,
571 supplements,
572 systemexcludes,
573 excludes,
574 })
575 }
576
577 pub fn may_iter(&self) -> impl Iterator<Item = &Attribute> {
580 self.systemmay
581 .iter()
582 .chain(self.may.iter())
583 .chain(self.systemmust.iter())
584 .chain(self.must.iter())
585 }
586}
587
588pub trait SchemaTransaction {
589 fn get_classes(&self) -> &HashMap<AttrString, SchemaClass>;
590 fn get_attributes(&self) -> &HashMap<Attribute, SchemaAttribute>;
591
592 fn get_attributes_unique(&self) -> &Vec<Attribute>;
593 fn get_reference_types(&self) -> &HashMap<Attribute, SchemaAttribute>;
594
595 fn validate(&self) -> Vec<Result<(), ConsistencyError>> {
596 let mut res = Vec::with_capacity(0);
597
598 let class_snapshot = self.get_classes();
599 let attribute_snapshot = self.get_attributes();
600
601 let mut unique_uuid_set = HashSet::new();
606 class_snapshot
607 .values()
608 .map(|class| &class.uuid)
609 .chain(attribute_snapshot.values().map(|attr| &attr.uuid))
610 .for_each(|uuid| {
611 if !unique_uuid_set.insert(uuid) {
613 res.push(Err(ConsistencyError::SchemaUuidNotUnique(*uuid)))
614 }
615 });
616
617 class_snapshot.values().for_each(|class| {
618 class
620 .systemmay
621 .iter()
622 .chain(class.may.iter())
623 .chain(class.systemmust.iter())
624 .chain(class.must.iter())
625 .for_each(|a| {
626 match attribute_snapshot.get(a) {
627 Some(attr) => {
628 if attr.phantom {
630 res.push(Err(ConsistencyError::SchemaClassPhantomAttribute(
631 class.name.to_string(),
632 a.to_string(),
633 )))
634 }
635 }
636 None => {
637 res.push(Err(ConsistencyError::SchemaClassMissingAttribute(
639 class.name.to_string(),
640 a.to_string(),
641 )))
642 }
643 }
644 })
645 }); res
647 }
648
649 fn is_replicated(&self, attr: &Attribute) -> bool {
650 match self.get_attributes().get(attr) {
651 Some(a_schema) => {
652 a_schema.replicated.into() && !a_schema.phantom
655 }
656 None => {
657 warn!(
658 "Attribute {} was not found in schema during replication request",
659 attr
660 );
661 false
662 }
663 }
664 }
665
666 fn is_multivalue(&self, attr: &Attribute) -> Result<bool, SchemaError> {
667 match self.get_attributes().get(attr) {
668 Some(a_schema) => Ok(a_schema.multivalue),
669 None => {
670 Err(SchemaError::InvalidAttribute(attr.to_string()))
672 }
673 }
674 }
675
676 fn normalise_attr_if_exists(&self, an: &str) -> Option<Attribute> {
677 let attr = Attribute::from(an);
678 if self.get_attributes().contains_key(&attr) {
679 Some(attr)
680 } else {
681 None
682 }
683 }
684
685 fn query_attrs_difference(
686 &self,
687 prev_class: &BTreeSet<&str>,
688 new_iutf8: &BTreeSet<&str>,
689 ) -> Result<(BTreeSet<&str>, BTreeSet<&str>), SchemaError> {
690 let schema_classes = self.get_classes();
691
692 let mut invalid_classes = Vec::with_capacity(0);
693
694 let prev_attrs: BTreeSet<&str> = prev_class
695 .iter()
696 .filter_map(|cls| match schema_classes.get(*cls) {
697 Some(x) => Some(x.may_iter()),
698 None => {
699 admin_debug!("invalid class: {:?}", cls);
700 invalid_classes.push(cls.to_string());
701 None
702 }
703 })
704 .flatten()
706 .map(|s| s.as_str())
707 .collect();
708
709 if !invalid_classes.is_empty() {
710 return Err(SchemaError::InvalidClass(invalid_classes));
711 };
712
713 let new_attrs: BTreeSet<&str> = new_iutf8
714 .iter()
715 .filter_map(|cls| match schema_classes.get(*cls) {
716 Some(x) => Some(x.may_iter()),
717 None => {
718 admin_debug!("invalid class: {:?}", cls);
719 invalid_classes.push(cls.to_string());
720 None
721 }
722 })
723 .flatten()
725 .map(|s| s.as_str())
726 .collect();
727
728 if !invalid_classes.is_empty() {
729 return Err(SchemaError::InvalidClass(invalid_classes));
730 };
731
732 let removed = prev_attrs.difference(&new_attrs).copied().collect();
733 let added = new_attrs.difference(&prev_attrs).copied().collect();
734
735 Ok((added, removed))
736 }
737}
738
739impl SchemaWriteTransaction<'_> {
740 pub fn commit(self) -> Result<(), OperationError> {
746 let SchemaWriteTransaction {
747 classes,
748 attributes,
749 unique_cache,
750 ref_cache,
751 } = self;
752
753 unique_cache.commit();
754 ref_cache.commit();
755 classes.commit();
756 attributes.commit();
757 Ok(())
758 }
759
760 pub fn update_attributes<I: Iterator<Item = SchemaAttribute>>(
761 &mut self,
762 attributetypes: I,
763 ) -> Result<(), OperationError> {
764 self.attributes.clear();
766
767 self.unique_cache.clear();
768 self.ref_cache.clear();
769 attributetypes.for_each(|a| {
773 if a.syntax == SyntaxType::ReferenceUuid ||
775 a.syntax == SyntaxType::ReferenceUuidN ||
776 a.syntax == SyntaxType::OauthScopeMap ||
777 a.syntax == SyntaxType::OauthClaimMap ||
778 a.syntax == SyntaxType::Oauth2Session ||
780 a.syntax == SyntaxType::ApplicationPassword
782 {
785 self.ref_cache.insert(a.name.clone(), a.clone());
786 }
787 if a.unique {
788 self.unique_cache.push(a.name.clone());
789 }
790 self.attributes.insert(a.name.clone(), a);
792 });
793
794 Ok(())
795 }
796
797 pub fn update_classes<I: Iterator<Item = SchemaClass>>(
798 &mut self,
799 classtypes: I,
800 ) -> Result<(), OperationError> {
801 self.classes.clear();
803 classtypes.into_iter().for_each(|a| {
807 self.classes.insert(a.name.clone(), a);
808 });
809 Ok(())
810 }
811
812 pub fn to_entries(&self) -> Vec<Entry<EntryInit, EntryNew>> {
813 let r: Vec<_> = self
814 .attributes
815 .values()
816 .map(Entry::<EntryInit, EntryNew>::from)
817 .chain(
818 self.classes
819 .values()
820 .map(Entry::<EntryInit, EntryNew>::from),
821 )
822 .collect();
823 r
824 }
825
826 pub fn reload_idxmeta(&self) -> Vec<IdxKey> {
827 self.get_attributes()
828 .values()
829 .flat_map(|a| {
830 if a.indexed || a.unique {
832 a.syntax.index_types()
833 } else {
834 &[]
835 }
836 .iter()
837 .map(move |itype: &IndexType| IdxKey {
838 attr: a.name.clone(),
839 itype: *itype,
840 })
841 })
842 .collect()
843 }
844
845 #[instrument(level = "debug", name = "schema::generate_in_memory", skip_all)]
854 pub fn generate_in_memory(&mut self) -> Result<(), OperationError> {
855 self.update_attributes(migration_data::system::attributes().into_iter())?;
858 self.update_classes(migration_data::system::classes().into_iter())?;
859
860 let r = self.validate();
861 if r.is_empty() {
862 debug!("schema validate -> passed");
863 Ok(())
864 } else {
865 error!(err = ?r, "schema validate -> errors");
866 Err(OperationError::ConsistencyError(
867 r.into_iter().filter_map(|v| v.err()).collect(),
868 ))
869 }
870 }
871
872 #[instrument(level = "debug", name = "schema::extend_in_memory", skip_all)]
873 pub fn extend_in_memory(
874 &mut self,
875 extra_attrs: Vec<SchemaAttribute>,
876 extra_classes: Vec<SchemaClass>,
877 ) -> Result<(), OperationError> {
878 self.update_attributes(
879 migration_data::system::attributes()
880 .into_iter()
881 .chain(extra_attrs.into_iter()),
882 )?;
883 self.update_classes(
884 migration_data::system::classes()
885 .into_iter()
886 .chain(extra_classes.into_iter()),
887 )?;
888
889 let r = self.validate();
890 if r.is_empty() {
891 debug!("schema validate -> passed");
892 Ok(())
893 } else {
894 error!(err = ?r, "schema validate -> errors");
895 Err(OperationError::ConsistencyError(
896 r.into_iter().filter_map(|v| v.err()).collect(),
897 ))
898 }
899 }
900}
901
902impl SchemaTransaction for SchemaWriteTransaction<'_> {
903 fn get_attributes_unique(&self) -> &Vec<Attribute> {
904 &self.unique_cache
905 }
906
907 fn get_reference_types(&self) -> &HashMap<Attribute, SchemaAttribute> {
908 &self.ref_cache
909 }
910
911 fn get_classes(&self) -> &HashMap<AttrString, SchemaClass> {
912 &self.classes
913 }
914
915 fn get_attributes(&self) -> &HashMap<Attribute, SchemaAttribute> {
916 &self.attributes
917 }
918}
919
920impl SchemaTransaction for SchemaReadTransaction {
921 fn get_attributes_unique(&self) -> &Vec<Attribute> {
922 &self.unique_cache
923 }
924
925 fn get_reference_types(&self) -> &HashMap<Attribute, SchemaAttribute> {
926 &self.ref_cache
927 }
928
929 fn get_classes(&self) -> &HashMap<AttrString, SchemaClass> {
930 &self.classes
931 }
932
933 fn get_attributes(&self) -> &HashMap<Attribute, SchemaAttribute> {
934 &self.attributes
935 }
936}
937
938impl Schema {
939 pub fn new() -> Result<Self, OperationError> {
940 let s = Schema {
941 classes: CowCell::new(HashMap::with_capacity(128)),
942 attributes: CowCell::new(HashMap::with_capacity(128)),
943 unique_cache: CowCell::new(Vec::with_capacity(0)),
944 ref_cache: CowCell::new(HashMap::with_capacity(64)),
945 };
946 let mut sw = s.write();
947 let r1 = sw.generate_in_memory();
948 debug_assert!(r1.is_ok());
949 r1?;
950 let r2 = sw.commit().map(|_| s);
951 debug_assert!(r2.is_ok());
952 r2
953 }
954
955 pub fn read(&self) -> SchemaReadTransaction {
956 SchemaReadTransaction {
957 classes: self.classes.read(),
958 attributes: self.attributes.read(),
959 unique_cache: self.unique_cache.read(),
960 ref_cache: self.ref_cache.read(),
961 }
962 }
963
964 pub fn write(&self) -> SchemaWriteTransaction<'_> {
965 SchemaWriteTransaction {
966 classes: self.classes.write(),
967 attributes: self.attributes.write(),
968 unique_cache: self.unique_cache.write(),
969 ref_cache: self.ref_cache.write(),
970 }
971 }
972
973 #[cfg(test)]
974 pub(crate) fn write_blocking(&self) -> SchemaWriteTransaction<'_> {
975 self.write()
976 }
977}
978
979#[cfg(test)]
980mod tests {
981 use crate::{
982 prelude::*,
983 schema::{Schema, SchemaAttribute, SchemaClass, SchemaTransaction, SyntaxType},
984 };
985 use std::collections::BTreeMap;
986 use uuid::Uuid;
987
988 macro_rules! validate_schema {
989 ($sch:ident) => {{
990 let r: Result<Vec<()>, ConsistencyError> = $sch.validate().into_iter().collect();
992 assert!(r.is_ok());
993 }};
994 }
995
996 macro_rules! sch_from_entry_ok {
997 (
998 $e:expr,
999 $type:ty
1000 ) => {{
1001 let ev1 = $e.into_sealed_committed();
1002
1003 let r1 = <$type>::try_from(&ev1);
1004 assert!(r1.is_ok());
1005 }};
1006 }
1007
1008 macro_rules! sch_from_entry_err {
1009 (
1010 $e:expr,
1011 $type:ty
1012 ) => {{
1013 let ev1 = $e.into_sealed_committed();
1014
1015 let r1 = <$type>::try_from(&ev1);
1016 assert!(r1.is_err());
1017 }};
1018 }
1019
1020 #[test]
1021 fn test_schema_attribute_from_entry() {
1022 sketching::test_init();
1023
1024 sch_from_entry_err!(
1025 entry_init!(
1026 (Attribute::Class, EntryClass::Object.to_value()),
1027 (Attribute::Class, EntryClass::AttributeType.to_value()),
1028 (
1029 Attribute::AttributeName,
1030 Value::new_iutf8("schema_attr_test")
1031 ),
1032 (
1033 Attribute::Uuid,
1034 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1035 ),
1036 (Attribute::Unique, Value::Bool(false))
1037 ),
1038 SchemaAttribute
1039 );
1040
1041 sch_from_entry_err!(
1042 entry_init!(
1043 (Attribute::Class, EntryClass::Object.to_value()),
1044 (Attribute::Class, EntryClass::AttributeType.to_value()),
1045 (
1046 Attribute::AttributeName,
1047 Value::new_iutf8("schema_attr_test")
1048 ),
1049 (
1050 Attribute::Uuid,
1051 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1052 ),
1053 (Attribute::MultiValue, Value::Bool(false)),
1054 (Attribute::Unique, Value::Bool(false)),
1055 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String))
1056 ),
1057 SchemaAttribute
1058 );
1059
1060 sch_from_entry_err!(
1061 entry_init!(
1062 (Attribute::Class, EntryClass::Object.to_value()),
1063 (Attribute::Class, EntryClass::AttributeType.to_value()),
1064 (
1065 Attribute::AttributeName,
1066 Value::new_iutf8("schema_attr_test")
1067 ),
1068 (
1069 Attribute::Uuid,
1070 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1071 ),
1072 (
1073 Attribute::Description,
1074 Value::Utf8("Test attr parsing".to_string())
1075 ),
1076 (Attribute::MultiValue, Value::Utf8("htouaoeu".to_string())),
1077 (Attribute::Unique, Value::Bool(false)),
1078 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String))
1079 ),
1080 SchemaAttribute
1081 );
1082
1083 sch_from_entry_err!(
1084 entry_init!(
1085 (Attribute::Class, EntryClass::Object.to_value()),
1086 (Attribute::Class, EntryClass::AttributeType.to_value()),
1087 (
1088 Attribute::AttributeName,
1089 Value::new_iutf8("schema_attr_test")
1090 ),
1091 (
1092 Attribute::Uuid,
1093 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1094 ),
1095 (
1096 Attribute::Description,
1097 Value::Utf8("Test attr parsing".to_string())
1098 ),
1099 (Attribute::MultiValue, Value::Bool(false)),
1100 (Attribute::Unique, Value::Bool(false)),
1101 (Attribute::Syntax, Value::Utf8("TNEOUNTUH".to_string()))
1102 ),
1103 SchemaAttribute
1104 );
1105
1106 sch_from_entry_ok!(
1108 entry_init!(
1109 (Attribute::Class, EntryClass::Object.to_value()),
1110 (Attribute::Class, EntryClass::AttributeType.to_value()),
1111 (
1112 Attribute::AttributeName,
1113 Value::new_iutf8("schema_attr_test")
1114 ),
1115 (
1116 Attribute::Uuid,
1117 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1118 ),
1119 (
1120 Attribute::Description,
1121 Value::Utf8("Test attr parsing".to_string())
1122 ),
1123 (Attribute::MultiValue, Value::Bool(false)),
1124 (Attribute::Unique, Value::Bool(false)),
1125 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String))
1126 ),
1127 SchemaAttribute
1128 );
1129
1130 sch_from_entry_ok!(
1132 entry_init!(
1133 (Attribute::Class, EntryClass::Object.to_value()),
1134 (Attribute::Class, EntryClass::AttributeType.to_value()),
1135 (
1136 Attribute::AttributeName,
1137 Value::new_iutf8("schema_attr_test")
1138 ),
1139 (
1140 Attribute::Uuid,
1141 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1142 ),
1143 (
1144 Attribute::Description,
1145 Value::Utf8("Test attr parsing".to_string())
1146 ),
1147 (Attribute::MultiValue, Value::Bool(false)),
1148 (Attribute::Unique, Value::Bool(false)),
1149 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String)),
1150 (Attribute::Index, Value::Bool(true))
1151 ),
1152 SchemaAttribute
1153 );
1154 }
1155
1156 #[test]
1157 fn test_schema_class_from_entry() {
1158 sch_from_entry_err!(
1159 entry_init!(
1160 (Attribute::Class, EntryClass::Object.to_value()),
1161 (Attribute::Class, EntryClass::ClassType.to_value()),
1162 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1163 (
1164 Attribute::Uuid,
1165 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1166 )
1167 ),
1168 SchemaClass
1169 );
1170
1171 sch_from_entry_err!(
1172 entry_init!(
1173 (Attribute::Class, EntryClass::Object.to_value()),
1174 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1175 (
1176 Attribute::Uuid,
1177 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1178 ),
1179 (
1180 Attribute::Description,
1181 Value::Utf8("class test".to_string())
1182 )
1183 ),
1184 SchemaClass
1185 );
1186
1187 sch_from_entry_ok!(
1189 entry_init!(
1190 (Attribute::Class, EntryClass::Object.to_value()),
1191 (Attribute::Class, EntryClass::ClassType.to_value()),
1192 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1193 (
1194 Attribute::Uuid,
1195 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1196 ),
1197 (
1198 Attribute::Description,
1199 Value::Utf8("class test".to_string())
1200 )
1201 ),
1202 SchemaClass
1203 );
1204
1205 sch_from_entry_ok!(
1207 entry_init!(
1208 (Attribute::Class, EntryClass::Object.to_value()),
1209 (Attribute::Class, EntryClass::ClassType.to_value()),
1210 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1211 (
1212 Attribute::Uuid,
1213 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1214 ),
1215 (
1216 Attribute::Description,
1217 Value::Utf8("class test".to_string())
1218 ),
1219 (Attribute::SystemMust, Value::new_iutf8n("a"))
1220 ),
1221 SchemaClass
1222 );
1223
1224 sch_from_entry_ok!(
1225 entry_init!(
1226 (Attribute::Class, EntryClass::Object.to_value()),
1227 (Attribute::Class, EntryClass::ClassType.to_value()),
1228 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1229 (
1230 Attribute::Uuid,
1231 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1232 ),
1233 (
1234 Attribute::Description,
1235 Value::Utf8("class test".to_string())
1236 ),
1237 (Attribute::SystemMay, Value::new_iutf8n("a"))
1238 ),
1239 SchemaClass
1240 );
1241
1242 sch_from_entry_ok!(
1243 entry_init!(
1244 (Attribute::Class, EntryClass::Object.to_value()),
1245 (Attribute::Class, EntryClass::ClassType.to_value()),
1246 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1247 (
1248 Attribute::Uuid,
1249 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1250 ),
1251 (
1252 Attribute::Description,
1253 Value::Utf8("class test".to_string())
1254 ),
1255 (Attribute::May, Value::new_iutf8n("a")),
1256 (Attribute::Must, Value::new_iutf8n("b"))
1257 ),
1258 SchemaClass
1259 );
1260
1261 sch_from_entry_ok!(
1262 entry_init!(
1263 (Attribute::Class, EntryClass::Object.to_value()),
1264 (Attribute::Class, EntryClass::ClassType.to_value()),
1265 (Attribute::ClassName, Value::new_iutf8("schema_class_test")),
1266 (
1267 Attribute::Uuid,
1268 Value::Uuid(uuid::uuid!("66c68b2f-d02c-4243-8013-7946e40fe321"))
1269 ),
1270 (
1271 Attribute::Description,
1272 Value::Utf8("class test".to_string())
1273 ),
1274 (Attribute::May, Value::new_iutf8n("a")),
1275 (Attribute::Must, Value::new_iutf8n("b")),
1276 (Attribute::SystemMay, Value::new_iutf8n("c")),
1277 (Attribute::SystemMust, Value::new_iutf8n("d"))
1278 ),
1279 SchemaClass
1280 );
1281 }
1282
1283 #[test]
1284 fn test_schema_attribute_simple() {
1285 let single_value_string = SchemaAttribute {
1289 name: Attribute::from("single_value"),
1290 uuid: Uuid::new_v4(),
1291 description: String::from(""),
1292 syntax: SyntaxType::Utf8StringInsensitive,
1293 ..Default::default()
1294 };
1295
1296 let r1 = single_value_string
1297 .validate_ava(&Attribute::from("single_value"), &(vs_iutf8!["test"] as _));
1298 assert_eq!(r1, Ok(()));
1299
1300 let rvs = ValueSetIutf8N::from_iter(["test1", "test2"]).unwrap() as _;
1301 let r2 = single_value_string.validate_ava(&Attribute::from("single_value"), &rvs);
1302 assert_eq!(
1303 r2,
1304 Err(SchemaError::InvalidAttributeSyntax(
1305 "single_value".to_string()
1306 ))
1307 );
1308
1309 let multi_value_string = SchemaAttribute {
1312 name: Attribute::from("mv_string"),
1313 uuid: Uuid::new_v4(),
1314 description: String::from(""),
1315 multivalue: true,
1316 syntax: SyntaxType::Utf8String,
1317 ..Default::default()
1318 };
1319
1320 let rvs = vs_utf8!["test1".to_string(), "test2".to_string()] as _;
1321 let r5 = multi_value_string.validate_ava(&Attribute::from("mv_string"), &rvs);
1322 assert_eq!(r5, Ok(()));
1323
1324 let multi_value_boolean = SchemaAttribute {
1325 name: Attribute::from("mv_bool"),
1326 uuid: Uuid::new_v4(),
1327 description: String::from(""),
1328 multivalue: true,
1329 syntax: SyntaxType::Boolean,
1330 ..Default::default()
1331 };
1332
1333 let rvs = vs_bool![true, false];
1350 let r4 = multi_value_boolean.validate_ava(&Attribute::from("mv_bool"), &(rvs as _));
1351 assert_eq!(r4, Ok(()));
1352
1353 let single_value_syntax = SchemaAttribute {
1355 name: Attribute::from("sv_syntax"),
1356 uuid: Uuid::new_v4(),
1357 description: String::from(""),
1358 syntax: SyntaxType::SyntaxId,
1359 ..Default::default()
1360 };
1361
1362 let rvs = vs_syntax![SyntaxType::try_from("UTF8STRING").unwrap()] as _;
1363 let r6 = single_value_syntax.validate_ava(&Attribute::from("sv_syntax"), &rvs);
1364 assert_eq!(r6, Ok(()));
1365
1366 let rvs = vs_utf8!["thaeountaheu".to_string()] as _;
1367 let r7 = single_value_syntax.validate_ava(&Attribute::from("sv_syntax"), &rvs);
1368 assert_eq!(
1369 r7,
1370 Err(SchemaError::InvalidAttributeSyntax("sv_syntax".to_string()))
1371 );
1372
1373 let single_value_index = SchemaAttribute {
1374 name: Attribute::from("sv_index"),
1375 uuid: Uuid::new_v4(),
1376 description: String::from(""),
1377 syntax: SyntaxType::IndexId,
1378 ..Default::default()
1379 };
1380
1381 let rvs = vs_utf8!["thaeountaheu".to_string()] as _;
1382 let r9 = single_value_index.validate_ava(&Attribute::from("sv_index"), &rvs);
1383 assert_eq!(
1384 r9,
1385 Err(SchemaError::InvalidAttributeSyntax("sv_index".to_string()))
1386 );
1387 }
1388
1389 #[test]
1390 fn test_schema_simple() {
1391 let schema = Schema::new().expect("failed to create schema");
1392 let schema_ro = schema.read();
1393 validate_schema!(schema_ro);
1394 }
1395
1396 #[test]
1397 fn test_schema_entries() {
1398 sketching::test_init();
1399 let schema_outer = Schema::new().expect("failed to create schema");
1402 let schema = schema_outer.read();
1403
1404 let e_no_uuid = entry_init!().into_invalid_new();
1405
1406 assert_eq!(
1407 e_no_uuid.validate(&schema),
1408 Err(SchemaError::MissingMustAttribute(vec![Attribute::Uuid]))
1409 );
1410
1411 let e_no_class = entry_init!((
1412 Attribute::Uuid,
1413 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1414 ))
1415 .into_invalid_new();
1416
1417 assert_eq!(e_no_class.validate(&schema), Err(SchemaError::NoClassFound));
1418
1419 let e_bad_class = entry_init!(
1420 (
1421 Attribute::Uuid,
1422 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1423 ),
1424 (Attribute::Class, Value::new_iutf8n("zzzzzz"))
1425 )
1426 .into_invalid_new();
1427 assert_eq!(
1428 e_bad_class.validate(&schema),
1429 Err(SchemaError::InvalidClass(vec!["zzzzzz".to_string()]))
1430 );
1431
1432 let e_attr_invalid = entry_init!(
1433 (
1434 Attribute::Uuid,
1435 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1436 ),
1437 (Attribute::Class, EntryClass::Object.to_value()),
1438 (Attribute::Class, EntryClass::AttributeType.to_value())
1439 )
1440 .into_invalid_new();
1441 let res = e_attr_invalid.validate(&schema);
1442 matches!(res, Err(SchemaError::MissingMustAttribute(_)));
1443
1444 let e_attr_invalid_may = entry_init!(
1445 (Attribute::Class, EntryClass::Object.to_value()),
1446 (Attribute::Class, EntryClass::AttributeType.to_value()),
1447 (Attribute::AttributeName, Value::new_iutf8("testattr")),
1448 (Attribute::Description, Value::Utf8("testattr".to_string())),
1449 (Attribute::MultiValue, Value::Bool(false)),
1450 (Attribute::Unique, Value::Bool(false)),
1451 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String)),
1452 (
1453 Attribute::Uuid,
1454 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1455 ),
1456 (Attribute::TestAttr, Value::Utf8("zzzz".to_string()))
1457 )
1458 .into_invalid_new();
1459
1460 assert_eq!(
1461 e_attr_invalid_may.validate(&schema),
1462 Err(SchemaError::AttributeNotValidForClass(
1463 Attribute::TestAttr.to_string()
1464 ))
1465 );
1466
1467 let e_attr_invalid_syn = entry_init!(
1468 (Attribute::Class, EntryClass::Object.to_value()),
1469 (Attribute::Class, EntryClass::AttributeType.to_value()),
1470 (Attribute::AttributeName, Value::new_iutf8("testattr")),
1471 (Attribute::Description, Value::Utf8("testattr".to_string())),
1472 (Attribute::MultiValue, Value::Utf8("false".to_string())),
1473 (Attribute::Unique, Value::Bool(false)),
1474 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String)),
1475 (
1476 Attribute::Uuid,
1477 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1478 )
1479 )
1480 .into_invalid_new();
1481
1482 assert_eq!(
1483 e_attr_invalid_syn.validate(&schema),
1484 Err(SchemaError::InvalidAttributeSyntax(
1485 "multivalue".to_string()
1486 ))
1487 );
1488
1489 let e_phantom = entry_init!(
1491 (Attribute::Class, EntryClass::Object.to_value()),
1492 (Attribute::Class, EntryClass::AttributeType.to_value()),
1493 (Attribute::AttributeName, Value::new_iutf8("testattr")),
1494 (Attribute::Description, Value::Utf8("testattr".to_string())),
1495 (Attribute::MultiValue, Value::Bool(false)),
1496 (Attribute::Unique, Value::Bool(false)),
1497 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String)),
1498 (
1499 Attribute::Uuid,
1500 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1501 ),
1502 (
1503 Attribute::PasswordImport,
1504 Value::Utf8("password".to_string())
1505 )
1506 )
1507 .into_invalid_new();
1508 assert!(e_phantom.validate(&schema).is_err());
1509
1510 let e_ok = entry_init!(
1511 (Attribute::Class, EntryClass::Object.to_value()),
1512 (Attribute::Class, EntryClass::AttributeType.to_value()),
1513 (Attribute::AttributeName, Value::new_iutf8("testattr")),
1514 (Attribute::Description, Value::Utf8("testattr".to_string())),
1515 (Attribute::MultiValue, Value::Bool(true)),
1516 (Attribute::Unique, Value::Bool(false)),
1517 (Attribute::Syntax, Value::Syntax(SyntaxType::Utf8String)),
1518 (
1519 Attribute::Uuid,
1520 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1521 )
1522 )
1523 .into_invalid_new();
1524 assert!(e_ok.validate(&schema).is_ok());
1525 }
1526
1527 #[test]
1528 fn test_schema_extensible() {
1529 let schema_outer = Schema::new().expect("failed to create schema");
1530 let schema = schema_outer.read();
1531 let e_extensible_bad = entry_init!(
1533 (Attribute::Class, EntryClass::ExtensibleObject.to_value()),
1534 (
1535 Attribute::Uuid,
1536 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1537 ),
1538 (Attribute::MultiValue, Value::Utf8("zzzz".to_string()))
1539 )
1540 .into_invalid_new();
1541
1542 assert_eq!(
1543 e_extensible_bad.validate(&schema),
1544 Err(SchemaError::InvalidAttributeSyntax(
1545 "multivalue".to_string()
1546 ))
1547 );
1548
1549 let e_extensible_phantom = entry_init!(
1551 (Attribute::Class, EntryClass::ExtensibleObject.to_value()),
1552 (
1553 Attribute::Uuid,
1554 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1555 ),
1556 (Attribute::PasswordImport, Value::Utf8("zzzz".to_string()))
1557 )
1558 .into_invalid_new();
1559
1560 assert_eq!(
1561 e_extensible_phantom.validate(&schema),
1562 Err(SchemaError::PhantomAttribute(
1563 Attribute::PasswordImport.to_string()
1564 ))
1565 );
1566
1567 let e_extensible = entry_init!(
1568 (Attribute::Class, EntryClass::ExtensibleObject.to_value()),
1569 (
1570 Attribute::Uuid,
1571 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
1572 ),
1573 (Attribute::MultiValue, Value::Bool(true))
1574 )
1575 .into_invalid_new();
1576
1577 assert!(e_extensible.validate(&schema).is_ok());
1579 }
1580
1581 #[test]
1582 fn test_schema_filter_validation() {
1583 let schema_outer = Schema::new().expect("failed to create schema");
1584 let schema = schema_outer.read();
1585
1586 let f_bool = filter_all!(f_eq(Attribute::MultiValue, PartialValue::new_iutf8("zzzz")));
1588 assert_eq!(
1589 f_bool.validate(&schema),
1590 Err(SchemaError::InvalidAttributeSyntax(
1591 "multivalue".to_string()
1592 ))
1593 );
1594 let f_insense = filter_all!(f_eq(Attribute::Class, EntryClass::AttributeType.into()));
1596 assert_eq!(
1597 f_insense.validate(&schema),
1598 Ok(filter_valid!(f_eq(
1599 Attribute::Class,
1600 EntryClass::AttributeType.into()
1601 )))
1602 );
1603 let f_or_empty = filter_all!(f_or!([]));
1605 assert_eq!(f_or_empty.validate(&schema), Err(SchemaError::EmptyFilter));
1606 let f_or = filter_all!(f_or!([f_eq(
1607 Attribute::MultiValue,
1608 PartialValue::new_iutf8("zzzz")
1609 )]));
1610 assert_eq!(
1611 f_or.validate(&schema),
1612 Err(SchemaError::InvalidAttributeSyntax(
1613 "multivalue".to_string()
1614 ))
1615 );
1616 let f_or_mult = filter_all!(f_and!([
1617 f_eq(Attribute::Class, EntryClass::AttributeType.into()),
1618 f_eq(Attribute::MultiValue, PartialValue::new_iutf8("zzzzzzz")),
1619 ]));
1620 assert_eq!(
1621 f_or_mult.validate(&schema),
1622 Err(SchemaError::InvalidAttributeSyntax(
1623 "multivalue".to_string()
1624 ))
1625 );
1626 let f_or_ok = filter_all!(f_andnot(f_and!([
1628 f_eq(Attribute::Class, EntryClass::AttributeType.into()),
1629 f_sub(Attribute::Class, EntryClass::ClassType.into()),
1630 f_pres(Attribute::Class)
1631 ])));
1632 assert_eq!(
1633 f_or_ok.validate(&schema),
1634 Ok(filter_valid!(f_andnot(f_and!([
1635 f_eq(Attribute::Class, EntryClass::AttributeType.into()),
1636 f_sub(Attribute::Class, EntryClass::ClassType.into()),
1637 f_pres(Attribute::Class)
1638 ]))))
1639 );
1640 }
1641
1642 #[test]
1643 fn test_schema_class_phantom_reject() {
1644 let schema_outer = Schema::new().expect("failed to create schema");
1646 let mut schema = schema_outer.write_blocking();
1647
1648 assert!(schema.validate().is_empty());
1649
1650 let class = SchemaClass {
1652 name: AttrString::from("testobject"),
1653 uuid: Uuid::new_v4(),
1654 description: String::from("test object"),
1655 systemmay: vec![Attribute::Claim],
1656 ..Default::default()
1657 };
1658
1659 assert!(schema.update_classes(std::iter::once(class)).is_ok());
1660
1661 assert_eq!(schema.validate().len(), 1);
1662 }
1663
1664 #[test]
1665 fn test_schema_class_exclusion_requires() {
1666 sketching::test_init();
1667
1668 let schema_outer = Schema::new().expect("failed to create schema");
1669 let mut schema = schema_outer.write_blocking();
1670
1671 assert!(schema.validate().is_empty());
1672
1673 let class_account = SchemaClass {
1676 name: Attribute::Account.into(),
1677 uuid: Uuid::new_v4(),
1678 description: String::from("account object"),
1679 systemmust: vec![
1680 Attribute::Class,
1681 Attribute::Uuid,
1682 Attribute::LastModifiedCid,
1683 Attribute::CreatedAtCid,
1684 ],
1685 systemsupplements: vec![EntryClass::Service.into(), EntryClass::Person.into()],
1686 ..Default::default()
1687 };
1688
1689 let class_person = SchemaClass {
1690 name: EntryClass::Person.into(),
1691 uuid: Uuid::new_v4(),
1692 description: String::from("person object"),
1693 systemmust: vec![
1694 Attribute::Class,
1695 Attribute::Uuid,
1696 Attribute::LastModifiedCid,
1697 Attribute::CreatedAtCid,
1698 ],
1699 ..Default::default()
1700 };
1701
1702 let class_service = SchemaClass {
1703 name: EntryClass::Service.into(),
1704 uuid: Uuid::new_v4(),
1705 description: String::from("service object"),
1706 systemmust: vec![
1707 Attribute::Class,
1708 Attribute::Uuid,
1709 Attribute::LastModifiedCid,
1710 Attribute::CreatedAtCid,
1711 ],
1712 excludes: vec![EntryClass::Person.into()],
1713 ..Default::default()
1714 };
1715
1716 assert!(schema
1717 .update_classes([class_account, class_person, class_service].into_iter())
1718 .is_ok());
1719
1720 let e_account = entry_init!(
1722 (Attribute::Class, EntryClass::Account.to_value()),
1723 (Attribute::Uuid, Value::Uuid(Uuid::new_v4()))
1724 )
1725 .into_invalid_new();
1726
1727 assert_eq!(
1728 e_account.validate(&schema),
1729 Err(SchemaError::SupplementsNotSatisfied(vec![
1730 EntryClass::Service.into(),
1731 EntryClass::Person.into(),
1732 ]))
1733 );
1734
1735 let e_service_person = entry_init!(
1750 (Attribute::Class, EntryClass::Service.to_value()),
1751 (Attribute::Class, EntryClass::Account.to_value()),
1752 (Attribute::Class, EntryClass::Person.to_value()),
1753 (Attribute::Uuid, Value::Uuid(Uuid::new_v4()))
1754 )
1755 .into_invalid_new();
1756
1757 assert_eq!(
1758 e_service_person.validate(&schema),
1759 Err(SchemaError::ExcludesNotSatisfied(vec![
1760 EntryClass::Person.to_string()
1761 ]))
1762 );
1763
1764 let e_service_valid = entry_init!(
1766 (Attribute::Class, EntryClass::Service.to_value()),
1767 (Attribute::Class, EntryClass::Account.to_value()),
1768 (Attribute::Uuid, Value::Uuid(Uuid::new_v4()))
1769 )
1770 .into_invalid_new();
1771
1772 assert!(e_service_valid.validate(&schema).is_ok());
1773
1774 let e_person_valid = entry_init!(
1775 (Attribute::Class, EntryClass::Person.to_value()),
1776 (Attribute::Class, EntryClass::Account.to_value()),
1777 (Attribute::Uuid, Value::Uuid(Uuid::new_v4()))
1778 )
1779 .into_invalid_new();
1780
1781 assert!(e_person_valid.validate(&schema).is_ok());
1782
1783 let e_person_valid = entry_init!(
1784 (Attribute::Class, EntryClass::Person.to_value()),
1785 (Attribute::Uuid, Value::Uuid(Uuid::new_v4()))
1786 )
1787 .into_invalid_new();
1788
1789 assert!(e_person_valid.validate(&schema).is_ok());
1790 }
1791
1792 #[qs_test]
1793 async fn test_schema_syntax_multivalue_unique(server: &QueryServer) {
1794 #[derive(Default)]
1795 struct X {
1796 multi: Vec<Attribute>,
1797 single: Vec<Attribute>,
1798 }
1799
1800 let read_txn = server
1802 .read()
1803 .await
1804 .expect("Failed to start read transaction");
1805
1806 let schema_txn = read_txn.get_schema();
1807 let schema_attrs_txn = schema_txn.get_attributes();
1808
1809 let mut attr_set: BTreeMap<SyntaxType, X> = BTreeMap::new();
1810
1811 for schema_attr in schema_attrs_txn.values() {
1813 if schema_attr.phantom {
1814 continue;
1815 }
1816
1817 let s = attr_set.entry(schema_attr.syntax).or_default();
1818
1819 if schema_attr.multivalue {
1820 s.multi.push(schema_attr.name.clone())
1821 } else {
1822 s.single.push(schema_attr.name.clone())
1823 }
1824 }
1825
1826 let mut pass = true;
1827
1828 for (syntax, x) in attr_set {
1829 if x.multi.is_empty() && x.single.is_empty() {
1830 error!("{} NOT USED", syntax);
1831 pass = false;
1832 } else if x.multi.is_empty() || x.single.is_empty() {
1833 continue;
1835 } else {
1836 pass = false;
1837 }
1838
1839 warn!("{}", syntax);
1840 warn!("multi: {:?}", x.multi);
1841 warn!("single: {:?}", x.single);
1842 }
1843
1844 assert!(pass);
1846 }
1847}