1use std::{
12 cmp::{Ordering, PartialOrd},
13 collections::BTreeSet,
14 fmt,
15 hash::Hash,
16 iter,
17 num::NonZeroU8,
18 str::FromStr,
19 sync::Arc,
20};
21
22use concread::arcache::{ARCache, ARCacheReadTxn};
23use hashbrown::HashMap;
24#[cfg(test)]
25use hashbrown::HashSet;
26use kanidm_proto::{
27 constants::ATTR_UUID,
28 internal::{Filter as ProtoFilter, OperationError, SchemaError},
29 scim_v1::{AttrPath as ScimAttrPath, ScimFilter},
30};
31use ldap3_proto::proto::{LdapFilter, LdapSubstringFilter};
32use serde::Deserialize;
33use uuid::Uuid;
34
35use crate::{
36 be::{IdxKey, IdxKeyRef, IdxKeyToRef, IdxMeta, IdxSlope},
37 idm::ldap::ldap_attr_filter_map,
38 prelude::*,
39 schema::SchemaTransaction,
40 value::{IndexType, PartialValue},
41};
42
43pub type ResolveFilterCache =
44 ARCache<(IdentityId, Arc<Filter<FilterValid>>), Arc<Filter<FilterValidResolved>>>;
45
46pub type ResolveFilterCacheReadTxn<'a> = ARCacheReadTxn<
47 'a,
48 (IdentityId, Arc<Filter<FilterValid>>),
49 Arc<Filter<FilterValidResolved>>,
50 (),
51>;
52
53pub fn f_eq(a: Attribute, v: PartialValue) -> FC {
58 FC::Eq(a, v)
59}
60
61pub fn f_sub(a: Attribute, v: PartialValue) -> FC {
62 FC::Cnt(a, v)
63}
64
65pub fn f_pres(a: Attribute) -> FC {
66 FC::Pres(a)
67}
68
69pub fn f_lt(a: Attribute, v: PartialValue) -> FC {
70 FC::LessThan(a, v)
71}
72
73pub fn f_gt(a: Attribute, v: PartialValue) -> FC {
74 FC::And(vec![
75 FC::Pres(a.clone()),
76 FC::AndNot(Box::new(FC::Or(vec![
77 FC::Eq(a.clone(), v.clone()),
78 FC::LessThan(a, v),
79 ]))),
80 ])
81}
82
83pub fn f_or(vs: Vec<FC>) -> FC {
84 FC::Or(vs)
85}
86
87pub fn f_and(vs: Vec<FC>) -> FC {
88 FC::And(vs)
89}
90
91pub fn f_inc(vs: Vec<FC>) -> FC {
92 FC::Inclusion(vs)
93}
94
95pub fn f_andnot(fc: FC) -> FC {
96 FC::AndNot(Box::new(fc))
97}
98
99pub fn f_self() -> FC {
100 FC::SelfUuid
101}
102
103pub fn f_invalid(a: Attribute) -> FC {
104 FC::Invalid(a)
105}
106
107pub fn f_id(uuid: &str) -> FC {
108 let uf = Uuid::parse_str(uuid)
109 .ok()
110 .map(|u| FC::Eq(Attribute::Uuid, PartialValue::Uuid(u)));
111 let spnf = PartialValue::new_spn_s(uuid).map(|spn| FC::Eq(Attribute::Spn, spn));
112 let nf = FC::Eq(Attribute::Name, PartialValue::new_iname(uuid));
113 let f: Vec<_> = iter::once(uf)
114 .chain(iter::once(spnf))
115 .flatten()
116 .chain(iter::once(nf))
117 .collect();
118 FC::Or(f)
119}
120
121pub fn f_spn_name(id: &str) -> FC {
122 let spnf = PartialValue::new_spn_s(id).map(|spn| FC::Eq(Attribute::Spn, spn));
123 let nf = FC::Eq(Attribute::Name, PartialValue::new_iname(id));
124 let f: Vec<_> = iter::once(spnf).flatten().chain(iter::once(nf)).collect();
125 FC::Or(f)
126}
127
128#[derive(Clone, Debug, Deserialize)]
131pub enum FC {
132 Eq(Attribute, PartialValue),
133 Cnt(Attribute, PartialValue),
134 Pres(Attribute),
135 LessThan(Attribute, PartialValue),
136 Or(Vec<FC>),
137 And(Vec<FC>),
138 Inclusion(Vec<FC>),
139 AndNot(Box<FC>),
140 SelfUuid,
141 Invalid(Attribute),
142 }
144
145#[derive(Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
147enum FilterComp {
148 Eq(Attribute, PartialValue),
150 Cnt(Attribute, PartialValue),
151 Stw(Attribute, PartialValue),
152 Enw(Attribute, PartialValue),
153 Pres(Attribute),
154 LessThan(Attribute, PartialValue),
155 Or(Vec<FilterComp>),
156 And(Vec<FilterComp>),
157 Inclusion(Vec<FilterComp>),
158 AndNot(Box<FilterComp>),
159 SelfUuid,
160 Invalid(Attribute),
161 }
164
165impl fmt::Debug for FilterComp {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 match self {
168 FilterComp::Eq(attr, pv) => {
169 write!(f, "{attr} eq {pv:?}")
170 }
171 FilterComp::Cnt(attr, pv) => {
172 write!(f, "{attr} cnt {pv:?}")
173 }
174 FilterComp::Stw(attr, pv) => {
175 write!(f, "{attr} stw {pv:?}")
176 }
177 FilterComp::Enw(attr, pv) => {
178 write!(f, "{attr} enw {pv:?}")
179 }
180 FilterComp::Pres(attr) => {
181 write!(f, "{attr} pres")
182 }
183 FilterComp::LessThan(attr, pv) => {
184 write!(f, "{attr} lt {pv:?}")
185 }
186 FilterComp::And(list) => {
187 write!(f, "(")?;
188 for (i, fc) in list.iter().enumerate() {
189 write!(f, "{fc:?}")?;
190 if i != list.len() - 1 {
191 write!(f, " and ")?;
192 }
193 }
194 write!(f, ")")
195 }
196 FilterComp::Or(list) => {
197 write!(f, "(")?;
198 for (i, fc) in list.iter().enumerate() {
199 write!(f, "{fc:?}")?;
200 if i != list.len() - 1 {
201 write!(f, " or ")?;
202 }
203 }
204 write!(f, ")")
205 }
206 FilterComp::Inclusion(list) => {
207 write!(f, "(")?;
208 for (i, fc) in list.iter().enumerate() {
209 write!(f, "{fc:?}")?;
210 if i != list.len() - 1 {
211 write!(f, " inc ")?;
212 }
213 }
214 write!(f, ")")
215 }
216 FilterComp::AndNot(inner) => {
217 write!(f, "not ( {inner:?} )")
218 }
219 FilterComp::SelfUuid => {
220 write!(f, "uuid eq self")
221 }
222 FilterComp::Invalid(attr) => {
223 write!(f, "invalid ( {attr:?} )")
224 }
225 }
226 }
227}
228
229#[derive(Clone, Eq)]
240pub enum FilterResolved {
241 Eq(Attribute, PartialValue, Option<NonZeroU8>),
243 Cnt(Attribute, PartialValue, Option<NonZeroU8>),
244 Stw(Attribute, PartialValue, Option<NonZeroU8>),
245 Enw(Attribute, PartialValue, Option<NonZeroU8>),
246 Pres(Attribute, Option<NonZeroU8>),
247 LessThan(Attribute, PartialValue, Option<NonZeroU8>),
248 Or(Vec<FilterResolved>, Option<NonZeroU8>),
249 And(Vec<FilterResolved>, Option<NonZeroU8>),
250 Invalid(Attribute),
251 Inclusion(Vec<FilterResolved>, Option<NonZeroU8>),
253 AndNot(Box<FilterResolved>, Option<NonZeroU8>),
254}
255
256impl fmt::Debug for FilterResolved {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 match self {
259 FilterResolved::Eq(attr, pv, idx) => {
260 write!(
261 f,
262 "(s{} {} eq {:?})",
263 idx.unwrap_or(NonZeroU8::MAX),
264 attr,
265 pv
266 )
267 }
268 FilterResolved::Cnt(attr, pv, idx) => {
269 write!(
270 f,
271 "(s{} {} cnt {:?})",
272 idx.unwrap_or(NonZeroU8::MAX),
273 attr,
274 pv
275 )
276 }
277 FilterResolved::Stw(attr, pv, idx) => {
278 write!(
279 f,
280 "(s{} {} stw {:?})",
281 idx.unwrap_or(NonZeroU8::MAX),
282 attr,
283 pv
284 )
285 }
286 FilterResolved::Enw(attr, pv, idx) => {
287 write!(
288 f,
289 "(s{} {} enw {:?})",
290 idx.unwrap_or(NonZeroU8::MAX),
291 attr,
292 pv
293 )
294 }
295 FilterResolved::Pres(attr, idx) => {
296 write!(f, "(s{} {} pres)", idx.unwrap_or(NonZeroU8::MAX), attr)
297 }
298 FilterResolved::LessThan(attr, pv, idx) => {
299 write!(
300 f,
301 "(s{} {} lt {:?})",
302 idx.unwrap_or(NonZeroU8::MAX),
303 attr,
304 pv
305 )
306 }
307 FilterResolved::And(list, idx) => {
308 write!(f, "(s{} ", idx.unwrap_or(NonZeroU8::MAX))?;
309 for (i, fc) in list.iter().enumerate() {
310 write!(f, "{fc:?}")?;
311 if i != list.len() - 1 {
312 write!(f, " and ")?;
313 }
314 }
315 write!(f, ")")
316 }
317 FilterResolved::Or(list, idx) => {
318 write!(f, "(s{} ", idx.unwrap_or(NonZeroU8::MAX))?;
319 for (i, fc) in list.iter().enumerate() {
320 write!(f, "{fc:?}")?;
321 if i != list.len() - 1 {
322 write!(f, " or ")?;
323 }
324 }
325 write!(f, ")")
326 }
327 FilterResolved::Inclusion(list, idx) => {
328 write!(f, "(s{} ", idx.unwrap_or(NonZeroU8::MAX))?;
329 for (i, fc) in list.iter().enumerate() {
330 write!(f, "{fc:?}")?;
331 if i != list.len() - 1 {
332 write!(f, " inc ")?;
333 }
334 }
335 write!(f, ")")
336 }
337 FilterResolved::AndNot(inner, idx) => {
338 write!(f, "not (s{} {:?})", idx.unwrap_or(NonZeroU8::MAX), inner)
339 }
340 FilterResolved::Invalid(attr) => {
341 write!(f, "{attr} inv")
342 }
343 }
344 }
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct FilterInvalid {
350 inner: FilterComp,
351}
352
353#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
354pub struct FilterValid {
356 inner: FilterComp,
357}
358
359#[derive(Clone, PartialEq, Eq)]
360pub struct FilterValidResolved {
361 inner: FilterResolved,
362}
363
364#[derive(Debug)]
365pub enum FilterPlan {
366 Invalid,
367 EqIndexed(Attribute, String),
368 EqUnindexed(Attribute),
369 EqCorrupt(Attribute),
370 SubIndexed(Attribute, String),
371 SubUnindexed(Attribute),
372 SubCorrupt(Attribute),
373 PresIndexed(Attribute),
374 PresUnindexed(Attribute),
375 PresCorrupt(Attribute),
376 LessThanUnindexed(Attribute),
377 LessThanIndexed(Attribute),
378 LessThanCorrupt(Attribute),
379 OrUnindexed(Vec<FilterPlan>),
380 OrIndexed(Vec<FilterPlan>),
381 OrPartial(Vec<FilterPlan>),
382 OrPartialThreshold(Vec<FilterPlan>),
383 AndEmptyCand(Vec<FilterPlan>),
384 AndIndexed(Vec<FilterPlan>),
385 AndUnindexed(Vec<FilterPlan>),
386 AndPartial(Vec<FilterPlan>),
387 AndPartialThreshold(Vec<FilterPlan>),
388 AndNot(Box<FilterPlan>),
389 InclusionInvalid(Vec<FilterPlan>),
390 InclusionIndexed(Vec<FilterPlan>),
391}
392
393fn fmt_filterplan_set(f: &mut fmt::Formatter<'_>, name: &str, plan: &[FilterPlan]) -> fmt::Result {
397 write!(f, "{name}(")?;
398 for item in plan {
399 write!(f, "{item}, ")?;
400 }
401 write!(f, ")")
402}
403
404impl fmt::Display for FilterPlan {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 match self {
407 Self::Invalid => write!(f, "Invalid"),
408 Self::EqIndexed(attr, _) => write!(f, "EqIndexed({attr})"),
409 Self::EqCorrupt(attr) => write!(f, "EqCorrupt({attr})"),
410 Self::EqUnindexed(attr) => write!(f, "EqUnindexed({attr})"),
411
412 Self::SubIndexed(attr, _) => write!(f, "SubIndexed({attr})"),
413 Self::SubCorrupt(attr) => write!(f, "SubCorrupt({attr})"),
414 Self::SubUnindexed(attr) => write!(f, "SubUnindexed({attr})"),
415
416 Self::PresIndexed(attr) => write!(f, "PresIndexed({attr})"),
417 Self::PresCorrupt(attr) => write!(f, "PresCorrupt({attr})"),
418 Self::PresUnindexed(attr) => write!(f, "PresUnindexed({attr})"),
419
420 Self::LessThanUnindexed(attr) => write!(f, "LessThanUnindexed({attr})"),
421 Self::LessThanIndexed(attr) => write!(f, "LessThanIndexed({attr})"),
422 Self::LessThanCorrupt(attr) => write!(f, "LessThanCorrupt({attr})"),
423
424 Self::OrUnindexed(plan) => fmt_filterplan_set(f, "OrUnindexed", plan),
425 Self::OrIndexed(plan) => write!(f, "OrIndexed(len={})", plan.len()),
426 Self::OrPartial(plan) => fmt_filterplan_set(f, "OrPartial", plan),
427 Self::OrPartialThreshold(plan) => fmt_filterplan_set(f, "OrPartialThreshold", plan),
428
429 Self::AndEmptyCand(plan) => write!(f, "AndEmptyCand(len={})", plan.len()),
430 Self::AndUnindexed(plan) => fmt_filterplan_set(f, "AndUnindexed", plan),
431 Self::AndIndexed(plan) => write!(f, "AndIndexed(len={})", plan.len()),
432 Self::AndPartial(plan) => fmt_filterplan_set(f, "AndPartial", plan),
433 Self::AndPartialThreshold(plan) => fmt_filterplan_set(f, "AndPartialThreshold", plan),
434
435 Self::AndNot(plan) => write!(f, "AndNot({plan})"),
436
437 Self::InclusionInvalid(plan) => fmt_filterplan_set(f, "InclusionInvalid", plan),
438 Self::InclusionIndexed(plan) => write!(f, "InclusionIndexed(len={})", plan.len()),
439 }
440 }
441}
442
443#[derive(Clone, Hash, Ord, Eq, PartialOrd, PartialEq)]
465pub struct Filter<STATE> {
466 state: STATE,
467}
468
469impl fmt::Debug for Filter<FilterValidResolved> {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
471 writeln!(f, "Filter(Valid) {:?}", self.state.inner)
472 }
473}
474
475impl fmt::Debug for Filter<FilterValid> {
476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 writeln!(f, "Filter(Valid) {:?}", self.state.inner)
478 }
479}
480
481impl fmt::Debug for Filter<FilterInvalid> {
482 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
483 writeln!(f, "Filter(Invalid) {:?}", self.state.inner)
484 }
485}
486
487impl Filter<FilterValidResolved> {
488 #[cfg(test)]
492 fn optimise(&self) -> Self {
493 Filter {
507 state: FilterValidResolved {
508 inner: self.state.inner.optimise(),
509 },
510 }
511 }
512
513 pub fn to_inner(&self) -> &FilterResolved {
523 &self.state.inner
524 }
525}
526
527impl Filter<FilterValid> {
528 pub fn invalidate(self) -> Filter<FilterInvalid> {
529 Filter {
531 state: FilterInvalid {
532 inner: self.state.inner,
533 },
534 }
535 }
536
537 pub fn resolve(
538 &self,
539 ev: &Identity,
540 idxmeta: Option<&IdxMeta>,
541 mut rsv_cache: Option<&mut ResolveFilterCacheReadTxn<'_>>,
542 ) -> Result<Filter<FilterValidResolved>, OperationError> {
543 let cacheable = idxmeta.is_some() && FilterResolved::resolve_cacheable(&self.state.inner);
552
553 let cache_key = if cacheable {
554 if let Some(rcache) = rsv_cache.as_mut() {
556 let cache_key = (ev.get_event_origin_id(), Arc::new(self.clone()));
558 if let Some(f) = rcache.get(&cache_key) {
559 trace!("shortcut: a resolved filter already exists.");
561 return Ok(f.as_ref().clone());
562 };
563 Some(cache_key)
565 } else {
566 None
567 }
568 } else {
569 None
571 };
572
573 let resolved_filt = Filter {
576 state: FilterValidResolved {
577 inner: match idxmeta {
578 Some(idx) => {
579 FilterResolved::resolve_idx(self.state.inner.clone(), ev, &idx.idxkeys)
580 }
581 None => FilterResolved::resolve_no_idx(self.state.inner.clone(), ev),
582 }
583 .map(|f| {
584 match idxmeta {
585 Some(_) => f.optimise(),
587 None => f.fast_optimise(),
589 }
590 })
591 .ok_or(OperationError::FilterUuidResolution)?,
592 },
593 };
594
595 if let Some(cache_key) = cache_key {
598 if let Some(rcache) = rsv_cache.as_mut() {
599 trace!(?resolved_filt, "inserting filter to resolved cache");
600 rcache.insert(cache_key, Arc::new(resolved_filt.clone()));
601 }
602 }
603
604 Ok(resolved_filt)
605 }
606
607 pub fn get_attr_set(&self) -> BTreeSet<Attribute> {
608 let mut r_set = BTreeSet::new();
610 self.state.inner.get_attr_set(&mut r_set);
611 r_set
612 }
613
614 pub fn into_ignore_hidden(self) -> Self {
621 Filter {
623 state: FilterValid {
624 inner: FilterComp::new_ignore_hidden(self.state.inner),
625 },
626 }
627 }
628
629 pub fn into_recycled(self) -> Self {
630 Filter {
632 state: FilterValid {
633 inner: FilterComp::new_recycled(self.state.inner),
634 },
635 }
636 }
637}
638
639impl Filter<FilterInvalid> {
640 pub fn new(inner: FC) -> Self {
641 let fc = FilterComp::new(inner);
642 Filter {
643 state: FilterInvalid { inner: fc },
644 }
645 }
646
647 pub fn new_ignore_hidden(inner: FC) -> Self {
648 let fc = FilterComp::new(inner);
649 Filter {
650 state: FilterInvalid {
651 inner: FilterComp::new_ignore_hidden(fc),
652 },
653 }
654 }
655
656 pub fn new_recycled(inner: FC) -> Self {
657 let fc = FilterComp::new(inner);
659 Filter {
660 state: FilterInvalid {
661 inner: FilterComp::new_recycled(fc),
662 },
663 }
664 }
665
666 pub fn join_parts_and(a: Self, b: Self) -> Self {
667 Filter {
669 state: FilterInvalid {
670 inner: FilterComp::And(vec![a.state.inner, b.state.inner]),
671 },
672 }
673 }
674
675 #[cfg(test)]
678 pub fn into_valid_resolved(self) -> Filter<FilterValidResolved> {
679 let idxmeta = vec![
690 (Attribute::Uuid, IndexType::Equality),
691 (Attribute::Uuid, IndexType::Presence),
692 (Attribute::Name, IndexType::Equality),
693 (Attribute::Name, IndexType::SubString),
694 (Attribute::Name, IndexType::Presence),
695 (Attribute::Class, IndexType::Equality),
696 (Attribute::Class, IndexType::Presence),
697 (Attribute::Member, IndexType::Equality),
698 (Attribute::Member, IndexType::Presence),
699 (Attribute::MemberOf, IndexType::Equality),
700 (Attribute::MemberOf, IndexType::Presence),
701 (Attribute::DirectMemberOf, IndexType::Equality),
702 (Attribute::DirectMemberOf, IndexType::Presence),
703 ];
704
705 let idxmeta_ref = idxmeta.iter().map(|(attr, itype)| (attr, itype)).collect();
706
707 Filter {
708 state: FilterValidResolved {
709 inner: FilterResolved::from_invalid(self.state.inner, &idxmeta_ref),
710 },
711 }
712 }
713
714 #[cfg(test)]
717 pub fn into_valid(self) -> Filter<FilterValid> {
718 Filter {
725 state: FilterValid {
726 inner: self.state.inner,
727 },
728 }
729 }
730
731 pub fn validate(
732 &self,
733 schema: &dyn SchemaTransaction,
734 ) -> Result<Filter<FilterValid>, SchemaError> {
735 Ok(Filter {
738 state: FilterValid {
739 inner: self.state.inner.validate(schema)?,
740 },
741 })
742 }
743
744 #[instrument(name = "filter::from_ro", level = "trace", skip_all)]
748 pub fn from_ro(
749 ev: &Identity,
750 f: &ProtoFilter,
751 qs: &mut QueryServerReadTransaction,
752 ) -> Result<Self, OperationError> {
753 let depth = DEFAULT_LIMIT_FILTER_DEPTH_MAX as usize;
754 let mut elems = ev.limits().filter_max_elements;
755 Ok(Filter {
756 state: FilterInvalid {
757 inner: FilterComp::from_ro(f, qs, depth, &mut elems)?,
758 },
759 })
760 }
761
762 #[instrument(name = "filter::from_rw", level = "trace", skip_all)]
763 pub fn from_rw(
764 ev: &Identity,
765 f: &ProtoFilter,
766 qs: &mut QueryServerWriteTransaction,
767 ) -> Result<Self, OperationError> {
768 let depth = DEFAULT_LIMIT_FILTER_DEPTH_MAX as usize;
769 let mut elems = ev.limits().filter_max_elements;
770 Ok(Filter {
771 state: FilterInvalid {
772 inner: FilterComp::from_rw(f, qs, depth, &mut elems)?,
773 },
774 })
775 }
776
777 #[instrument(name = "filter::from_ldap_ro", level = "trace", skip_all)]
778 pub fn from_ldap_ro(
779 ev: &Identity,
780 f: &LdapFilter,
781 qs: &mut QueryServerReadTransaction,
782 ) -> Result<Self, OperationError> {
783 let depth = DEFAULT_LIMIT_FILTER_DEPTH_MAX as usize;
784 let mut elems = ev.limits().filter_max_elements;
785 Ok(Filter {
786 state: FilterInvalid {
787 inner: FilterComp::from_ldap_ro(f, qs, depth, &mut elems)?,
788 },
789 })
790 }
791
792 #[instrument(name = "filter::from_scim_ro", level = "trace", skip_all)]
793 pub fn from_scim_ro(
794 ev: &Identity,
795 f: &ScimFilter,
796 qs: &mut QueryServerReadTransaction,
797 ) -> Result<Self, OperationError> {
798 let depth = DEFAULT_LIMIT_FILTER_DEPTH_MAX as usize;
799 let mut elems = ev.limits().filter_max_elements;
800 Ok(Filter {
801 state: FilterInvalid {
802 inner: FilterComp::from_scim_ro(f, qs, depth, &mut elems)?,
803 },
804 })
805 }
806}
807
808impl FromStr for Filter<FilterInvalid> {
809 type Err = OperationError;
810 fn from_str(s: &str) -> Result<Self, Self::Err> {
811 let f: FC = serde_json::from_str(s).map_err(|_| OperationError::FilterParseError)?;
812 Ok(Filter {
813 state: FilterInvalid {
814 inner: FilterComp::new(f),
815 },
816 })
817 }
818}
819
820impl FilterComp {
821 fn new(fc: FC) -> Self {
822 match fc {
823 FC::Eq(a, v) => FilterComp::Eq(a, v),
824 FC::Cnt(a, v) => FilterComp::Cnt(a, v),
825 FC::Pres(a) => FilterComp::Pres(a),
826 FC::LessThan(a, v) => FilterComp::LessThan(a, v),
827 FC::Or(v) => FilterComp::Or(v.into_iter().map(FilterComp::new).collect()),
828 FC::And(v) => FilterComp::And(v.into_iter().map(FilterComp::new).collect()),
829 FC::Inclusion(v) => FilterComp::Inclusion(v.into_iter().map(FilterComp::new).collect()),
830 FC::AndNot(b) => FilterComp::AndNot(Box::new(FilterComp::new(*b))),
831 FC::SelfUuid => FilterComp::SelfUuid,
832 FC::Invalid(a) => FilterComp::Invalid(a),
833 }
834 }
835
836 fn new_ignore_hidden(fc: FilterComp) -> Self {
837 FilterComp::And(vec![
838 FilterComp::AndNot(Box::new(FilterComp::Or(vec![
839 FilterComp::Eq(Attribute::Class, EntryClass::Tombstone.into()),
840 FilterComp::Eq(Attribute::Class, EntryClass::Recycled.into()),
841 ]))),
842 fc,
843 ])
844 }
845
846 fn new_recycled(fc: FilterComp) -> Self {
847 FilterComp::And(vec![
848 FilterComp::Eq(Attribute::Class, EntryClass::Recycled.into()),
849 fc,
850 ])
851 }
852
853 fn get_attr_set(&self, r_set: &mut BTreeSet<Attribute>) {
854 match self {
855 FilterComp::Eq(attr, _)
856 | FilterComp::Cnt(attr, _)
857 | FilterComp::Stw(attr, _)
858 | FilterComp::Enw(attr, _)
859 | FilterComp::Pres(attr)
860 | FilterComp::LessThan(attr, _)
861 | FilterComp::Invalid(attr) => {
862 r_set.insert(attr.clone());
863 }
864 FilterComp::Or(vs) => vs.iter().for_each(|f| f.get_attr_set(r_set)),
865 FilterComp::And(vs) => vs.iter().for_each(|f| f.get_attr_set(r_set)),
866 FilterComp::Inclusion(vs) => vs.iter().for_each(|f| f.get_attr_set(r_set)),
867 FilterComp::AndNot(f) => f.get_attr_set(r_set),
868 FilterComp::SelfUuid => {
869 r_set.insert(Attribute::Uuid);
870 }
871 }
872 }
873
874 fn validate(&self, schema: &dyn SchemaTransaction) -> Result<FilterComp, SchemaError> {
875 let schema_attributes = schema.get_attributes();
882 match self {
887 FilterComp::Eq(attr, value) => {
888 match schema_attributes.get(attr) {
891 Some(schema_a) => {
892 schema_a
893 .validate_partialvalue(attr, value)
894 .map(|_| FilterComp::Eq(attr.clone(), value.clone()))
896 }
898 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
899 }
900 }
901 FilterComp::Cnt(attr, value) => {
902 match schema_attributes.get(attr) {
903 Some(schema_a) => {
904 schema_a
905 .validate_partialvalue(attr, value)
906 .map(|_| FilterComp::Cnt(attr.clone(), value.clone()))
908 }
910 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
911 }
912 }
913 FilterComp::Stw(attr, value) => {
914 match schema_attributes.get(attr) {
915 Some(schema_a) => {
916 schema_a
917 .validate_partialvalue(attr, value)
918 .map(|_| FilterComp::Stw(attr.clone(), value.clone()))
920 }
922 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
923 }
924 }
925 FilterComp::Enw(attr, value) => {
926 match schema_attributes.get(attr) {
927 Some(schema_a) => {
928 schema_a
929 .validate_partialvalue(attr, value)
930 .map(|_| FilterComp::Enw(attr.clone(), value.clone()))
932 }
934 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
935 }
936 }
937 FilterComp::Pres(attr) => {
938 match schema_attributes.get(attr) {
939 Some(_attr_name) => {
940 Ok(FilterComp::Pres(attr.clone()))
942 }
943 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
944 }
945 }
946 FilterComp::LessThan(attr, value) => {
947 match schema_attributes.get(attr) {
948 Some(schema_a) => {
949 schema_a
950 .validate_partialvalue(attr, value)
951 .map(|_| FilterComp::LessThan(attr.clone(), value.clone()))
953 }
955 None => Err(SchemaError::InvalidAttribute(attr.to_string())),
956 }
957 }
958 FilterComp::Or(filters) => {
959 if filters.is_empty() {
964 return Err(SchemaError::EmptyFilter);
965 };
966 let x: Result<Vec<_>, _> = filters
967 .iter()
968 .map(|filter| filter.validate(schema))
969 .collect();
970 x.map(FilterComp::Or)
972 }
973 FilterComp::And(filters) => {
974 if filters.is_empty() {
979 return Err(SchemaError::EmptyFilter);
980 };
981 let x: Result<Vec<_>, _> = filters
982 .iter()
983 .map(|filter| filter.validate(schema))
984 .collect();
985 x.map(FilterComp::And)
987 }
988 FilterComp::Inclusion(filters) => {
989 if filters.is_empty() {
990 return Err(SchemaError::EmptyFilter);
991 };
992 let x: Result<Vec<_>, _> = filters
993 .iter()
994 .map(|filter| filter.validate(schema))
995 .collect();
996 x.map(FilterComp::Inclusion)
998 }
999 FilterComp::AndNot(filter) => {
1000 filter
1002 .validate(schema)
1003 .map(|r_filter| FilterComp::AndNot(Box::new(r_filter)))
1004 }
1005 FilterComp::SelfUuid => {
1006 Ok(FilterComp::SelfUuid)
1008 }
1009 FilterComp::Invalid(attr) => {
1010 Ok(FilterComp::Invalid(attr.clone()))
1013 }
1014 }
1015 }
1016
1017 fn from_ro(
1018 f: &ProtoFilter,
1019 qs: &mut QueryServerReadTransaction,
1020 depth: usize,
1021 elems: &mut usize,
1022 ) -> Result<Self, OperationError> {
1023 let ndepth = depth.checked_sub(1).ok_or(OperationError::ResourceLimit)?;
1024 Ok(match f {
1025 ProtoFilter::Eq(a, v) => {
1026 let nk = Attribute::from(a.as_str());
1027 let v = qs.clone_partialvalue(&nk, v)?;
1028 FilterComp::Eq(nk, v)
1029 }
1030 ProtoFilter::Cnt(a, v) => {
1031 let nk = Attribute::from(a.as_str());
1032 let v = qs.clone_partialvalue(&nk, v)?;
1033 FilterComp::Cnt(nk, v)
1034 }
1035 ProtoFilter::Pres(a) => {
1036 let nk = Attribute::from(a.as_str());
1037 FilterComp::Pres(nk)
1038 }
1039 ProtoFilter::Or(l) => {
1040 *elems = (*elems)
1041 .checked_sub(l.len())
1042 .ok_or(OperationError::ResourceLimit)?;
1043 FilterComp::Or(
1044 l.iter()
1045 .map(|f| Self::from_ro(f, qs, ndepth, elems))
1046 .collect::<Result<Vec<_>, _>>()?,
1047 )
1048 }
1049 ProtoFilter::And(l) => {
1050 *elems = (*elems)
1051 .checked_sub(l.len())
1052 .ok_or(OperationError::ResourceLimit)?;
1053 FilterComp::And(
1054 l.iter()
1055 .map(|f| Self::from_ro(f, qs, ndepth, elems))
1056 .collect::<Result<Vec<_>, _>>()?,
1057 )
1058 }
1059 ProtoFilter::AndNot(l) => {
1060 *elems = (*elems)
1061 .checked_sub(1)
1062 .ok_or(OperationError::ResourceLimit)?;
1063 FilterComp::AndNot(Box::new(Self::from_ro(l, qs, ndepth, elems)?))
1064 }
1065 ProtoFilter::SelfUuid => FilterComp::SelfUuid,
1066 })
1067 }
1068
1069 fn from_rw(
1070 f: &ProtoFilter,
1071 qs: &mut QueryServerWriteTransaction,
1072 depth: usize,
1073 elems: &mut usize,
1074 ) -> Result<Self, OperationError> {
1075 let ndepth = depth.checked_sub(1).ok_or(OperationError::ResourceLimit)?;
1076 Ok(match f {
1077 ProtoFilter::Eq(a, v) => {
1078 let nk = Attribute::from(a.as_str());
1079 let v = qs.clone_partialvalue(&nk, v)?;
1080 FilterComp::Eq(nk, v)
1081 }
1082 ProtoFilter::Cnt(a, v) => {
1083 let nk = Attribute::from(a.as_str());
1084 let v = qs.clone_partialvalue(&nk, v)?;
1085 FilterComp::Cnt(nk, v)
1086 }
1087 ProtoFilter::Pres(a) => {
1088 let nk = Attribute::from(a.as_str());
1089 FilterComp::Pres(nk)
1090 }
1091 ProtoFilter::Or(l) => {
1092 *elems = (*elems)
1093 .checked_sub(l.len())
1094 .ok_or(OperationError::ResourceLimit)?;
1095 FilterComp::Or(
1096 l.iter()
1097 .map(|f| Self::from_rw(f, qs, ndepth, elems))
1098 .collect::<Result<Vec<_>, _>>()?,
1099 )
1100 }
1101 ProtoFilter::And(l) => {
1102 *elems = (*elems)
1103 .checked_sub(l.len())
1104 .ok_or(OperationError::ResourceLimit)?;
1105 FilterComp::And(
1106 l.iter()
1107 .map(|f| Self::from_rw(f, qs, ndepth, elems))
1108 .collect::<Result<Vec<_>, _>>()?,
1109 )
1110 }
1111 ProtoFilter::AndNot(l) => {
1112 *elems = (*elems)
1113 .checked_sub(1)
1114 .ok_or(OperationError::ResourceLimit)?;
1115
1116 FilterComp::AndNot(Box::new(Self::from_rw(l, qs, ndepth, elems)?))
1117 }
1118 ProtoFilter::SelfUuid => FilterComp::SelfUuid,
1119 })
1120 }
1121
1122 fn from_ldap_ro(
1123 f: &LdapFilter,
1124 qs: &mut QueryServerReadTransaction,
1125 depth: usize,
1126 elems: &mut usize,
1127 ) -> Result<Self, OperationError> {
1128 let ndepth = depth.checked_sub(1).ok_or(OperationError::ResourceLimit)?;
1129 *elems = (*elems)
1130 .checked_sub(1)
1131 .ok_or(OperationError::ResourceLimit)?;
1132 Ok(match f {
1133 LdapFilter::And(l) => FilterComp::And(
1134 l.iter()
1135 .map(|f| Self::from_ldap_ro(f, qs, ndepth, elems))
1136 .collect::<Result<Vec<_>, _>>()?,
1137 ),
1138 LdapFilter::Or(l) => FilterComp::Or(
1139 l.iter()
1140 .map(|f| Self::from_ldap_ro(f, qs, ndepth, elems))
1141 .collect::<Result<Vec<_>, _>>()?,
1142 ),
1143 LdapFilter::Not(l) => {
1144 FilterComp::AndNot(Box::new(Self::from_ldap_ro(l, qs, ndepth, elems)?))
1145 }
1146 LdapFilter::Equality(a, v) => {
1147 let a = ldap_attr_filter_map(a);
1148 let pv = qs.clone_partialvalue(&a, v);
1149
1150 match pv {
1151 Ok(pv) => FilterComp::Eq(a, pv),
1152 Err(_) if a == Attribute::Spn => FilterComp::Invalid(a),
1153 Err(err) => return Err(err),
1154 }
1155 }
1156 LdapFilter::Present(a) => FilterComp::Pres(ldap_attr_filter_map(a)),
1157 LdapFilter::Substring(
1158 a,
1159 LdapSubstringFilter {
1160 initial,
1161 any,
1162 final_,
1163 },
1164 ) => {
1165 let a = ldap_attr_filter_map(a);
1166
1167 let mut terms = Vec::with_capacity(any.len() + 2);
1168 if let Some(ini) = initial {
1169 let v = qs.clone_partialvalue(&a, ini)?;
1170 terms.push(FilterComp::Stw(a.clone(), v));
1171 }
1172
1173 for term in any.iter() {
1174 let v = qs.clone_partialvalue(&a, term)?;
1175 terms.push(FilterComp::Cnt(a.clone(), v));
1176 }
1177
1178 if let Some(fin) = final_ {
1179 let v = qs.clone_partialvalue(&a, fin)?;
1180 terms.push(FilterComp::Enw(a.clone(), v));
1181 }
1182
1183 FilterComp::And(terms)
1184 }
1185 LdapFilter::GreaterOrEqual(_, _) => {
1186 admin_error!("Unsupported filter operation - greater or equal");
1187 return Err(OperationError::FilterGeneration);
1188 }
1189 LdapFilter::LessOrEqual(_, _) => {
1190 admin_error!("Unsupported filter operation - less or equal");
1191 return Err(OperationError::FilterGeneration);
1192 }
1193 LdapFilter::Approx(_, _) => {
1194 admin_error!("Unsupported filter operation - approximate");
1195 return Err(OperationError::FilterGeneration);
1196 }
1197 LdapFilter::Extensible(_) => {
1198 admin_error!("Unsupported filter operation - extensible");
1199 return Err(OperationError::FilterGeneration);
1200 }
1201 })
1202 }
1203
1204 fn from_scim_ro(
1205 f: &ScimFilter,
1206 qs: &mut QueryServerReadTransaction,
1207 depth: usize,
1208 elems: &mut usize,
1209 ) -> Result<Self, OperationError> {
1210 let ndepth = depth.checked_sub(1).ok_or(OperationError::ResourceLimit)?;
1211 *elems = (*elems)
1212 .checked_sub(1)
1213 .ok_or(OperationError::ResourceLimit)?;
1214 Ok(match f {
1215 ScimFilter::Present(ScimAttrPath { a, s: None }) => FilterComp::Pres(a.clone()),
1216 ScimFilter::Equal(ScimAttrPath { a, s: None }, json_value) => {
1217 let pv = qs.resolve_scim_json_get(a, json_value)?;
1218 FilterComp::Eq(a.clone(), pv)
1219 }
1220 ScimFilter::Contains(ScimAttrPath { a, s: None }, json_value) => {
1221 let pv = qs.resolve_scim_json_get(a, json_value)?;
1222 FilterComp::Cnt(a.clone(), pv)
1223 }
1224 ScimFilter::StartsWith(ScimAttrPath { a, s: None }, json_value) => {
1225 let pv = qs.resolve_scim_json_get(a, json_value)?;
1226 FilterComp::Stw(a.clone(), pv)
1227 }
1228 ScimFilter::EndsWith(ScimAttrPath { a, s: None }, json_value) => {
1229 let pv = qs.resolve_scim_json_get(a, json_value)?;
1230 FilterComp::Enw(a.clone(), pv)
1231 }
1232 ScimFilter::Greater(ScimAttrPath { a, s: None }, json_value) => {
1233 let pv = qs.resolve_scim_json_get(a, json_value)?;
1234 FilterComp::And(vec![
1236 FilterComp::Pres(a.clone()),
1237 FilterComp::AndNot(Box::new(FilterComp::Or(vec![
1238 FilterComp::LessThan(a.clone(), pv.clone()),
1239 FilterComp::Eq(a.clone(), pv),
1240 ]))),
1241 ])
1242 }
1243 ScimFilter::Less(ScimAttrPath { a, s: None }, json_value) => {
1244 let pv = qs.resolve_scim_json_get(a, json_value)?;
1245 FilterComp::LessThan(a.clone(), pv)
1246 }
1247 ScimFilter::GreaterOrEqual(ScimAttrPath { a, s: None }, json_value) => {
1248 let pv = qs.resolve_scim_json_get(a, json_value)?;
1249 FilterComp::And(vec![
1251 FilterComp::Pres(a.clone()),
1252 FilterComp::AndNot(Box::new(FilterComp::LessThan(a.clone(), pv.clone()))),
1253 ])
1254 }
1255 ScimFilter::LessOrEqual(ScimAttrPath { a, s: None }, json_value) => {
1256 let pv = qs.resolve_scim_json_get(a, json_value)?;
1257 FilterComp::Or(vec![
1258 FilterComp::LessThan(a.clone(), pv.clone()),
1259 FilterComp::Eq(a.clone(), pv),
1260 ])
1261 }
1262 ScimFilter::Not(f) => {
1263 let f = Self::from_scim_ro(f, qs, ndepth, elems)?;
1264 FilterComp::AndNot(Box::new(f))
1265 }
1266 ScimFilter::Or(left, right) => {
1267 let left = Self::from_scim_ro(left, qs, ndepth, elems)?;
1268 let right = Self::from_scim_ro(right, qs, ndepth, elems)?;
1269 FilterComp::Or(vec![left, right])
1270 }
1271 ScimFilter::And(left, right) => {
1272 let left = Self::from_scim_ro(left, qs, ndepth, elems)?;
1273 let right = Self::from_scim_ro(right, qs, ndepth, elems)?;
1274 FilterComp::And(vec![left, right])
1275 }
1276 ScimFilter::NotEqual(ScimAttrPath { s: None, .. }, _) => {
1277 error!("Unsupported filter operation - not-equal");
1278 return Err(OperationError::FilterGeneration);
1279 }
1280 ScimFilter::Present(ScimAttrPath { s: Some(_), .. })
1281 | ScimFilter::Equal(ScimAttrPath { s: Some(_), .. }, _)
1282 | ScimFilter::NotEqual(ScimAttrPath { s: Some(_), .. }, _)
1283 | ScimFilter::Contains(ScimAttrPath { s: Some(_), .. }, _)
1284 | ScimFilter::StartsWith(ScimAttrPath { s: Some(_), .. }, _)
1285 | ScimFilter::EndsWith(ScimAttrPath { s: Some(_), .. }, _)
1286 | ScimFilter::Greater(ScimAttrPath { s: Some(_), .. }, _)
1287 | ScimFilter::Less(ScimAttrPath { s: Some(_), .. }, _)
1288 | ScimFilter::GreaterOrEqual(ScimAttrPath { s: Some(_), .. }, _)
1289 | ScimFilter::LessOrEqual(ScimAttrPath { s: Some(_), .. }, _) => {
1290 error!("Unsupported filter operation - sub-attribute");
1291 return Err(OperationError::FilterGeneration);
1292 }
1293 ScimFilter::Complex(..) => {
1294 error!("Unsupported filter operation - complex");
1295 return Err(OperationError::FilterGeneration);
1296 }
1297 })
1298 }
1299}
1300
1301#[cfg(test)]
1327impl PartialOrd for Filter<FilterValidResolved> {
1328 fn partial_cmp(&self, rhs: &Filter<FilterValidResolved>) -> Option<Ordering> {
1329 self.state.inner.partial_cmp(&rhs.state.inner)
1330 }
1331}
1332
1333impl PartialEq for FilterResolved {
1334 fn eq(&self, rhs: &FilterResolved) -> bool {
1335 match (self, rhs) {
1336 (FilterResolved::Eq(a1, v1, _), FilterResolved::Eq(a2, v2, _)) => a1 == a2 && v1 == v2,
1337 (FilterResolved::Cnt(a1, v1, _), FilterResolved::Cnt(a2, v2, _)) => {
1338 a1 == a2 && v1 == v2
1339 }
1340 (FilterResolved::Pres(a1, _), FilterResolved::Pres(a2, _)) => a1 == a2,
1341 (FilterResolved::LessThan(a1, v1, _), FilterResolved::LessThan(a2, v2, _)) => {
1342 a1 == a2 && v1 == v2
1343 }
1344 (FilterResolved::And(vs1, _), FilterResolved::And(vs2, _)) => vs1 == vs2,
1345 (FilterResolved::Or(vs1, _), FilterResolved::Or(vs2, _)) => vs1 == vs2,
1346 (FilterResolved::Inclusion(vs1, _), FilterResolved::Inclusion(vs2, _)) => vs1 == vs2,
1347 (FilterResolved::AndNot(f1, _), FilterResolved::AndNot(f2, _)) => f1 == f2,
1348 (_, _) => false,
1349 }
1350 }
1351}
1352
1353impl PartialOrd for FilterResolved {
1354 fn partial_cmp(&self, rhs: &FilterResolved) -> Option<Ordering> {
1355 Some(self.cmp(rhs))
1356 }
1357}
1358
1359impl Ord for FilterResolved {
1360 fn cmp(&self, rhs: &FilterResolved) -> Ordering {
1362 let left_slopey = self.get_slopeyness_factor();
1363 let right_slopey = rhs.get_slopeyness_factor();
1364
1365 let r = match (left_slopey, right_slopey) {
1366 (Some(sfl), Some(sfr)) => sfl.cmp(&sfr),
1367 (Some(_), None) => Ordering::Less,
1368 (None, Some(_)) => Ordering::Greater,
1369 (None, None) => Ordering::Equal,
1370 };
1371
1372 if r == Ordering::Equal {
1379 match (self, rhs) {
1380 (FilterResolved::Eq(a1, v1, _), FilterResolved::Eq(a2, v2, _))
1381 | (FilterResolved::Cnt(a1, v1, _), FilterResolved::Cnt(a2, v2, _))
1382 | (FilterResolved::LessThan(a1, v1, _), FilterResolved::LessThan(a2, v2, _)) => {
1383 match a1.cmp(a2) {
1384 Ordering::Equal => v1.cmp(v2),
1385 o => o,
1386 }
1387 }
1388 (FilterResolved::Pres(a1, _), FilterResolved::Pres(a2, _)) => a1.cmp(a2),
1389 (FilterResolved::Eq(_, _, _), _) => Ordering::Less,
1391 (_, FilterResolved::Eq(_, _, _)) => Ordering::Greater,
1392 (FilterResolved::Pres(_, _), _) => Ordering::Less,
1393 (_, FilterResolved::Pres(_, _)) => Ordering::Greater,
1394 (FilterResolved::LessThan(_, _, _), _) => Ordering::Less,
1395 (_, FilterResolved::LessThan(_, _, _)) => Ordering::Greater,
1396 (FilterResolved::Cnt(_, _, _), _) => Ordering::Less,
1397 (_, FilterResolved::Cnt(_, _, _)) => Ordering::Greater,
1398 (_, _) => Ordering::Equal,
1400 }
1401 } else {
1402 r
1403 }
1404 }
1405}
1406
1407impl FilterResolved {
1408 #[cfg(test)]
1411 fn from_invalid(fc: FilterComp, idxmeta: &HashSet<(&Attribute, &IndexType)>) -> Self {
1412 match fc {
1413 FilterComp::Eq(a, v) => {
1414 let idx = idxmeta.contains(&(&a, &IndexType::Equality));
1415 let idx = NonZeroU8::new(idx as u8);
1416 FilterResolved::Eq(a, v, idx)
1417 }
1418 FilterComp::SelfUuid => panic!("Not possible to resolve SelfUuid in from_invalid!"),
1419 FilterComp::Invalid(attr) => FilterResolved::Invalid(attr),
1420 FilterComp::Cnt(a, v) => {
1421 let idx = idxmeta.contains(&(&a, &IndexType::SubString));
1422 let idx = NonZeroU8::new(idx as u8);
1423 FilterResolved::Cnt(a, v, idx)
1424 }
1425 FilterComp::Stw(a, v) => {
1426 let idx = idxmeta.contains(&(&a, &IndexType::SubString));
1427 let idx = NonZeroU8::new(idx as u8);
1428 FilterResolved::Stw(a, v, idx)
1429 }
1430 FilterComp::Enw(a, v) => {
1431 let idx = idxmeta.contains(&(&a, &IndexType::SubString));
1432 let idx = NonZeroU8::new(idx as u8);
1433 FilterResolved::Enw(a, v, idx)
1434 }
1435 FilterComp::Pres(a) => {
1436 let idx = idxmeta.contains(&(&a, &IndexType::Presence));
1437 FilterResolved::Pres(a, NonZeroU8::new(idx as u8))
1438 }
1439 FilterComp::LessThan(a, v) => {
1440 let idx = idxmeta.contains(&(&a, &IndexType::Ordering));
1441 FilterResolved::LessThan(a, v, NonZeroU8::new(idx as u8))
1442 }
1443 FilterComp::Or(vs) => FilterResolved::Or(
1444 vs.into_iter()
1445 .map(|v| FilterResolved::from_invalid(v, idxmeta))
1446 .collect(),
1447 None,
1448 ),
1449 FilterComp::And(vs) => FilterResolved::And(
1450 vs.into_iter()
1451 .map(|v| FilterResolved::from_invalid(v, idxmeta))
1452 .collect(),
1453 None,
1454 ),
1455 FilterComp::Inclusion(vs) => FilterResolved::Inclusion(
1456 vs.into_iter()
1457 .map(|v| FilterResolved::from_invalid(v, idxmeta))
1458 .collect(),
1459 None,
1460 ),
1461 FilterComp::AndNot(f) => {
1462 FilterResolved::AndNot(
1468 Box::new(FilterResolved::from_invalid((*f).clone(), idxmeta)),
1469 None,
1470 )
1471 }
1472 }
1473 }
1474
1475 fn resolve_cacheable(fc: &FilterComp) -> bool {
1476 match fc {
1477 FilterComp::Or(vs) | FilterComp::And(vs) | FilterComp::Inclusion(vs) => {
1478 if vs.len() < 8 {
1479 vs.iter().all(FilterResolved::resolve_cacheable)
1480 } else {
1481 false
1483 }
1484 }
1485 FilterComp::AndNot(f) => FilterResolved::resolve_cacheable(f.as_ref()),
1486 FilterComp::Eq(..)
1487 | FilterComp::SelfUuid
1488 | FilterComp::Cnt(..)
1489 | FilterComp::Stw(..)
1490 | FilterComp::Enw(..)
1491 | FilterComp::Pres(_)
1492 | FilterComp::Invalid(_)
1493 | FilterComp::LessThan(..) => true,
1494 }
1495 }
1496
1497 fn resolve_idx(
1498 fc: FilterComp,
1499 ev: &Identity,
1500 idxmeta: &HashMap<IdxKey, IdxSlope>,
1501 ) -> Option<Self> {
1502 match fc {
1503 FilterComp::Eq(a, v) => {
1504 let idxkref = IdxKeyRef::new(&a, &IndexType::Equality);
1505 let idx = idxmeta
1506 .get(&idxkref as &dyn IdxKeyToRef)
1507 .copied()
1508 .and_then(NonZeroU8::new);
1509 Some(FilterResolved::Eq(a, v, idx))
1510 }
1511 FilterComp::SelfUuid => {
1512 let uuid = ev.get_uuid();
1513 let idxkref = IdxKeyRef::new(Attribute::Uuid.as_ref(), &IndexType::Equality);
1514 let idx = idxmeta
1515 .get(&idxkref as &dyn IdxKeyToRef)
1516 .copied()
1517 .and_then(NonZeroU8::new);
1518 Some(FilterResolved::Eq(
1519 Attribute::Uuid,
1520 PartialValue::Uuid(uuid),
1521 idx,
1522 ))
1523 }
1524 FilterComp::Cnt(a, v) => {
1525 let idxkref = IdxKeyRef::new(&a, &IndexType::SubString);
1526 let idx = idxmeta
1527 .get(&idxkref as &dyn IdxKeyToRef)
1528 .copied()
1529 .and_then(NonZeroU8::new);
1530 Some(FilterResolved::Cnt(a, v, idx))
1531 }
1532 FilterComp::Stw(a, v) => {
1533 let idxkref = IdxKeyRef::new(&a, &IndexType::SubString);
1534 let idx = idxmeta
1535 .get(&idxkref as &dyn IdxKeyToRef)
1536 .copied()
1537 .and_then(NonZeroU8::new);
1538 Some(FilterResolved::Stw(a, v, idx))
1539 }
1540 FilterComp::Enw(a, v) => {
1541 let idxkref = IdxKeyRef::new(&a, &IndexType::SubString);
1542 let idx = idxmeta
1543 .get(&idxkref as &dyn IdxKeyToRef)
1544 .copied()
1545 .and_then(NonZeroU8::new);
1546 Some(FilterResolved::Enw(a, v, idx))
1547 }
1548 FilterComp::Pres(a) => {
1549 let idxkref = IdxKeyRef::new(&a, &IndexType::Presence);
1550 let idx = idxmeta
1551 .get(&idxkref as &dyn IdxKeyToRef)
1552 .copied()
1553 .and_then(NonZeroU8::new);
1554 Some(FilterResolved::Pres(a, idx))
1555 }
1556 FilterComp::LessThan(a, v) => {
1557 let idxkref = IdxKeyRef::new(&a, &IndexType::Ordering);
1558 let idx = idxmeta
1559 .get(&idxkref as &dyn IdxKeyToRef)
1560 .copied()
1561 .and_then(NonZeroU8::new);
1562 Some(FilterResolved::LessThan(a, v, idx))
1563 }
1564 FilterComp::Or(vs) => {
1568 let fi: Option<Vec<_>> = vs
1569 .into_iter()
1570 .map(|f| FilterResolved::resolve_idx(f, ev, idxmeta))
1571 .collect();
1572 fi.map(|fi| FilterResolved::Or(fi, None))
1573 }
1574 FilterComp::And(vs) => {
1575 let fi: Option<Vec<_>> = vs
1576 .into_iter()
1577 .map(|f| FilterResolved::resolve_idx(f, ev, idxmeta))
1578 .collect();
1579 fi.map(|fi| FilterResolved::And(fi, None))
1580 }
1581 FilterComp::Inclusion(vs) => {
1582 let fi: Option<Vec<_>> = vs
1583 .into_iter()
1584 .map(|f| FilterResolved::resolve_idx(f, ev, idxmeta))
1585 .collect();
1586 fi.map(|fi| FilterResolved::Inclusion(fi, None))
1587 }
1588 FilterComp::AndNot(f) => {
1589 FilterResolved::resolve_idx((*f).clone(), ev, idxmeta)
1595 .map(|fi| FilterResolved::AndNot(Box::new(fi), None))
1596 }
1597 FilterComp::Invalid(attr) => Some(FilterResolved::Invalid(attr)),
1598 }
1599 }
1600
1601 fn resolve_no_idx(fc: FilterComp, ev: &Identity) -> Option<Self> {
1602 match fc {
1606 FilterComp::Eq(a, v) => {
1607 let idx = matches!(a.as_str(), ATTR_NAME | ATTR_UUID);
1611 let idx = NonZeroU8::new(idx as u8);
1612 Some(FilterResolved::Eq(a, v, idx))
1613 }
1614 FilterComp::SelfUuid => {
1615 let uuid = ev.get_uuid();
1616 Some(FilterResolved::Eq(
1617 Attribute::Uuid,
1618 PartialValue::Uuid(uuid),
1619 NonZeroU8::new(true as u8),
1620 ))
1621 }
1622 FilterComp::Cnt(a, v) => Some(FilterResolved::Cnt(a, v, None)),
1623 FilterComp::Stw(a, v) => Some(FilterResolved::Stw(a, v, None)),
1624 FilterComp::Enw(a, v) => Some(FilterResolved::Enw(a, v, None)),
1625 FilterComp::Pres(a) => Some(FilterResolved::Pres(a, None)),
1626 FilterComp::LessThan(a, v) => Some(FilterResolved::LessThan(a, v, None)),
1627 FilterComp::Or(vs) => {
1628 let fi: Option<Vec<_>> = vs
1629 .into_iter()
1630 .map(|f| FilterResolved::resolve_no_idx(f, ev))
1631 .collect();
1632 fi.map(|fi| FilterResolved::Or(fi, None))
1633 }
1634 FilterComp::And(vs) => {
1635 let fi: Option<Vec<_>> = vs
1636 .into_iter()
1637 .map(|f| FilterResolved::resolve_no_idx(f, ev))
1638 .collect();
1639 fi.map(|fi| FilterResolved::And(fi, None))
1640 }
1641 FilterComp::Inclusion(vs) => {
1642 let fi: Option<Vec<_>> = vs
1643 .into_iter()
1644 .map(|f| FilterResolved::resolve_no_idx(f, ev))
1645 .collect();
1646 fi.map(|fi| FilterResolved::Inclusion(fi, None))
1647 }
1648 FilterComp::AndNot(f) => {
1649 FilterResolved::resolve_no_idx((*f).clone(), ev)
1655 .map(|fi| FilterResolved::AndNot(Box::new(fi), None))
1656 }
1657 FilterComp::Invalid(attr) => Some(FilterResolved::Invalid(attr)),
1658 }
1659 }
1660
1661 fn fast_optimise(self) -> Self {
1663 match self {
1664 FilterResolved::Inclusion(mut f_list, _) => {
1665 f_list.sort_unstable();
1666 f_list.dedup();
1667 let sf = f_list.last().and_then(|f| f.get_slopeyness_factor());
1668 FilterResolved::Inclusion(f_list, sf)
1669 }
1670 FilterResolved::And(mut f_list, _) => {
1671 f_list.sort_unstable();
1672 f_list.dedup();
1673 let sf = f_list.first().and_then(|f| f.get_slopeyness_factor());
1674 FilterResolved::And(f_list, sf)
1675 }
1676 v => v,
1677 }
1678 }
1679
1680 fn optimise(&self) -> Self {
1681 match self {
1683 FilterResolved::Inclusion(f_list, _) => {
1684 let (f_list_inc, mut f_list_new): (Vec<_>, Vec<_>) = f_list
1686 .iter()
1687 .map(|f_ref| f_ref.optimise())
1688 .partition(|f| matches!(f, FilterResolved::Inclusion(_, _)));
1689
1690 f_list_inc.into_iter().for_each(|fc| {
1691 if let FilterResolved::Inclusion(mut l, _) = fc {
1692 f_list_new.append(&mut l)
1693 }
1694 });
1695 f_list_new.sort_unstable();
1697 f_list_new.dedup();
1698 let sf = f_list_new.last().and_then(|f| f.get_slopeyness_factor());
1700 FilterResolved::Inclusion(f_list_new, sf)
1701 }
1702 FilterResolved::And(f_list, _) => {
1703 let (f_list_and, mut f_list_new): (Vec<_>, Vec<_>) = f_list
1705 .iter()
1706 .map(|f_ref| f_ref.optimise())
1707 .partition(|f| matches!(f, FilterResolved::And(_, _)));
1708
1709 f_list_and.into_iter().for_each(|fc| {
1722 if let FilterResolved::And(mut l, _) = fc {
1723 f_list_new.append(&mut l)
1724 }
1725 });
1726
1727 if f_list_new.len() == 1 {
1729 f_list_new.remove(0)
1730 } else {
1731 f_list_new.sort_unstable();
1733 f_list_new.dedup();
1734 let sf = f_list_new.first().and_then(|f| f.get_slopeyness_factor());
1738 FilterResolved::And(f_list_new, sf)
1741 }
1742 }
1743 FilterResolved::Or(f_list, _) => {
1744 let (f_list_or, mut f_list_new): (Vec<_>, Vec<_>) = f_list
1745 .iter()
1746 .map(|f_ref| f_ref.optimise())
1748 .partition(|f| matches!(f, FilterResolved::Or(_, _)));
1750
1751 f_list_or.into_iter().for_each(|fc| {
1753 if let FilterResolved::Or(mut l, _) = fc {
1754 f_list_new.append(&mut l)
1755 }
1756 });
1757
1758 if f_list_new.len() == 1 {
1760 f_list_new.remove(0)
1761 } else {
1762 #[allow(clippy::unnecessary_sort_by)]
1769 f_list_new.sort_unstable_by(|a, b| b.cmp(a));
1770 f_list_new.dedup();
1771 let sf = f_list_new.last().and_then(|f| f.get_slopeyness_factor());
1773 FilterResolved::Or(f_list_new, sf)
1774 }
1775 }
1776 f => f.clone(),
1777 }
1778 }
1779
1780 pub fn is_andnot(&self) -> bool {
1781 matches!(self, FilterResolved::AndNot(_, _))
1782 }
1783
1784 #[inline(always)]
1785 fn get_slopeyness_factor(&self) -> Option<NonZeroU8> {
1786 match self {
1787 FilterResolved::Eq(_, _, sf)
1788 | FilterResolved::Cnt(_, _, sf)
1789 | FilterResolved::Stw(_, _, sf)
1790 | FilterResolved::Enw(_, _, sf)
1791 | FilterResolved::Pres(_, sf)
1792 | FilterResolved::LessThan(_, _, sf)
1793 | FilterResolved::Or(_, sf)
1794 | FilterResolved::And(_, sf)
1795 | FilterResolved::Inclusion(_, sf)
1796 | FilterResolved::AndNot(_, sf) => *sf,
1797 FilterResolved::Invalid(_) => NonZeroU8::new(1),
1799 }
1800 }
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805 use std::{
1806 cmp::{Ordering, PartialOrd},
1807 collections::BTreeSet,
1808 time::Duration,
1809 };
1810
1811 use kanidm_proto::internal::Filter as ProtoFilter;
1812 use ldap3_proto::simple::LdapFilter;
1813
1814 use crate::{
1815 event::{CreateEvent, DeleteEvent},
1816 filter::{Filter, FilterInvalid, DEFAULT_LIMIT_FILTER_DEPTH_MAX},
1817 prelude::*,
1818 };
1819
1820 #[test]
1821 fn test_filter_simple() {
1822 let _filt: Filter<FilterInvalid> = filter!(f_eq(Attribute::Class, EntryClass::User.into()));
1824
1825 let _complex_filt: Filter<FilterInvalid> = filter!(f_and!([
1827 f_or!([
1828 f_eq(Attribute::UserId, PartialValue::new_iutf8("test_a")),
1829 f_eq(Attribute::UserId, PartialValue::new_iutf8("test_b")),
1830 ]),
1831 f_sub(Attribute::Class, EntryClass::User.into()),
1832 ]));
1833 }
1834
1835 macro_rules! filter_optimise_assert {
1836 (
1837 $init:expr,
1838 $expect:expr
1839 ) => {{
1840 #[allow(unused_imports)]
1841 use crate::filter::{f_and, f_andnot, f_eq, f_or, f_pres, f_sub};
1842 use crate::filter::{Filter, FilterInvalid};
1843 let f_init: Filter<FilterInvalid> = Filter::new($init);
1844 let f_expect: Filter<FilterInvalid> = Filter::new($expect);
1845 let f_init_r = f_init.into_valid_resolved();
1847 let f_init_o = f_init_r.optimise();
1848 let f_init_e = f_expect.into_valid_resolved();
1849 debug!("--");
1850 debug!("init --> {:?}", f_init_r);
1851 debug!("opt --> {:?}", f_init_o);
1852 debug!("expect --> {:?}", f_init_e);
1853 assert_eq!(f_init_o, f_init_e);
1854 }};
1855 }
1856
1857 #[test]
1858 fn test_filter_optimise() {
1859 sketching::test_init();
1860 filter_optimise_assert!(
1862 f_and(vec![f_and(vec![f_eq(
1863 Attribute::Class,
1864 EntryClass::TestClass.into()
1865 )])]),
1866 f_eq(Attribute::Class, EntryClass::TestClass.into())
1867 );
1868
1869 filter_optimise_assert!(
1870 f_or(vec![f_or(vec![f_eq(
1871 Attribute::Class,
1872 EntryClass::TestClass.into()
1873 )])]),
1874 f_eq(Attribute::Class, EntryClass::TestClass.into())
1875 );
1876
1877 filter_optimise_assert!(
1878 f_and(vec![f_or(vec![f_and(vec![f_eq(
1879 Attribute::Class,
1880 EntryClass::TestClass.to_partialvalue()
1881 )])])]),
1882 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue())
1883 );
1884
1885 filter_optimise_assert!(
1887 f_and(vec![
1888 f_and(vec![f_eq(
1889 Attribute::Class,
1890 EntryClass::TestClass.to_partialvalue()
1891 )]),
1892 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1893 f_pres(Attribute::Class),
1894 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue())
1895 ]),
1896 f_and(vec![
1897 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1898 f_pres(Attribute::Class),
1899 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1900 ])
1901 );
1902
1903 filter_optimise_assert!(
1905 f_and(vec![
1906 f_and(vec![
1907 f_eq(Attribute::Class, PartialValue::new_iutf8("foo")),
1908 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1909 f_eq(Attribute::Uid, PartialValue::new_iutf8("bar")),
1910 ]),
1911 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1912 f_pres(Attribute::Class),
1913 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue())
1914 ]),
1915 f_and(vec![
1916 f_eq(Attribute::Class, PartialValue::new_iutf8("foo")),
1917 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1918 f_pres(Attribute::Class),
1919 f_eq(Attribute::Uid, PartialValue::new_iutf8("bar")),
1920 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1921 ])
1922 );
1923
1924 filter_optimise_assert!(
1925 f_or(vec![
1926 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1927 f_pres(Attribute::Class),
1928 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1929 f_or(vec![f_eq(
1930 Attribute::Class,
1931 EntryClass::TestClass.to_partialvalue()
1932 )]),
1933 ]),
1934 f_or(vec![
1935 f_sub(Attribute::Class, PartialValue::new_iutf8("te")),
1936 f_pres(Attribute::Class),
1937 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue())
1938 ])
1939 );
1940
1941 filter_optimise_assert!(
1943 f_or(vec![
1944 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1945 f_and(vec![
1946 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1947 f_eq(Attribute::Term, EntryClass::TestClass.to_partialvalue()),
1948 f_or(vec![f_eq(
1949 Attribute::Class,
1950 EntryClass::TestClass.to_partialvalue()
1951 )])
1952 ]),
1953 ]),
1954 f_or(vec![
1955 f_and(vec![
1956 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1957 f_eq(Attribute::Term, EntryClass::TestClass.to_partialvalue())
1958 ]),
1959 f_eq(Attribute::Class, EntryClass::TestClass.to_partialvalue()),
1960 ])
1961 );
1962 }
1963
1964 #[test]
1965 fn test_filter_eq() {
1966 let f_t1a = filter!(f_pres(Attribute::UserId));
1967 let f_t1b = filter!(f_pres(Attribute::UserId));
1968 let f_t1c = filter!(f_pres(Attribute::NonExist));
1969
1970 assert_eq!(f_t1a, f_t1b);
1971 assert!(f_t1a != f_t1c);
1972 assert!(f_t1b != f_t1c);
1973
1974 let f_t2a = filter!(f_and!([f_pres(Attribute::UserId)]));
1975 let f_t2b = filter!(f_and!([f_pres(Attribute::UserId)]));
1976 let f_t2c = filter!(f_and!([f_pres(Attribute::NonExist)]));
1977 assert_eq!(f_t2a, f_t2b);
1978 assert!(f_t2a != f_t2c);
1979 assert!(f_t2b != f_t2c);
1980
1981 assert!(f_t2c != f_t1a);
1982 assert!(f_t2c != f_t1c);
1983 }
1984
1985 #[test]
1986 fn test_filter_ord() {
1987 let f_t1a = filter_resolved!(f_pres(Attribute::UserId));
1991 let f_t1b = filter_resolved!(f_pres(Attribute::UserId));
1992
1993 assert_eq!(f_t1a.partial_cmp(&f_t1b), Some(Ordering::Equal));
1994 assert_eq!(f_t1b.partial_cmp(&f_t1a), Some(Ordering::Equal));
1995
1996 let f_t2a = filter_resolved!(f_and!([]));
1997 let f_t2b = filter_resolved!(f_and!([]));
1998 assert_eq!(f_t2a.partial_cmp(&f_t2b), Some(Ordering::Equal));
1999 assert_eq!(f_t2b.partial_cmp(&f_t2a), Some(Ordering::Equal));
2000
2001 let f_t3b = filter_resolved!(f_eq(Attribute::UserId, PartialValue::new_iutf8("")));
2004 assert_eq!(f_t1a.partial_cmp(&f_t3b), Some(Ordering::Greater));
2005 assert_eq!(f_t3b.partial_cmp(&f_t1a), Some(Ordering::Less));
2006
2007 let f_t4b = filter_resolved!(f_sub(Attribute::UserId, PartialValue::new_iutf8("")));
2009 assert_eq!(f_t1a.partial_cmp(&f_t4b), Some(Ordering::Less));
2010 assert_eq!(f_t3b.partial_cmp(&f_t4b), Some(Ordering::Less));
2011
2012 assert_eq!(f_t4b.partial_cmp(&f_t1a), Some(Ordering::Greater));
2013 assert_eq!(f_t4b.partial_cmp(&f_t3b), Some(Ordering::Greater));
2014 }
2015
2016 #[test]
2017 fn test_filter_clone() {
2018 let f_t1a = filter_resolved!(f_pres(Attribute::UserId));
2021 let f_t1b = f_t1a.clone();
2022 let f_t1c = filter_resolved!(f_pres(Attribute::NonExist));
2023
2024 assert_eq!(f_t1a, f_t1b);
2025 assert!(f_t1a != f_t1c);
2026
2027 let f_t2a = filter_resolved!(f_and!([f_pres(Attribute::UserId)]));
2028 let f_t2b = f_t2a.clone();
2029 let f_t2c = filter_resolved!(f_and!([f_pres(Attribute::NonExist)]));
2030
2031 assert_eq!(f_t2a, f_t2b);
2032 assert!(f_t2a != f_t2c);
2033 }
2034
2035 #[test]
2036 fn test_lessthan_entry_filter() {
2037 let e = entry_init!(
2038 (Attribute::UserId, Value::new_iutf8("william")),
2039 (
2040 Attribute::Uuid,
2041 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
2042 ),
2043 (Attribute::GidNumber, Value::Uint32(1000))
2044 )
2045 .into_sealed_new();
2046
2047 let f_t1a = filter_resolved!(f_lt(Attribute::GidNumber, PartialValue::new_uint32(500)));
2048 assert!(!e.entry_match_no_index(&f_t1a));
2049
2050 let f_t1b = filter_resolved!(f_lt(Attribute::GidNumber, PartialValue::new_uint32(1000)));
2051 assert!(!e.entry_match_no_index(&f_t1b));
2052
2053 let f_t1c = filter_resolved!(f_lt(Attribute::GidNumber, PartialValue::new_uint32(1001)));
2054 assert!(e.entry_match_no_index(&f_t1c));
2055 }
2056
2057 #[test]
2058 fn test_or_entry_filter() {
2059 let e = entry_init!(
2060 (Attribute::UserId, Value::new_iutf8("william")),
2061 (
2062 Attribute::Uuid,
2063 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
2064 ),
2065 (Attribute::GidNumber, Value::Uint32(1000))
2066 )
2067 .into_sealed_new();
2068
2069 let f_t1a = filter_resolved!(f_or!([
2070 f_eq(Attribute::UserId, PartialValue::new_iutf8("william")),
2071 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000)),
2072 ]));
2073 assert!(e.entry_match_no_index(&f_t1a));
2074
2075 let f_t2a = filter_resolved!(f_or!([
2076 f_eq(Attribute::UserId, PartialValue::new_iutf8("william")),
2077 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000)),
2078 ]));
2079 assert!(e.entry_match_no_index(&f_t2a));
2080
2081 let f_t3a = filter_resolved!(f_or!([
2082 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2083 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000)),
2084 ]));
2085 assert!(e.entry_match_no_index(&f_t3a));
2086
2087 let f_t4a = filter_resolved!(f_or!([
2088 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2089 f_eq(Attribute::GidNumber, PartialValue::Uint32(1001)),
2090 ]));
2091 assert!(!e.entry_match_no_index(&f_t4a));
2092 }
2093
2094 #[test]
2095 fn test_and_entry_filter() {
2096 let e = entry_init!(
2097 (Attribute::UserId, Value::new_iutf8("william")),
2098 (
2099 Attribute::Uuid,
2100 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
2101 ),
2102 (Attribute::GidNumber, Value::Uint32(1000))
2103 )
2104 .into_sealed_new();
2105
2106 let f_t1a = filter_resolved!(f_and!([
2107 f_eq(Attribute::UserId, PartialValue::new_iutf8("william")),
2108 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000)),
2109 ]));
2110 assert!(e.entry_match_no_index(&f_t1a));
2111
2112 let f_t2a = filter_resolved!(f_and!([
2113 f_eq(Attribute::UserId, PartialValue::new_iutf8("william")),
2114 f_eq(Attribute::GidNumber, PartialValue::Uint32(1001)),
2115 ]));
2116 assert!(!e.entry_match_no_index(&f_t2a));
2117
2118 let f_t3a = filter_resolved!(f_and!([
2119 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2120 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000)),
2121 ]));
2122 assert!(!e.entry_match_no_index(&f_t3a));
2123
2124 let f_t4a = filter_resolved!(f_and!([
2125 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2126 f_eq(Attribute::GidNumber, PartialValue::Uint32(1001)),
2127 ]));
2128 assert!(!e.entry_match_no_index(&f_t4a));
2129 }
2130
2131 #[test]
2132 fn test_not_entry_filter() {
2133 let e1 = entry_init!(
2134 (Attribute::UserId, Value::new_iutf8("william")),
2135 (
2136 Attribute::Uuid,
2137 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
2138 ),
2139 (Attribute::GidNumber, Value::Uint32(1000))
2140 )
2141 .into_sealed_new();
2142
2143 let f_t1a = filter_resolved!(f_andnot(f_eq(
2144 Attribute::UserId,
2145 PartialValue::new_iutf8("alice")
2146 )));
2147 assert!(e1.entry_match_no_index(&f_t1a));
2148
2149 let f_t2a = filter_resolved!(f_andnot(f_eq(
2150 Attribute::UserId,
2151 PartialValue::new_iutf8("william")
2152 )));
2153 assert!(!e1.entry_match_no_index(&f_t2a));
2154 }
2155
2156 #[test]
2157 fn test_nested_entry_filter() {
2158 let e1 = entry_init!(
2159 (Attribute::Class, EntryClass::Person.to_value().clone()),
2160 (
2161 Attribute::Uuid,
2162 Value::Uuid(uuid::uuid!("db237e8a-0079-4b8c-8a56-593b22aa44d1"))
2163 ),
2164 (Attribute::GidNumber, Value::Uint32(1000))
2165 )
2166 .into_sealed_new();
2167
2168 let e2 = entry_init!(
2169 (Attribute::Class, EntryClass::Person.to_value().clone()),
2170 (
2171 Attribute::Uuid,
2172 Value::Uuid(uuid::uuid!("4b6228ab-1dbe-42a4-a9f5-f6368222438e"))
2173 ),
2174 (Attribute::GidNumber, Value::Uint32(1001))
2175 )
2176 .into_sealed_new();
2177
2178 let e3 = entry_init!(
2179 (Attribute::Class, EntryClass::Person.to_value()),
2180 (
2181 Attribute::Uuid,
2182 Value::Uuid(uuid::uuid!("7b23c99d-c06b-4a9a-a958-3afa56383e1d"))
2183 ),
2184 (Attribute::GidNumber, Value::Uint32(1002))
2185 )
2186 .into_sealed_new();
2187
2188 let e4 = entry_init!(
2189 (Attribute::Class, EntryClass::Group.to_value()),
2190 (
2191 Attribute::Uuid,
2192 Value::Uuid(uuid::uuid!("21d816b5-1f6a-4696-b7c1-6ed06d22ed81"))
2193 ),
2194 (Attribute::GidNumber, Value::Uint32(1000))
2195 )
2196 .into_sealed_new();
2197
2198 let f_t1a = filter_resolved!(f_and!([
2199 f_eq(Attribute::Class, EntryClass::Person.into()),
2200 f_or!([
2201 f_eq(Attribute::GidNumber, PartialValue::Uint32(1001)),
2202 f_eq(Attribute::GidNumber, PartialValue::Uint32(1000))
2203 ])
2204 ]));
2205
2206 assert!(e1.entry_match_no_index(&f_t1a));
2207 assert!(e2.entry_match_no_index(&f_t1a));
2208 assert!(!e3.entry_match_no_index(&f_t1a));
2209 assert!(!e4.entry_match_no_index(&f_t1a));
2210 }
2211
2212 #[test]
2213 fn test_attr_set_filter() {
2214 let mut f_expect = BTreeSet::new();
2215 f_expect.insert(Attribute::from("userid"));
2216 f_expect.insert(Attribute::Class);
2217 let f_t1a = filter_valid!(f_and!([
2220 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2221 f_eq(Attribute::Class, PartialValue::new_iutf8("1001")),
2222 ]));
2223
2224 assert_eq!(f_t1a.get_attr_set(), f_expect);
2225
2226 let f_t2a = filter_valid!(f_and!([
2227 f_eq(Attribute::UserId, PartialValue::new_iutf8("alice")),
2228 f_eq(Attribute::Class, PartialValue::new_iutf8("1001")),
2229 f_eq(Attribute::UserId, PartialValue::new_iutf8("claire")),
2230 ]));
2231
2232 assert_eq!(f_t2a.get_attr_set(), f_expect);
2233 }
2234
2235 #[qs_test]
2236 async fn test_filter_resolve_value(server: &QueryServer) {
2237 let time_p1 = duration_from_epoch_now();
2238 let time_p2 = time_p1 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
2239 let time_p3 = time_p2 + Duration::from_secs(CHANGELOG_MAX_AGE * 2);
2240
2241 let mut server_txn = server.write(time_p1).await.expect("txn");
2242
2243 let e1 = entry_init!(
2244 (Attribute::Class, EntryClass::Object.to_value()),
2245 (Attribute::Class, EntryClass::Account.to_value()),
2246 (Attribute::Class, EntryClass::Person.to_value()),
2247 (Attribute::Name, Value::new_iname("testperson1")),
2248 (
2249 Attribute::Uuid,
2250 Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
2251 ),
2252 (Attribute::Description, Value::new_utf8s("testperson1")),
2253 (Attribute::DisplayName, Value::new_utf8s("testperson1"))
2254 );
2255
2256 let e2 = entry_init!(
2257 (Attribute::Class, EntryClass::Object.to_value()),
2258 (Attribute::Class, EntryClass::Account.to_value()),
2259 (Attribute::Class, EntryClass::Person.to_value()),
2260 (Attribute::Name, Value::new_iname("testperson2")),
2261 (
2262 Attribute::Uuid,
2263 Value::Uuid(uuid::uuid!("a67c0c71-0b35-4218-a6b0-22d23d131d27"))
2264 ),
2265 (Attribute::Description, Value::new_utf8s("testperson2")),
2266 (Attribute::DisplayName, Value::new_utf8s("testperson2"))
2267 );
2268
2269 let e_ts = entry_init!(
2271 (Attribute::Class, EntryClass::Object.to_value()),
2272 (Attribute::Class, EntryClass::Account.to_value()),
2273 (Attribute::Class, EntryClass::Person.to_value()),
2274 (Attribute::Name, Value::new_iname("testperson3")),
2275 (
2276 Attribute::Uuid,
2277 Value::Uuid(uuid!("9557f49c-97a5-4277-a9a5-097d17eb8317"))
2278 ),
2279 (Attribute::Description, Value::new_utf8s("testperson3")),
2280 (Attribute::DisplayName, Value::new_utf8s("testperson3"))
2281 );
2282
2283 let ce = CreateEvent::new_internal(vec![e1, e2, e_ts]);
2284 let cr = server_txn.create(&ce);
2285 assert!(cr.is_ok());
2286
2287 let de_sin = DeleteEvent::new_internal_invalid(filter!(f_or!([f_eq(
2288 Attribute::Name,
2289 PartialValue::new_iname("testperson3")
2290 )])));
2291 assert!(server_txn.delete(&de_sin).is_ok());
2292
2293 assert!(server_txn.commit().is_ok());
2295
2296 let mut server_txn = server.write(time_p2).await.expect("txn");
2298 assert!(server_txn.purge_recycled().is_ok());
2299 assert!(server_txn.commit().is_ok());
2300
2301 let mut server_txn = server.write(time_p3).await.expect("txn");
2302 assert!(server_txn.purge_tombstones().is_ok());
2303
2304 let t1 = vs_utf8!["teststring".to_string()] as _;
2308 let r1 = server_txn.resolve_valueset(&t1);
2309 assert_eq!(r1, Ok(vec!["teststring".to_string()]));
2310
2311 let t_uuid = vs_refer![uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930")] as _;
2313 let r_uuid = server_txn.resolve_valueset(&t_uuid);
2314 debug!("{:?}", r_uuid);
2315 assert_eq!(r_uuid, Ok(vec!["testperson1@example.com".to_string()]));
2316
2317 let t_uuid = vs_refer![uuid!("a67c0c71-0b35-4218-a6b0-22d23d131d27")] as _;
2319 let r_uuid = server_txn.resolve_valueset(&t_uuid);
2320 debug!("{:?}", r_uuid);
2321 assert_eq!(r_uuid, Ok(vec!["testperson2@example.com".to_string()]));
2322
2323 let t_uuid_non = vs_refer![uuid!("b83e98f0-3d2e-41d2-9796-d8d993289c86")] as _;
2325 let r_uuid_non = server_txn.resolve_valueset(&t_uuid_non);
2326 debug!("{:?}", r_uuid_non);
2327 assert_eq!(
2328 r_uuid_non,
2329 Ok(vec!["b83e98f0-3d2e-41d2-9796-d8d993289c86".to_string()])
2330 );
2331
2332 let t_uuid_ts = vs_refer![uuid!("9557f49c-97a5-4277-a9a5-097d17eb8317")] as _;
2334 let r_uuid_ts = server_txn.resolve_valueset(&t_uuid_ts);
2335 debug!("{:?}", r_uuid_ts);
2336 assert_eq!(
2337 r_uuid_ts,
2338 Ok(vec!["9557f49c-97a5-4277-a9a5-097d17eb8317".to_string()])
2339 );
2340 }
2341
2342 #[qs_test]
2343 async fn test_filter_depth_limits(server: &QueryServer) {
2344 let mut r_txn = server.read().await.unwrap();
2345
2346 let mut inv_proto = ProtoFilter::Pres(Attribute::Class.to_string());
2347 for _i in 0..(DEFAULT_LIMIT_FILTER_DEPTH_MAX + 1) {
2348 inv_proto = ProtoFilter::And(vec![inv_proto]);
2349 }
2350
2351 let mut inv_ldap = LdapFilter::Present(Attribute::Class.to_string());
2352 for _i in 0..(DEFAULT_LIMIT_FILTER_DEPTH_MAX + 1) {
2353 inv_ldap = LdapFilter::And(vec![inv_ldap]);
2354 }
2355
2356 let ev = Identity::from_internal();
2357
2358 let res = Filter::from_ro(&ev, &inv_proto, &mut r_txn);
2360 assert_eq!(res, Err(OperationError::ResourceLimit));
2361
2362 let res = Filter::from_ldap_ro(&ev, &inv_ldap, &mut r_txn);
2364 assert_eq!(res, Err(OperationError::ResourceLimit));
2365
2366 std::mem::drop(r_txn);
2368
2369 let mut wr_txn = server.write(duration_from_epoch_now()).await.expect("txn");
2371 let res = Filter::from_rw(&ev, &inv_proto, &mut wr_txn);
2372 assert_eq!(res, Err(OperationError::ResourceLimit));
2373 }
2374
2375 #[qs_test]
2376 async fn test_filter_max_element_limits(server: &QueryServer) {
2377 const LIMIT: usize = 4;
2378 let mut r_txn = server.read().await.unwrap();
2379
2380 let inv_proto = ProtoFilter::And(
2381 (0..(LIMIT * 2))
2382 .map(|_| ProtoFilter::Pres(Attribute::Class.to_string()))
2383 .collect(),
2384 );
2385
2386 let inv_ldap = LdapFilter::And(
2387 (0..(LIMIT * 2))
2388 .map(|_| LdapFilter::Present(Attribute::Class.to_string()))
2389 .collect(),
2390 );
2391
2392 let mut ev = Identity::from_internal();
2393 ev.limits_mut().filter_max_elements = LIMIT;
2394
2395 let res = Filter::from_ro(&ev, &inv_proto, &mut r_txn);
2397 assert_eq!(res, Err(OperationError::ResourceLimit));
2398
2399 let res = Filter::from_ldap_ro(&ev, &inv_ldap, &mut r_txn);
2401 assert_eq!(res, Err(OperationError::ResourceLimit));
2402
2403 std::mem::drop(r_txn);
2405
2406 let mut wr_txn = server.write(duration_from_epoch_now()).await.expect("txn");
2408 let res = Filter::from_rw(&ev, &inv_proto, &mut wr_txn);
2409 assert_eq!(res, Err(OperationError::ResourceLimit));
2410 }
2411}