Skip to main content

kanidmd_lib/
filter.rs

1//! [`Filter`]s are one of the three foundational concepts of the design in kanidm.
2//! They are used in nearly every aspect of the server to provide searching of
3//! datasets and assertion of entry properties.
4//!
5//! A filter is a logical statement of properties that an [`Entry`] and its
6//! AVAs must uphold to be considered true.
7//!
8//! [`Filter`]: struct.Filter.html
9//! [`Entry`]: ../entry/struct.Entry.html
10
11use 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
53// Default filter is safe, ignores all hidden types!
54
55// This is &Value so we can lazy const then clone, but perhaps we can reconsider
56// later if this should just take Value.
57pub 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/// This is the short-form for tests and internal filters that can then
129/// be transformed into a filter for the server to use.
130#[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    // Not(Box<FC>),
143}
144
145/// This is the filters internal representation
146#[derive(Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
147enum FilterComp {
148    // This is attr - value
149    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    // Does this mean we can add a true not to the type now?
162    // Not(Box<FilterComp>),
163}
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/// This is the fully resolved internal representation. Note the lack of Not and selfUUID
230/// because these are resolved into And(Pres(class), AndNot(term)) and Eq(uuid, ...) respectively.
231/// Importantly, we make this accessible to Entry so that it can then match on filters
232/// internally.
233///
234/// Each filter that has been resolved also has been enriched with metadata about its
235/// index, and index slope. For the purpose of this module, consider slope as a "weight"
236/// where small value - faster index, larger value - slower index. This metadata is extremely
237/// important for the query optimiser to make decisions about how to re-arrange queries
238/// correctly.
239#[derive(Clone, Eq)]
240pub enum FilterResolved {
241    // This is attr - value - indexed slope factor
242    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    // All terms must have 1 or more items, or the inclusion is false!
252    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)]
348/// A filter before it's gone through schema validation
349pub struct FilterInvalid {
350    inner: FilterComp,
351}
352
353#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
354/// A filter after it's gone through schema validation
355pub 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
393// This difference in this is that we want to show unindexed elements more prominently
394// in the execution.
395
396fn 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/// A `Filter` is a logical set of assertions about the state of an [`Entry`] and
444/// it's avas. `Filter`s are built from a set of possible assertions.
445///
446/// * `Pres`ence. An ava of that attribute's name exists, with any value on the [`Entry`].
447/// * `Eq`uality. An ava of the attribute exists and contains this matching value.
448/// * `Sub`string. An ava of the attribute exists and has a substring containing the requested value.
449/// * `Or`. Contains multiple filters and asserts at least one is true.
450/// * `And`. Contains multiple filters and asserts all of them are true.
451/// * `AndNot`. This is different to a "logical not" operation. This asserts that a condition is not
452///   true in the current candidate set. A search of `AndNot` alone will yield not results, but an
453///   `AndNot` in an `And` query will assert that a condition can not hold.
454///
455/// `Filter`s for security reasons are validated by the schema to assert all requested attributes
456/// are valid and exist in the schema so that they can have their indexes correctly used. This avoids
457/// a denial of service attack that may lead to full-table scans.
458///
459/// This `Filter` validation state is in the `STATE` attribute and will be either `FilterInvalid`
460/// or `FilterValid`. The `Filter` must be checked by the schema to move to `FilterValid`. This
461/// helps to prevent errors at compile time to assert `Filters` are securely checked
462///
463/// [`Entry`]: ../entry/struct.Entry.html
464#[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    // Does this need mut self? Aren't we returning
489    // a new copied filter?
490
491    #[cfg(test)]
492    fn optimise(&self) -> Self {
493        // Apply optimisations to the filter
494        // An easy way would be imple partialOrd
495        // then do sort on the or/and/not
496        // as the general conditions we want
497        // to optimise on are in those ...
498        //
499        // The other big one is folding redundant
500        // terms down.
501        //
502        // If an or/not/and condition has no items, remove it
503        //
504        // If its the root item?
505
506        Filter {
507            state: FilterValidResolved {
508                inner: self.state.inner.optimise(),
509            },
510        }
511    }
512
513    // It's not possible to invalid a resolved filter, because we don't know
514    // what the origin of the Self or Not keywords were.
515    //
516    // Saying this, we have entry -> filter_from_attrs. Should that return
517    // a valid or validResolved? If it does valid resolved we need invalidate
518    // so we can down cast and then re-validate and re-resolve ...
519
520    // Allow the entry crate to read the internals of the filter.
521    // more likely, we should move entry matching HERE ...
522    pub fn to_inner(&self) -> &FilterResolved {
523        &self.state.inner
524    }
525}
526
527impl Filter<FilterValid> {
528    pub fn invalidate(self) -> Filter<FilterInvalid> {
529        // Just move the state.
530        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        // Given a filter, resolve Not and SelfUuid to real terms.
544        //
545        // The benefit of moving optimisation to this step is from various inputs, we can
546        // get to a resolved + optimised filter, and then we can cache those outputs in many
547        // cases! The exception is *large* filters, especially from the memberof plugin. We
548        // want to skip these because they can really jam up the server.
549
550        // Don't cache anything unless we have valid indexing metadata.
551        let cacheable = idxmeta.is_some() && FilterResolved::resolve_cacheable(&self.state.inner);
552
553        let cache_key = if cacheable {
554            // do we have a cache?
555            if let Some(rcache) = rsv_cache.as_mut() {
556                // construct the key. For now it's expensive because we have to clone, but ... eh.
557                let cache_key = (ev.get_event_origin_id(), Arc::new(self.clone()));
558                if let Some(f) = rcache.get(&cache_key) {
559                    // Got it? Shortcut and return!
560                    trace!("shortcut: a resolved filter already exists.");
561                    return Ok(f.as_ref().clone());
562                };
563                // Not in cache? Set the cache_key.
564                Some(cache_key)
565            } else {
566                None
567            }
568        } else {
569            // Not cacheable, lets just bail.
570            None
571        };
572
573        // If we got here, nothing in cache - resolve it the hard way.
574
575        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                        // Do a proper optimise if we have idxmeta.
586                        Some(_) => f.optimise(),
587                        // Only do this if we don't have idxmeta.
588                        None => f.fast_optimise(),
589                    }
590                })
591                .ok_or(OperationError::FilterUuidResolution)?,
592            },
593        };
594
595        // Now it's computed, inject it. Remember, we won't have a cache_key here
596        // if cacheable == false.
597        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        // Recurse through the filter getting an attribute set.
609        let mut r_set = BTreeSet::new();
610        self.state.inner.get_attr_set(&mut r_set);
611        r_set
612    }
613
614    /*
615     * CORRECTNESS: This is a transform on the "immutable" filtervalid type.
616     * We know this is correct because internally we can assert that the hidden
617     * and recycled types *must* be valid.
618     */
619
620    pub fn into_ignore_hidden(self) -> Self {
621        // Destructure the former filter, and surround it with an ignore_hidden.
622        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        // Destructure the former filter and surround it with a recycled only query
631        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        // Create a filter that searches recycled items only.
658        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        // I regret this function so much, but then again ...
668        Filter {
669            state: FilterInvalid {
670                inner: FilterComp::And(vec![a.state.inner, b.state.inner]),
671            },
672        }
673    }
674
675    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
676    /// This is a TEST ONLY method and will never be exposed in production.
677    #[cfg(test)]
678    pub fn into_valid_resolved(self) -> Filter<FilterValidResolved> {
679        // There is a good reason this function only exists in tests ...
680        //
681        // YOLO.
682        // tl;dr - panic if there is a Self term because we don't have the QS
683        // to resolve the uuid. Perhaps in the future we can provide a uuid
684        // to this for the resolving to make it safer and test case usable.
685
686        // First we make a fake idx meta, which is meant to be "just enough" to make
687        // some core test idxs faster. This is never used in production, it's JUST for
688        // test case speedups.
689        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    /// ⚠️  - Bypass the schema state machine and force the filter to be considered valid.
715    /// This is a TEST ONLY method and will never be exposed in production.
716    #[cfg(test)]
717    pub fn into_valid(self) -> Filter<FilterValid> {
718        // There is a good reason this function only exists in tests ...
719        //
720        // YOLO.
721        // tl;dr - blindly accept that this filter and it's ava's MUST have
722        // been normalised and exist in schema. If they don't things may subtly
723        // break, fail, or explode. As subtle as an explosion can be.
724        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        // TODO: Add a schema validation cache that can return pre-validated filters.
736
737        Ok(Filter {
738            state: FilterValid {
739                inner: self.state.inner.validate(schema)?,
740            },
741        })
742    }
743
744    // This has to have two versions to account for ro/rw traits, because RS can't
745    // monomorphise on the trait to call clone_value. An option is to make a fn that
746    // takes "clone_value(t, a, v) instead, but that may have a similar issue.
747    #[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        // Optimisation is done at another stage.
876
877        // This probably needs some rework
878
879        // Getting this each recursion could be slow. Maybe
880        // we need an inner function that passes the reference?
881        let schema_attributes = schema.get_attributes();
882        // We used to check the attr_name by normalising it (lowercasing)
883        // but should we? I think we actually should just call a special
884        // handler on schema to fix it up.
885
886        match self {
887            FilterComp::Eq(attr, value) => {
888                // Check the requested attribute exists, and this PV type matches something
889                // that can be queried of the attribute.
890                match schema_attributes.get(attr) {
891                    Some(schema_a) => {
892                        schema_a
893                            .validate_partialvalue(attr, value)
894                            // Okay, it worked, transform to a filter component
895                            .map(|_| FilterComp::Eq(attr.clone(), value.clone()))
896                        // On error, pass the error back out.
897                    }
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                            // Okay, it worked, transform to a filter component
907                            .map(|_| FilterComp::Cnt(attr.clone(), value.clone()))
908                        // On error, pass the error back out.
909                    }
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                            // Okay, it worked, transform to a filter component
919                            .map(|_| FilterComp::Stw(attr.clone(), value.clone()))
920                        // On error, pass the error back out.
921                    }
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                            // Okay, it worked, transform to a filter component
931                            .map(|_| FilterComp::Enw(attr.clone(), value.clone()))
932                        // On error, pass the error back out.
933                    }
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                        // Return our valid data
941                        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                            // Okay, it worked, transform to a filter component
952                            .map(|_| FilterComp::LessThan(attr.clone(), value.clone()))
953                        // On error, pass the error back out.
954                    }
955                    None => Err(SchemaError::InvalidAttribute(attr.to_string())),
956                }
957            }
958            FilterComp::Or(filters) => {
959                // * If all filters are okay, return Ok(Filter::Or())
960                // * Any filter is invalid, return the error.
961                // * An empty "or" is a valid filter in mathematical terms, but we throw an
962                //   error to warn the user because it's super unlikely they want that
963                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                // Now put the valid filters into the Filter
971                x.map(FilterComp::Or)
972            }
973            FilterComp::And(filters) => {
974                // * If all filters are okay, return Ok(Filter::Or())
975                // * Any filter is invalid, return the error.
976                // * An empty "and" is a valid filter in mathematical terms, but we throw an
977                //   error to warn the user because it's super unlikely they want that
978                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                // Now put the valid filters into the Filter
986                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                // Now put the valid filters into the Filter
997                x.map(FilterComp::Inclusion)
998            }
999            FilterComp::AndNot(filter) => {
1000                // Just validate the inner
1001                filter
1002                    .validate(schema)
1003                    .map(|r_filter| FilterComp::AndNot(Box::new(r_filter)))
1004            }
1005            FilterComp::SelfUuid => {
1006                // Pretty hard to mess this one up ;)
1007                Ok(FilterComp::SelfUuid)
1008            }
1009            FilterComp::Invalid(attr) => {
1010                // FilterComp may be invalid but Invalid is still a valid value.
1011                // we continue the evaluation so OR queries can still succeed
1012                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                // Greater is equivalent to "not equal or less than".
1235                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                // Greater or equal is equivalent to "not less than".
1250                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/* We only configure partial eq if cfg test on the invalid/valid types */
1302/*
1303impl PartialEq for Filter<FilterInvalid> {
1304    fn eq(&self, rhs: &Filter<FilterInvalid>) -> bool {
1305        self.state.inner == rhs.state.inner
1306    }
1307}
1308
1309impl PartialEq for Filter<FilterValid> {
1310    fn eq(&self, rhs: &Filter<FilterValid>) -> bool {
1311        self.state.inner == rhs.state.inner
1312    }
1313}
1314
1315impl PartialEq for Filter<FilterValidResolved> {
1316    fn eq(&self, rhs: &Filter<FilterValidResolved>) -> bool {
1317        self.state.inner == rhs.state.inner
1318    }
1319}
1320*/
1321
1322/*
1323 * Only needed in tests, in run time order only matters on the inner for
1324 * optimisation.
1325 */
1326#[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    /// Ordering of filters for optimisation and subsequent dead term elimination.
1361    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 they are equal, compare other elements for determining the order. This is what
1373        // allows dead term elimination to occur.
1374        //
1375        // In almost all cases, we'll miss this step though as slopes will vary distinctly.
1376        //
1377        // We do NOT need to check for indexed vs unindexed here, we already did it in the slope check!
1378        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                // Now sort these into the generally "best" order.
1390                (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                // They can't be re-arranged, they don't move!
1399                (_, _) => Ordering::Equal,
1400            }
1401        } else {
1402            r
1403        }
1404    }
1405}
1406
1407impl FilterResolved {
1408    /// ⚠️  - Process a filter without verifying with schema.
1409    /// This is a TEST ONLY method and will never be exposed in production.
1410    #[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                // TODO: pattern match box here. (AndNot(box f)).
1463                // We have to clone f into our space here because pattern matching can
1464                // not today remove the box, and we need f in our ownership. Since
1465                // AndNot currently is a rare request, cloning is not the worst thing
1466                // here ...
1467                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                    // Too lorge.
1482                    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            // We set the compound filters slope factor to "None" here, because when we do
1565            // optimise we'll actually fill in the correct slope factors after we sort those
1566            // inner terms in a more optimal way.
1567            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                // TODO: pattern match box here. (AndNot(box f)).
1590                // We have to clone f into our space here because pattern matching can
1591                // not today remove the box, and we need f in our ownership. Since
1592                // AndNot currently is a rare request, cloning is not the worst thing
1593                // here ...
1594                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        // ⚠️  ⚠️  ⚠️  ⚠️
1603        // Remember, this function means we have NO INDEX METADATA so we can only
1604        // assign slopes to values we can GUARANTEE will EXIST.
1605        match fc {
1606            FilterComp::Eq(a, v) => {
1607                // Since we have no index data, we manually configure a reasonable
1608                // slope and indicate the presence of some expected basic
1609                // indexes.
1610                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                // TODO: pattern match box here. (AndNot(box f)).
1650                // We have to clone f into our space here because pattern matching can
1651                // not today remove the box, and we need f in our ownership. Since
1652                // AndNot currently is a rare request, cloning is not the worst thing
1653                // here ...
1654                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    // This is an optimise that only attempts to optimise the outer terms.
1662    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        // Most optimisations only matter around or/and terms.
1682        match self {
1683            FilterResolved::Inclusion(f_list, _) => {
1684                // first, optimise all our inner elements
1685                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                // finally, optimise this list by sorting.
1696                f_list_new.sort_unstable();
1697                f_list_new.dedup();
1698                // Inclusions are similar to or, so what's our worst case?
1699                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                // first, optimise all our inner elements
1704                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                // now, iterate over this list - for each "and" term, fold
1710                // it's elements to this level.
1711                // This is one of the most important improvements because it means
1712                // that we can compare terms such that:
1713                //
1714                // (&(class=*)(&(uid=foo)))
1715                // if we did not and fold, this would remain as is. However, by and
1716                // folding, we can optimise to:
1717                // (&(uid=foo)(class=*))
1718                // Which will be faster when indexed as the uid=foo will trigger
1719                // shortcutting
1720
1721                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 the f_list_and only has one element, pop it and return.
1728                if f_list_new.len() == 1 {
1729                    f_list_new.remove(0)
1730                } else {
1731                    // finally, optimise this list by sorting.
1732                    f_list_new.sort_unstable();
1733                    f_list_new.dedup();
1734                    // Which ever element as the head is first must be the min SF
1735                    // so we use this in our And to represent the "best possible" value
1736                    // of how indexes will perform.
1737                    let sf = f_list_new.first().and_then(|f| f.get_slopeyness_factor());
1738                    //
1739                    // return!
1740                    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                    // Optimise all inner items.
1747                    .map(|f_ref| f_ref.optimise())
1748                    // Split out inner-or terms to fold into this term.
1749                    .partition(|f| matches!(f, FilterResolved::Or(_, _)));
1750
1751                // Append the inner terms.
1752                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 the f_list_or only has one element, pop it and return.
1759                if f_list_new.len() == 1 {
1760                    f_list_new.remove(0)
1761                } else {
1762                    // sort, but reverse so that sub-optimal elements are earlier
1763                    // to promote fast-failure.
1764                    // We have to allow this on clippy, which attempts to suggest:
1765                    //   f_list_new.sort_unstable_by_key(|&b| Reverse(b))
1766                    // However, because these are references, it causes a lifetime
1767                    // issue, and fails to compile.
1768                    #[allow(clippy::unnecessary_sort_by)]
1769                    f_list_new.sort_unstable_by(|a, b| b.cmp(a));
1770                    f_list_new.dedup();
1771                    // The *last* element is the most here, and our worst case factor.
1772                    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            // We hard code 1 because there is no slope for an invalid filter
1798            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        // Test construction.
1823        let _filt: Filter<FilterInvalid> = filter!(f_eq(Attribute::Class, EntryClass::User.into()));
1824
1825        // AFTER
1826        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            // Create a resolved filter, via the most unsafe means possible!
1846            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        // Given sets of "optimisable" filters, optimise them.
1861        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        // Later this can test duplicate filter detection.
1886        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        // Test dedup removes only the correct element despite padding.
1904        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        // Test dedup doesn't affect nested items incorrectly.
1942        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        // Test that we uphold the rules of partialOrd
1988        // Basic equality
1989        // Test the two major paths here (str vs list)
1990        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        // antisymmetry: if a < b then !(a > b), as well as a > b implying !(a < b); and
2002        // These are unindexed so we have to check them this way.
2003        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        // transitivity: a < b and b < c implies a < c. The same must hold for both == and >.
2008        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        // Test that cloning filters yields the same result regardless of
2019        // complexity.
2020        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        // Given filters, get their expected attribute sets - this is used by access control profiles
2218        // to determine what attrs we are requesting regardless of the partialvalue.
2219        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        // We need to add these and then push through the state machine.
2270        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        // Commit
2294        assert!(server_txn.commit().is_ok());
2295
2296        // Now, establish enough time for the recycled items to be purged.
2297        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        // ===== ✅ now ready to test!
2305
2306        // Resolving most times should yield expected results
2307        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        // Resolve UUID with matching spn
2312        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        // Resolve UUID with matching name
2318        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        // Resolve UUID non-exist
2324        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        // Resolve UUID to tombstone/recycled (same an non-exst)
2333        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        // Test proto + read
2359        let res = Filter::from_ro(&ev, &inv_proto, &mut r_txn);
2360        assert_eq!(res, Err(OperationError::ResourceLimit));
2361
2362        // ldap
2363        let res = Filter::from_ldap_ro(&ev, &inv_ldap, &mut r_txn);
2364        assert_eq!(res, Err(OperationError::ResourceLimit));
2365
2366        // Can only have one db conn at a time.
2367        std::mem::drop(r_txn);
2368
2369        // proto + write
2370        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        // Test proto + read
2396        let res = Filter::from_ro(&ev, &inv_proto, &mut r_txn);
2397        assert_eq!(res, Err(OperationError::ResourceLimit));
2398
2399        // ldap
2400        let res = Filter::from_ldap_ro(&ev, &inv_ldap, &mut r_txn);
2401        assert_eq!(res, Err(OperationError::ResourceLimit));
2402
2403        // Can only have one db conn at a time.
2404        std::mem::drop(r_txn);
2405
2406        // proto + write
2407        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}