Skip to main content

kanidmd_lib/server/access/
mod.rs

1//! Access Control Profiles
2//!
3//! This is a pretty important and security sensitive part of the code - it's
4//! responsible for making sure that who is allowed to do what is enforced, as
5//! well as who is *not* allowed to do what.
6//!
7//! A detailed design can be found in access-profiles-and-security.
8//!
9//! This component of the server really has a few parts
10//! - the ability to parse access profile structures into real ACP structs
11//! - the ability to apply sets of ACP's to entries for coarse actions (IE
12//!   search.
13//! - the ability to turn an entry into a partial-entry for results send
14//!   requirements (also search).
15
16use hashbrown::HashMap;
17use std::{cell::Cell, collections::BTreeSet, ops::DerefMut, sync::Arc};
18
19use concread::{arcache::ARCacheBuilder, cowcell::*};
20use uuid::Uuid;
21
22use crate::{
23    entry::{Entry, EntryInit, EntryNew},
24    event::{CreateEvent, DeleteEvent, ModifyEvent, SearchEvent},
25    filter::{Filter, FilterValid, ResolveFilterCache, ResolveFilterCacheReadTxn},
26    modify::Modify,
27    prelude::*,
28};
29
30use self::profiles::{
31    AccessControlCreate, AccessControlCreateResolved, AccessControlDelete,
32    AccessControlDeleteResolved, AccessControlModify, AccessControlModifyResolved,
33    AccessControlReceiver, AccessControlReceiverCondition, AccessControlSearch,
34    AccessControlSearchResolved, AccessControlTarget, AccessControlTargetCondition,
35};
36
37use kanidm_proto::scim_v1::server::ScimAttributeEffectiveAccess;
38
39use self::{
40    create::{apply_create_access, CreateResult},
41    delete::{apply_delete_access, DeleteResult},
42    modify::{apply_modify_access, ModifyResult},
43    search::{apply_search_access, SearchResult},
44};
45
46const ACP_RESOLVE_FILTER_CACHE_MAX: usize = 256;
47const ACP_RESOLVE_FILTER_CACHE_LOCAL: usize = 0;
48
49mod create;
50mod delete;
51mod migration;
52mod modify;
53pub mod profiles;
54mod protected;
55mod search;
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum Access {
59    Grant,
60    Deny,
61    Allow(BTreeSet<Attribute>),
62}
63
64impl From<&Access> for ScimAttributeEffectiveAccess {
65    fn from(value: &Access) -> Self {
66        match value {
67            Access::Grant => Self::Grant,
68            Access::Deny => Self::Deny,
69            Access::Allow(set) => Self::Allow(set.clone()),
70        }
71    }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum AccessClass {
76    Grant,
77    Deny,
78    Allow(BTreeSet<AttrString>),
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct AccessEffectivePermission {
83    /// Who the access applies to
84    pub ident: Uuid,
85    /// The target the access affects
86    pub target: Uuid,
87    pub delete: bool,
88    pub search: Access,
89    pub modify_pres: Access,
90    pub modify_rem: Access,
91    pub modify_pres_class: AccessClass,
92    pub modify_rem_class: AccessClass,
93}
94
95pub enum AccessBasicResult {
96    // Deny this operation unconditionally.
97    Deny,
98    // Unbounded allow, provided no deny state exists.
99    Grant,
100    // This module makes no decisions about this entry.
101    Ignore,
102}
103
104pub enum AccessSrchResult {
105    // Deny this operation unconditionally.
106    Deny,
107    // Unbounded allow, provided no deny state exists.
108    Grant,
109    // This module makes no decisions about this entry.
110    Ignore,
111    // Limit the allowed attr set to this - this doesn't
112    // allow anything, it constrains what might be allowed
113    // by a later module.
114    /*
115    Constrain {
116        attr: BTreeSet<Attribute>,
117    },
118    */
119    Allow { attr: BTreeSet<Attribute> },
120}
121
122pub enum AccessModResult<'a> {
123    // Deny this operation unconditionally.
124    Deny,
125    // Unbounded allow, provided no deny state exists.
126    // Grant,
127    // This module makes no decisions about this entry.
128    Ignore,
129    // Limit the allowed attr set to this - this doesn't
130    // allow anything, it constrains what might be allowed
131    // by a later module.
132    Constrain {
133        pres_attr: BTreeSet<Attribute>,
134        rem_attr: BTreeSet<Attribute>,
135        pres_cls: Option<BTreeSet<&'a str>>,
136        rem_cls: Option<BTreeSet<&'a str>>,
137    },
138    // Allow these modifications within constraints.
139    Allow {
140        pres_attr: BTreeSet<Attribute>,
141        rem_attr: BTreeSet<Attribute>,
142        pres_class: BTreeSet<&'a str>,
143        rem_class: BTreeSet<&'a str>,
144    },
145}
146
147// =========================================================================
148// ACP transactions and management for server bits.
149// =========================================================================
150
151#[derive(Clone)]
152struct AccessControlsInner {
153    acps_search: Vec<AccessControlSearch>,
154    acps_create: Vec<AccessControlCreate>,
155    acps_modify: Vec<AccessControlModify>,
156    acps_delete: Vec<AccessControlDelete>,
157    sync_agreements: HashMap<Uuid, BTreeSet<Attribute>>,
158    // Oauth2
159    // Sync prov
160}
161
162pub struct AccessControls {
163    inner: CowCell<AccessControlsInner>,
164    // acp_related_search_cache: ARCache<Uuid, Vec<Uuid>>,
165    acp_resolve_filter_cache: ResolveFilterCache,
166}
167
168fn resolve_access_conditions(
169    ident: &Identity,
170    ident_memberof: Option<&BTreeSet<Uuid>>,
171    receiver: &AccessControlReceiver,
172    target: &AccessControlTarget,
173    acp_resolve_filter_cache: &mut ResolveFilterCacheReadTxn<'_>,
174) -> Option<(AccessControlReceiverCondition, AccessControlTargetCondition)> {
175    let receiver_condition = match receiver {
176        AccessControlReceiver::Group(groups) => {
177            let group_check = ident_memberof
178                // Have at least one group allowed.
179                .map(|imo| {
180                    trace!(?imo, ?groups);
181                    imo.intersection(groups).next().is_some()
182                })
183                .unwrap_or_default();
184
185            if group_check {
186                AccessControlReceiverCondition::GroupChecked
187            } else {
188                // AccessControlReceiverCondition::None
189                return None;
190            }
191        }
192        AccessControlReceiver::EntryManager => AccessControlReceiverCondition::EntryManager,
193        AccessControlReceiver::None => return None,
194        // AccessControlReceiverCondition::None,
195    };
196
197    let target_condition = match &target {
198        AccessControlTarget::Scope(filter) => filter
199            .resolve(ident, None, Some(acp_resolve_filter_cache))
200            .map_err(|e| {
201                admin_error!(?e, "A internal filter/event was passed for resolution!?!?");
202                e
203            })
204            .ok()
205            .map(AccessControlTargetCondition::Scope)?,
206        AccessControlTarget::None => return None,
207    };
208
209    Some((receiver_condition, target_condition))
210}
211
212pub trait AccessControlsTransaction<'a> {
213    fn get_search(&self) -> &Vec<AccessControlSearch>;
214    fn get_create(&self) -> &Vec<AccessControlCreate>;
215    fn get_modify(&self) -> &Vec<AccessControlModify>;
216    fn get_delete(&self) -> &Vec<AccessControlDelete>;
217    fn get_sync_agreements(&self) -> &HashMap<Uuid, BTreeSet<Attribute>>;
218
219    #[allow(clippy::mut_from_ref)]
220    fn get_acp_resolve_filter_cache(&self) -> &mut ResolveFilterCacheReadTxn<'a>;
221
222    #[instrument(level = "trace", name = "access::search_related_acp", skip_all)]
223    fn search_related_acp<'b>(
224        &'b self,
225        ident: &Identity,
226        attrs: Option<&BTreeSet<Attribute>>,
227    ) -> Vec<AccessControlSearchResolved<'b>> {
228        let search_state = self.get_search();
229        let acp_resolve_filter_cache = self.get_acp_resolve_filter_cache();
230
231        // ⚠️  WARNING ⚠️  -- Why is this cache commented out?
232        //
233        // The reason for this is that to determine what acps relate, we need to be
234        // aware of session claims - since these can change session to session, we
235        // would need the cache to be structured to handle this. It's much better
236        // in a search to just lean on the filter resolve cache because of this
237        // dynamic behaviour.
238        //
239        // It may be possible to do per-operation caching when we know that we will
240        // perform the reduce step, but it may not be worth it. It's probably better
241        // to make entry_match_no_index faster.
242
243        /*
244        if let Some(acs_uuids) = acp_related_search_cache.get(rec_entry.get_uuid()) {
245            lperf_trace_segment!( "access::search_related_acp<cached>", || {
246                // If we have a cache, we should look here first for all the uuids that match
247
248                // could this be a better algo?
249                search_state
250                    .iter()
251                    .filter(|acs| acs_uuids.binary_search(&acs.acp.uuid).is_ok())
252                    .collect()
253            })
254        } else {
255        */
256        // else, we calculate this, and then stash/cache the uuids.
257
258        let ident_memberof = ident.get_memberof();
259
260        // let related_acp: Vec<(&AccessControlSearch, Filter<FilterValidResolved>)> =
261        let related_acp: Vec<AccessControlSearchResolved<'b>> = search_state
262            .iter()
263            .filter_map(|acs| {
264                // Now resolve the receiver filter
265                // Okay, so in filter resolution, the primary error case
266                // is that we have a non-user in the event. We have already
267                // checked for this above BUT we should still check here
268                // properly just in case.
269                //
270                // In this case, we assume that if the event is internal
271                // that the receiver can NOT match because it has no selfuuid
272                // and can as a result, never return true. This leads to this
273                // acp not being considered in that case ... which should never
274                // happen because we already bypassed internal ops above!
275                //
276                // A possible solution is to change the filter resolve function
277                // such that it takes an entry, rather than an event, but that
278                // would create issues in search.
279                let (receiver_condition, target_condition) = resolve_access_conditions(
280                    ident,
281                    ident_memberof,
282                    &acs.acp.receiver,
283                    &acs.acp.target,
284                    acp_resolve_filter_cache,
285                )?;
286
287                Some(AccessControlSearchResolved {
288                    acp: acs,
289                    receiver_condition,
290                    target_condition,
291                })
292            })
293            .collect();
294
295        // Trim any search rule that doesn't provide attributes related to the request.
296        let related_acp = if let Some(r_attrs) = attrs.as_ref() {
297            related_acp
298                .into_iter()
299                .filter(|acs| !acs.acp.attrs.is_disjoint(r_attrs))
300                .collect()
301        } else {
302            // None here means all attrs requested.
303            related_acp
304        };
305
306        related_acp
307    }
308
309    #[instrument(level = "debug", name = "access::filter_entries", skip_all)]
310    fn filter_entries(
311        &self,
312        ident: &Identity,
313        filter_orig: &Filter<FilterValid>,
314        entries: Vec<Arc<EntrySealedCommitted>>,
315    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
316        // Prepare some shared resources.
317
318        // Get the set of attributes requested by this se filter. This is what we are
319        // going to access check.
320        let requested_attrs: BTreeSet<Attribute> = filter_orig.get_attr_set();
321
322        // NOTE: This is a safety barrier, but queries can't proceed if they have no attributes.
323        if requested_attrs.is_empty() {
324            security_access!("denied ❌ - no attributes were requested in search, denying all entries from release");
325            return Ok(Vec::with_capacity(0));
326        }
327
328        // First get the set of acps that apply to this receiver
329        let related_acp = self.search_related_acp(ident, None);
330
331        // For each entry.
332        let entries_is_empty = entries.is_empty();
333        let allowed_entries: Vec<_> = entries
334            .into_iter()
335            .filter(|e| {
336                match apply_search_access(ident, related_acp.as_slice(), e) {
337                    SearchResult::Deny => false,
338                    SearchResult::Grant => true,
339                    SearchResult::Allow(allowed_attrs) => {
340                        // The allow set constrained.
341                        let decision = requested_attrs.is_subset(&allowed_attrs);
342                        security_debug!(
343                            ?decision,
344                            allowed = ?allowed_attrs,
345                            requested = ?requested_attrs,
346                            "search attribute decision",
347                        );
348                        decision
349                    }
350                }
351            })
352            .collect();
353
354        if allowed_entries.is_empty() {
355            if !entries_is_empty {
356                security_access!("denied ❌ - no entries were released");
357            }
358        } else {
359            debug!("allowed search of {} entries ✅", allowed_entries.len());
360        }
361
362        Ok(allowed_entries)
363    }
364
365    // Contains all the way to eval acps to entries
366    #[inline(always)]
367    fn search_filter_entries(
368        &self,
369        se: &SearchEvent,
370        entries: Vec<Arc<EntrySealedCommitted>>,
371    ) -> Result<Vec<Arc<EntrySealedCommitted>>, OperationError> {
372        self.filter_entries(&se.ident, &se.filter_orig, entries)
373    }
374
375    #[instrument(
376        level = "debug",
377        name = "access::search_filter_entry_attributes",
378        skip_all
379    )]
380    fn search_filter_entry_attributes(
381        &self,
382        se: &SearchEvent,
383        entries: Vec<Arc<EntrySealedCommitted>>,
384    ) -> Result<Vec<EntryReducedCommitted>, OperationError> {
385        struct DoEffectiveCheck<'b> {
386            modify_related_acp: Vec<AccessControlModifyResolved<'b>>,
387            delete_related_acp: Vec<AccessControlDeleteResolved<'b>>,
388            sync_agmts: &'b HashMap<Uuid, BTreeSet<Attribute>>,
389        }
390
391        match &se.ident.origin {
392            IdentType::Internal(_) => {
393                // In production we can't risk leaking data here, so we return
394                // empty sets.
395                security_critical!("IMPOSSIBLE STATE: Internal search in external interface?! Returning empty for safety.");
396                // No need to check ACS
397                return Err(OperationError::InvalidState);
398            }
399            IdentType::Synch(_) => {
400                security_critical!("Blocking sync check");
401                return Err(OperationError::InvalidState);
402            }
403            IdentType::User(u) => u.entry.get_uuid(),
404        };
405
406        // Build a reference set from the req_attrs. This is what we test against
407        // to see if the attribute is something we currently want.
408
409        let do_effective_check = se.effective_access_check.then(|| {
410            debug!("effective permission check requested during reduction phase");
411
412            // == modify ==
413            let modify_related_acp = self.modify_related_acp(&se.ident);
414            // == delete ==
415            let delete_related_acp = self.delete_related_acp(&se.ident);
416
417            let sync_agmts = self.get_sync_agreements();
418
419            DoEffectiveCheck {
420                modify_related_acp,
421                delete_related_acp,
422                sync_agmts,
423            }
424        });
425
426        // Get the relevant acps for this receiver.
427        let search_related_acp = self.search_related_acp(&se.ident, se.attrs.as_ref());
428
429        // For each entry.
430        let entries_is_empty = entries.is_empty();
431        let allowed_entries: Vec<_> = entries
432            .into_iter()
433            .filter_map(|entry| {
434                match apply_search_access(&se.ident, &search_related_acp, &entry) {
435                    SearchResult::Deny => {
436                        None
437                    }
438                    SearchResult::Grant => {
439                        // No properly written access module should allow
440                        // unbounded attribute read!
441                        error!("An access module allowed full read, this is a BUG! Denying read to prevent data leaks.");
442                        None
443                    }
444                    SearchResult::Allow(allowed_attrs) => {
445                        // The allow set constrained.
446                        debug!(
447                            requested = ?se.attrs,
448                            allowed = ?allowed_attrs,
449                            "reduction",
450                        );
451
452                        // Reduce requested by allowed.
453                        let reduced_attrs = if let Some(requested) = se.attrs.as_ref() {
454                            requested & &allowed_attrs
455                        } else {
456                            allowed_attrs
457                        };
458
459                        let effective_permissions = do_effective_check.as_ref().map(|do_check| {
460                            self.entry_effective_permission_check(
461                                &se.ident,
462                                &entry,
463                                &search_related_acp,
464                                &do_check.modify_related_acp,
465                                &do_check.delete_related_acp,
466                                do_check.sync_agmts,
467                            )
468                        })
469                        .map(Box::new);
470
471                        Some(entry.reduce_attributes(&reduced_attrs, effective_permissions))
472                    }
473                }
474
475                // End filter
476            })
477            .collect();
478
479        if allowed_entries.is_empty() {
480            if !entries_is_empty {
481                security_access!("reduced to empty set on all entries ❌");
482            }
483        } else {
484            debug!(
485                "attribute set reduced on {} entries ✅",
486                allowed_entries.len()
487            );
488        }
489
490        Ok(allowed_entries)
491    }
492
493    #[instrument(level = "trace", name = "access::modify_related_acp", skip_all)]
494    fn modify_related_acp<'b>(&'b self, ident: &Identity) -> Vec<AccessControlModifyResolved<'b>> {
495        // Some useful references we'll use for the remainder of the operation
496        let modify_state = self.get_modify();
497        let acp_resolve_filter_cache = self.get_acp_resolve_filter_cache();
498
499        let ident_memberof = ident.get_memberof();
500
501        // Find the acps that relate to the caller, and compile their related
502        // target filters.
503        let related_acp: Vec<_> = modify_state
504            .iter()
505            .filter_map(|acs| {
506                trace!(acs_name = ?acs.acp.name);
507                let (receiver_condition, target_condition) = resolve_access_conditions(
508                    ident,
509                    ident_memberof,
510                    &acs.acp.receiver,
511                    &acs.acp.target,
512                    acp_resolve_filter_cache,
513                )?;
514
515                Some(AccessControlModifyResolved {
516                    acp: acs,
517                    receiver_condition,
518                    target_condition,
519                })
520            })
521            .collect();
522
523        related_acp
524    }
525
526    #[instrument(level = "debug", name = "access::modify_allow_operation", skip_all)]
527    fn modify_allow_operation(
528        &self,
529        me: &ModifyEvent,
530        entries: &[Arc<EntrySealedCommitted>],
531    ) -> Result<bool, OperationError> {
532        // Find the acps that relate to the caller, and compile their related
533        // target filters.
534        let related_acp: Vec<_> = self.modify_related_acp(&me.ident);
535
536        let r = entries.iter().all(|e| {
537            self.modify_allow_operation_per_entry(&me.ident, &related_acp, e, &me.modlist)
538        });
539
540        if r {
541            debug!("allowed modify of {} entries ✅", entries.len());
542        } else {
543            security_access!("denied ❌ - modify may not proceed");
544        }
545        Ok(r)
546    }
547
548    #[instrument(
549        level = "debug",
550        name = "access::batch_modify_allow_operation",
551        skip_all
552    )]
553    fn batch_modify_allow_operation(
554        &self,
555        me: &BatchModifyEvent,
556        entries: &[Arc<EntrySealedCommitted>],
557    ) -> Result<bool, OperationError> {
558        // Find the acps that relate to the caller, and compile their related
559        // target filters.
560        let related_acp = self.modify_related_acp(&me.ident);
561
562        let r = entries.iter().all(|e| {
563            // Due to how batch mod works, we have to check the modlist *per entry* rather
564            // than as a whole.
565
566            let Some(modlist) = me.modset.get(&e.get_uuid()) else {
567                security_access!(
568                    "modlist not present for {}, failing operation.",
569                    e.get_uuid()
570                );
571                return false;
572            };
573
574            self.modify_allow_operation_per_entry(&me.ident, &related_acp, e, modlist)
575        });
576
577        if r {
578            debug!("allowed modify of {} entries ✅", entries.len());
579        } else {
580            security_access!("denied ❌ - modifications may not proceed");
581        }
582        Ok(r)
583    }
584
585    fn modify_allow_operation_per_entry(
586        &self,
587        ident: &Identity,
588        related_acp: &[AccessControlModifyResolved<'_>],
589        entry: &Arc<EntrySealedCommitted>,
590        modlist: &ModifyList<ModifyValid>,
591    ) -> bool {
592        let disallow = modlist
593            .iter()
594            .any(|m| matches!(m, Modify::Purged(a) if a == Attribute::Class.as_ref()));
595
596        if disallow {
597            security_access!("Disallowing purge in modification");
598            return false;
599        }
600
601        // build two sets of "requested pres" and "requested rem"
602        let requested_pres: BTreeSet<Attribute> = modlist
603            .iter()
604            .filter_map(|m| match m {
605                Modify::Present(a, _) | Modify::Set(a, _) | Modify::Assert(a, _) => Some(a.clone()),
606                Modify::Removed(_, _) | Modify::Purged(_) => None,
607            })
608            .collect();
609
610        let requested_rem: BTreeSet<Attribute> = modlist
611            .iter()
612            .filter_map(|m| match m {
613                Modify::Removed(a, _) | Modify::Purged(a) | Modify::Set(a, _) => Some(a.clone()),
614                Modify::Present(_, _) | Modify::Assert(_, _) => None,
615            })
616            .collect();
617
618        let mut requested_pres_classes: BTreeSet<&str> = Default::default();
619        let mut requested_rem_classes: BTreeSet<&str> = Default::default();
620
621        // This loop extracts what classes have been requested for modification so that we can
622        // apply our modify class rules.
623        for modify in modlist.iter() {
624            match modify {
625                Modify::Present(a, v) if a == Attribute::Class.as_ref() => {
626                    if let Some(s) = v.to_str() {
627                        requested_pres_classes.insert(s);
628                    } else {
629                        error!("invalid modify present state - class was unable to be determined");
630                        return false;
631                    }
632                }
633                Modify::Removed(a, v) if a == Attribute::Class.as_ref() => {
634                    if let Some(s) = v.to_str() {
635                        requested_rem_classes.insert(s);
636                    } else {
637                        error!("invalid modify removed state - class was unable to be determined");
638                        return false;
639                    }
640                }
641                Modify::Set(a, v) if a == Attribute::Class.as_ref() => {
642                    // When we apply the set of classes, we base the access control decision
643                    // only on what CHANGED, rather than the full set that is present.
644                    if let Some(current_classes) = entry.get_ava_as_iutf8(Attribute::Class) {
645                        if let Some(requested_classes) = v.as_iutf8_set() {
646                            // Diff the classes to determine what changed. We only perform access
647                            // checks on what is different, rather than everything in the set. This
648                            // is what allow's SCIM PUT to operate since you have to "set" every
649                            // value in the set, even if it's not one you have access too.
650                            requested_pres_classes.extend(
651                                requested_classes
652                                    .difference(current_classes)
653                                    .map(|s| s.as_str()),
654                            );
655                            requested_rem_classes.extend(
656                                current_classes
657                                    .difference(requested_classes)
658                                    .map(|s| s.as_str()),
659                            );
660                        } else {
661                            // This should be an impossible case - to have made it to this
662                            // point, then the modify should have passed schema validation
663                            // an must be a valid iutf8 set, and return a Some(). However
664                            // in the interest of completeness, we defend from this and
665                            // and deny the operation.
666                            error!("invalid valueset state - requested class set is not valid");
667                            return false;
668                        }
669                    } else {
670                        error!("invalid entry state - entry does not have attribute class and is not valid");
671                        return false;
672                    }
673                }
674                // No attribute::class present.
675                Modify::Set(_, _) | Modify::Removed(_, _) | Modify::Present(_, _) => {}
676                // Actions don't relate to gathering of classes for modification checks
677                Modify::Purged(_) | Modify::Assert(_, _) => {}
678            }
679        }
680
681        debug!(?requested_pres, "Requested present set");
682        debug!(?requested_rem, "Requested remove set");
683        debug!(?requested_pres_classes, "Requested present class set");
684        debug!(?requested_rem_classes, "Requested remove class set");
685        debug!(entry_id = %entry.get_display_id());
686
687        // You must request *at least* one change. Note that in the case a class
688        // is being changed, it must also have at least one pres/rem state also.
689        if requested_pres.is_empty() && requested_rem.is_empty() {
690            security_error!("No modifications were requested");
691            return false;
692        };
693
694        let sync_agmts = self.get_sync_agreements();
695
696        match apply_modify_access(ident, related_acp, sync_agmts, entry) {
697            ModifyResult::Deny => {
698                security_error!("modify access denied.");
699                false
700            }
701            ModifyResult::Grant => true,
702            ModifyResult::Allow {
703                pres,
704                rem,
705                pres_cls,
706                rem_cls,
707            } => {
708                let mut decision = true;
709
710                if !requested_pres.is_subset(&pres) {
711                    security_error!("requested_pres is not a subset of allowed");
712                    security_error!(
713                        "requested_pres: {:?} !⊆ allowed: {:?}",
714                        requested_pres,
715                        pres
716                    );
717                    decision = false
718                };
719
720                if !requested_rem.is_subset(&rem) {
721                    security_error!("requested_rem is not a subset of allowed");
722                    security_error!("requested_rem: {:?} !⊆ allowed: {:?}", requested_rem, rem);
723                    decision = false;
724                };
725
726                if !requested_pres_classes.is_subset(&pres_cls) {
727                    security_error!("requested_pres_classes is not a subset of allowed");
728                    security_error!(
729                        "requested_classes: {:?} !⊆ allowed: {:?}",
730                        requested_pres_classes,
731                        pres_cls
732                    );
733                    decision = false;
734                };
735
736                if !requested_rem_classes.is_subset(&rem_cls) {
737                    security_error!("requested_rem_classes is not a subset of allowed");
738                    security_error!(
739                        "requested_classes: {:?} !⊆ allowed: {:?}",
740                        requested_rem_classes,
741                        rem_cls
742                    );
743                    decision = false;
744                }
745
746                if decision {
747                    debug!("passed pres, rem, classes check.");
748                }
749
750                // Yield the result
751                decision
752            }
753        }
754    }
755
756    #[instrument(level = "debug", name = "access::create_allow_operation", skip_all)]
757    fn create_allow_operation(
758        &self,
759        ce: &CreateEvent,
760        entries: &[Entry<EntryInit, EntryNew>],
761    ) -> Result<bool, OperationError> {
762        // Some useful references we'll use for the remainder of the operation
763        let create_state = self.get_create();
764        let acp_resolve_filter_cache = self.get_acp_resolve_filter_cache();
765
766        let ident_memberof = ce.ident.get_memberof();
767
768        // Find the acps that relate to the caller.
769        let related_acp: Vec<_> = create_state
770            .iter()
771            .filter_map(|acs| {
772                let (receiver_condition, target_condition) = resolve_access_conditions(
773                    &ce.ident,
774                    ident_memberof,
775                    &acs.acp.receiver,
776                    &acs.acp.target,
777                    acp_resolve_filter_cache,
778                )?;
779
780                Some(AccessControlCreateResolved {
781                    acp: acs,
782                    receiver_condition,
783                    target_condition,
784                })
785            })
786            .collect();
787
788        // For each entry
789        let decision = entries.iter().all(|e| {
790            let requested_pres: BTreeSet<_> = e.attr_keys().cloned().collect();
791            let Some(requested_pres_classes) = e
792                .get_ava_as_iutf8(Attribute::Class)
793                .map(|set| set.iter().map(|s| s.as_str()).collect::<BTreeSet<_>>())
794            else {
795                error!("unable to perform access control checks on entry with no classes, denied.");
796                return false;
797            };
798
799            debug!(?requested_pres, "Requested present set");
800            debug!(?requested_pres_classes, "Requested present class set");
801            debug!(entry_id = %e.get_display_id());
802
803            match apply_create_access(&ce.ident, related_acp.as_slice(), e) {
804                CreateResult::Deny => false,
805                CreateResult::Grant => true,
806                CreateResult::Allow { pres, pres_cls } => {
807                    let mut decision = true;
808
809                    if !requested_pres.is_subset(&pres) {
810                        security_error!("requested_pres is not a subset of allowed");
811                        security_error!(
812                            "requested_pres: {:?} !⊆ allowed: {:?}",
813                            requested_pres,
814                            pres
815                        );
816                        decision = false
817                    };
818
819                    if !requested_pres_classes.is_subset(&pres_cls) {
820                        security_error!("requested_pres_classes is not a subset of allowed");
821                        security_error!(
822                            "requested_classes: {:?} !⊆ allowed: {:?}",
823                            requested_pres_classes,
824                            pres_cls
825                        );
826                        decision = false;
827                    };
828
829                    if decision {
830                        debug!("passed pres, classes check.");
831                    }
832
833                    decision
834                }
835            }
836        });
837
838        if decision {
839            debug!("allowed create of {} entries ✅", entries.len());
840        } else {
841            security_access!("denied ❌ - create may not proceed");
842        }
843
844        Ok(decision)
845    }
846
847    #[instrument(level = "trace", name = "access::delete_related_acp", skip_all)]
848    fn delete_related_acp<'b>(&'b self, ident: &Identity) -> Vec<AccessControlDeleteResolved<'b>> {
849        // Some useful references we'll use for the remainder of the operation
850        let delete_state = self.get_delete();
851        let acp_resolve_filter_cache = self.get_acp_resolve_filter_cache();
852
853        let ident_memberof = ident.get_memberof();
854
855        let related_acp: Vec<_> = delete_state
856            .iter()
857            .filter_map(|acs| {
858                let (receiver_condition, target_condition) = resolve_access_conditions(
859                    ident,
860                    ident_memberof,
861                    &acs.acp.receiver,
862                    &acs.acp.target,
863                    acp_resolve_filter_cache,
864                )?;
865
866                Some(AccessControlDeleteResolved {
867                    acp: acs,
868                    receiver_condition,
869                    target_condition,
870                })
871            })
872            .collect();
873
874        related_acp
875    }
876
877    #[instrument(level = "debug", name = "access::delete_allow_operation", skip_all)]
878    fn delete_allow_operation(
879        &self,
880        de: &DeleteEvent,
881        entries: &[Arc<EntrySealedCommitted>],
882    ) -> Result<bool, OperationError> {
883        // Find the acps that relate to the caller.
884        let related_acp = self.delete_related_acp(&de.ident);
885
886        // For each entry
887        let r = entries.iter().all(|e| {
888            match apply_delete_access(&de.ident, related_acp.as_slice(), e) {
889                DeleteResult::Deny => false,
890                DeleteResult::Grant => true,
891            }
892        });
893        if r {
894            debug!("allowed delete of {} entries ✅", entries.len());
895        } else {
896            security_access!("denied ❌ - delete may not proceed");
897        }
898        Ok(r)
899    }
900
901    #[instrument(level = "debug", name = "access::effective_permission_check", skip_all)]
902    fn effective_permission_check(
903        &self,
904        ident: &Identity,
905        attrs: Option<BTreeSet<Attribute>>,
906        entries: &[Arc<EntrySealedCommitted>],
907    ) -> Result<Vec<AccessEffectivePermission>, OperationError> {
908        // I think we need a structure like CheckResult, which is in the order of the
909        // entries, but also stashes the uuid. Then it has search, mod, create, delete,
910        // as separate attrs to describe what is capable.
911
912        // Does create make sense here? I don't think it does. Create requires you to
913        // have an entry template. I think james was right about the create being
914        // a template copy op ...
915
916        trace!(ident = %ident, "Effective permission check");
917        // I think we separate this to multiple checks ...?
918
919        // == search ==
920        // Get the relevant acps for this receiver.
921        let search_related_acp = self.search_related_acp(ident, attrs.as_ref());
922        // == modify ==
923        let modify_related_acp = self.modify_related_acp(ident);
924        // == delete ==
925        let delete_related_acp = self.delete_related_acp(ident);
926
927        let sync_agmts = self.get_sync_agreements();
928
929        let effective_permissions: Vec<_> = entries
930            .iter()
931            .map(|entry| {
932                self.entry_effective_permission_check(
933                    ident,
934                    entry,
935                    &search_related_acp,
936                    &modify_related_acp,
937                    &delete_related_acp,
938                    sync_agmts,
939                )
940            })
941            .collect();
942
943        effective_permissions.iter().for_each(|ep| {
944            trace!(?ep);
945        });
946
947        Ok(effective_permissions)
948    }
949
950    fn entry_effective_permission_check<'b>(
951        &'b self,
952        ident: &Identity,
953        entry: &Arc<EntrySealedCommitted>,
954        search_related_acp: &[AccessControlSearchResolved<'b>],
955        modify_related_acp: &[AccessControlModifyResolved<'b>],
956        delete_related_acp: &[AccessControlDeleteResolved<'b>],
957        sync_agmts: &HashMap<Uuid, BTreeSet<Attribute>>,
958    ) -> AccessEffectivePermission {
959        // == search ==
960        let search_effective = match apply_search_access(ident, search_related_acp, entry) {
961            SearchResult::Deny => Access::Deny,
962            SearchResult::Grant => Access::Grant,
963            SearchResult::Allow(allowed_attrs) => {
964                // Bound by requested attrs?
965                Access::Allow(allowed_attrs.into_iter().collect())
966            }
967        };
968
969        // == modify ==
970        let (modify_pres, modify_rem, modify_pres_class, modify_rem_class) =
971            match apply_modify_access(ident, modify_related_acp, sync_agmts, entry) {
972                ModifyResult::Deny => (
973                    Access::Deny,
974                    Access::Deny,
975                    AccessClass::Deny,
976                    AccessClass::Deny,
977                ),
978                ModifyResult::Grant => (
979                    Access::Grant,
980                    Access::Grant,
981                    AccessClass::Grant,
982                    AccessClass::Grant,
983                ),
984                ModifyResult::Allow {
985                    pres,
986                    rem,
987                    pres_cls,
988                    rem_cls,
989                } => (
990                    Access::Allow(pres.into_iter().collect()),
991                    Access::Allow(rem.into_iter().collect()),
992                    AccessClass::Allow(pres_cls.into_iter().map(|s| s.into()).collect()),
993                    AccessClass::Allow(rem_cls.into_iter().map(|s| s.into()).collect()),
994                ),
995            };
996
997        // == delete ==
998        let delete_status = apply_delete_access(ident, delete_related_acp, entry);
999
1000        let delete = match delete_status {
1001            DeleteResult::Deny => false,
1002            DeleteResult::Grant => true,
1003        };
1004
1005        AccessEffectivePermission {
1006            ident: ident.get_uuid(),
1007            target: entry.get_uuid(),
1008            delete,
1009            search: search_effective,
1010            modify_pres,
1011            modify_rem,
1012            modify_pres_class,
1013            modify_rem_class,
1014        }
1015    }
1016}
1017
1018pub struct AccessControlsWriteTransaction<'a> {
1019    inner: CowCellWriteTxn<'a, AccessControlsInner>,
1020    acp_resolve_filter_cache: Cell<ResolveFilterCacheReadTxn<'a>>,
1021}
1022
1023impl AccessControlsWriteTransaction<'_> {
1024    // We have a method to update each set, so that if an error
1025    // occurs we KNOW it's an error, rather than using errors as
1026    // part of the logic (IE try-parse-fail method).
1027    pub fn update_search(
1028        &mut self,
1029        mut acps: Vec<AccessControlSearch>,
1030    ) -> Result<(), OperationError> {
1031        std::mem::swap(&mut acps, &mut self.inner.deref_mut().acps_search);
1032        Ok(())
1033    }
1034
1035    pub fn update_create(
1036        &mut self,
1037        mut acps: Vec<AccessControlCreate>,
1038    ) -> Result<(), OperationError> {
1039        std::mem::swap(&mut acps, &mut self.inner.deref_mut().acps_create);
1040        Ok(())
1041    }
1042
1043    pub fn update_modify(
1044        &mut self,
1045        mut acps: Vec<AccessControlModify>,
1046    ) -> Result<(), OperationError> {
1047        std::mem::swap(&mut acps, &mut self.inner.deref_mut().acps_modify);
1048        Ok(())
1049    }
1050
1051    pub fn update_delete(
1052        &mut self,
1053        mut acps: Vec<AccessControlDelete>,
1054    ) -> Result<(), OperationError> {
1055        std::mem::swap(&mut acps, &mut self.inner.deref_mut().acps_delete);
1056        Ok(())
1057    }
1058
1059    pub fn update_sync_agreements(
1060        &mut self,
1061        mut sync_agreements: HashMap<Uuid, BTreeSet<Attribute>>,
1062    ) {
1063        std::mem::swap(
1064            &mut sync_agreements,
1065            &mut self.inner.deref_mut().sync_agreements,
1066        );
1067    }
1068
1069    pub fn commit(self) -> Result<(), OperationError> {
1070        self.inner.commit();
1071
1072        Ok(())
1073    }
1074}
1075
1076impl<'a> AccessControlsTransaction<'a> for AccessControlsWriteTransaction<'a> {
1077    fn get_search(&self) -> &Vec<AccessControlSearch> {
1078        &self.inner.acps_search
1079    }
1080
1081    fn get_create(&self) -> &Vec<AccessControlCreate> {
1082        &self.inner.acps_create
1083    }
1084
1085    fn get_modify(&self) -> &Vec<AccessControlModify> {
1086        &self.inner.acps_modify
1087    }
1088
1089    fn get_delete(&self) -> &Vec<AccessControlDelete> {
1090        &self.inner.acps_delete
1091    }
1092
1093    fn get_sync_agreements(&self) -> &HashMap<Uuid, BTreeSet<Attribute>> {
1094        &self.inner.sync_agreements
1095    }
1096
1097    fn get_acp_resolve_filter_cache(&self) -> &mut ResolveFilterCacheReadTxn<'a> {
1098        unsafe {
1099            let mptr = self.acp_resolve_filter_cache.as_ptr();
1100            &mut (*mptr) as &mut ResolveFilterCacheReadTxn<'a>
1101        }
1102    }
1103}
1104
1105// =========================================================================
1106// ACP operations (Should this actually be on the ACP's themself?
1107// =========================================================================
1108
1109pub struct AccessControlsReadTransaction<'a> {
1110    inner: CowCellReadTxn<AccessControlsInner>,
1111    // acp_related_search_cache: Cell<ARCacheReadTxn<'a, Uuid, Vec<Uuid>>>,
1112    acp_resolve_filter_cache: Cell<ResolveFilterCacheReadTxn<'a>>,
1113}
1114
1115unsafe impl Sync for AccessControlsReadTransaction<'_> {}
1116
1117unsafe impl Send for AccessControlsReadTransaction<'_> {}
1118
1119impl<'a> AccessControlsTransaction<'a> for AccessControlsReadTransaction<'a> {
1120    fn get_search(&self) -> &Vec<AccessControlSearch> {
1121        &self.inner.acps_search
1122    }
1123
1124    fn get_create(&self) -> &Vec<AccessControlCreate> {
1125        &self.inner.acps_create
1126    }
1127
1128    fn get_modify(&self) -> &Vec<AccessControlModify> {
1129        &self.inner.acps_modify
1130    }
1131
1132    fn get_delete(&self) -> &Vec<AccessControlDelete> {
1133        &self.inner.acps_delete
1134    }
1135
1136    fn get_sync_agreements(&self) -> &HashMap<Uuid, BTreeSet<Attribute>> {
1137        &self.inner.sync_agreements
1138    }
1139
1140    fn get_acp_resolve_filter_cache(&self) -> &mut ResolveFilterCacheReadTxn<'a> {
1141        unsafe {
1142            let mptr = self.acp_resolve_filter_cache.as_ptr();
1143            &mut (*mptr) as &mut ResolveFilterCacheReadTxn<'a>
1144        }
1145    }
1146}
1147
1148// =========================================================================
1149// ACP transaction operations
1150// =========================================================================
1151
1152impl Default for AccessControls {
1153    #![allow(clippy::expect_used)]
1154    fn default() -> Self {
1155        AccessControls {
1156            inner: CowCell::new(AccessControlsInner {
1157                acps_search: Vec::with_capacity(0),
1158                acps_create: Vec::with_capacity(0),
1159                acps_modify: Vec::with_capacity(0),
1160                acps_delete: Vec::with_capacity(0),
1161                sync_agreements: HashMap::default(),
1162            }),
1163            // Allow the expect, if this fails it represents a programming/development
1164            // failure.
1165            acp_resolve_filter_cache: ARCacheBuilder::new()
1166                .set_size(ACP_RESOLVE_FILTER_CACHE_MAX, ACP_RESOLVE_FILTER_CACHE_LOCAL)
1167                .set_reader_quiesce(true)
1168                .build()
1169                .expect("Failed to construct acp_resolve_filter_cache"),
1170        }
1171    }
1172}
1173
1174impl AccessControls {
1175    pub fn try_quiesce(&self) {
1176        self.acp_resolve_filter_cache.try_quiesce();
1177    }
1178
1179    pub fn read(&self) -> AccessControlsReadTransaction<'_> {
1180        AccessControlsReadTransaction {
1181            inner: self.inner.read(),
1182            // acp_related_search_cache: Cell::new(self.acp_related_search_cache.read()),
1183            acp_resolve_filter_cache: Cell::new(self.acp_resolve_filter_cache.read()),
1184        }
1185    }
1186
1187    pub fn write(&self) -> AccessControlsWriteTransaction<'_> {
1188        AccessControlsWriteTransaction {
1189            inner: self.inner.write(),
1190            // acp_related_search_cache_wr: self.acp_related_search_cache.write(),
1191            // acp_related_search_cache: Cell::new(self.acp_related_search_cache.read()),
1192            acp_resolve_filter_cache: Cell::new(self.acp_resolve_filter_cache.read()),
1193        }
1194    }
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199    use hashbrown::HashMap;
1200    use std::{collections::BTreeSet, sync::Arc};
1201
1202    use uuid::uuid;
1203
1204    use super::{
1205        profiles::{
1206            AccessControlCreate, AccessControlDelete, AccessControlModify, AccessControlProfile,
1207            AccessControlSearch, AccessControlTarget,
1208        },
1209        Access, AccessClass, AccessControls, AccessControlsTransaction, AccessEffectivePermission,
1210    };
1211    use crate::{migration_data::BUILTIN_ACCOUNT_ANONYMOUS, prelude::*, valueset::ValueSetIname};
1212
1213    const UUID_TEST_ACCOUNT_1: Uuid = uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930");
1214    const UUID_TEST_ACCOUNT_2: Uuid = uuid::uuid!("cec0852a-abdf-4ea6-9dae-d3157cb33d3a");
1215    const UUID_TEST_GROUP_1: Uuid = uuid::uuid!("81ec1640-3637-4a2f-8a52-874fa3c3c92f");
1216    const UUID_TEST_GROUP_2: Uuid = uuid::uuid!("acae81d6-5ea7-4bd8-8f7f-fcec4c0dd647");
1217
1218    pub static E_TEST_ACCOUNT_1: LazyLock<Arc<EntrySealedCommitted>> = LazyLock::new(|| {
1219        Arc::new(
1220            entry_init!(
1221                (Attribute::Class, EntryClass::Object.to_value()),
1222                (Attribute::Name, Value::new_iname("test_account_1")),
1223                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
1224                (Attribute::MemberOf, Value::ReferN(UUID_TEST_GROUP_1))
1225            )
1226            .into_sealed_committed(),
1227        )
1228    });
1229    pub static E_TEST_ACCOUNT_2: LazyLock<Arc<EntrySealedCommitted>> = LazyLock::new(|| {
1230        Arc::new(
1231            entry_init!(
1232                (Attribute::Class, EntryClass::Object.to_value()),
1233                (Attribute::Name, Value::new_iname("test_account_1")),
1234                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_2)),
1235                (Attribute::MemberOf, Value::ReferN(UUID_TEST_GROUP_2))
1236            )
1237            .into_sealed_committed(),
1238        )
1239    });
1240
1241    macro_rules! acp_from_entry_err {
1242        (
1243            $qs:expr,
1244            $e:expr,
1245            $type:ty
1246        ) => {{
1247            let ev1 = $e.into_sealed_committed();
1248
1249            let r1 = <$type>::try_from($qs, &ev1);
1250            error!(?r1);
1251            assert!(r1.is_err());
1252        }};
1253    }
1254
1255    macro_rules! acp_from_entry_ok {
1256        (
1257            $qs:expr,
1258            $e:expr,
1259            $type:ty
1260        ) => {{
1261            let ev1 = $e.into_sealed_committed();
1262
1263            let r1 = <$type>::try_from($qs, &ev1);
1264            assert!(r1.is_ok());
1265            r1.unwrap()
1266        }};
1267    }
1268
1269    #[qs_test]
1270    async fn test_access_acp_parser(qs: &QueryServer) {
1271        // Test parsing entries to acp. There so no point testing schema violations
1272        // because the schema system is well tested an robust. Instead we target
1273        // entry misconfigurations, such as missing classes required.
1274
1275        // Generally, we are testing the *positive* cases here, because schema
1276        // really protects us *a lot* here, but it's nice to have defence and
1277        // layers of validation.
1278
1279        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1280
1281        acp_from_entry_err!(
1282            &mut qs_write,
1283            entry_init!(
1284                (Attribute::Class, EntryClass::Object.to_value()),
1285                (Attribute::Name, Value::new_iname("acp_invalid")),
1286                (
1287                    Attribute::Uuid,
1288                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1289                )
1290            ),
1291            AccessControlProfile
1292        );
1293
1294        acp_from_entry_err!(
1295            &mut qs_write,
1296            entry_init!(
1297                (Attribute::Class, EntryClass::Object.to_value()),
1298                (
1299                    Attribute::Class,
1300                    EntryClass::AccessControlProfile.to_value()
1301                ),
1302                (
1303                    Attribute::Class,
1304                    EntryClass::AccessControlReceiverGroup.to_value()
1305                ),
1306                (
1307                    Attribute::Class,
1308                    EntryClass::AccessControlTargetScope.to_value()
1309                ),
1310                (Attribute::Name, Value::new_iname("acp_invalid")),
1311                (
1312                    Attribute::Uuid,
1313                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1314                )
1315            ),
1316            AccessControlProfile
1317        );
1318
1319        acp_from_entry_err!(
1320            &mut qs_write,
1321            entry_init!(
1322                (Attribute::Class, EntryClass::Object.to_value()),
1323                (
1324                    Attribute::Class,
1325                    EntryClass::AccessControlProfile.to_value()
1326                ),
1327                (
1328                    Attribute::Class,
1329                    EntryClass::AccessControlReceiverGroup.to_value()
1330                ),
1331                (
1332                    Attribute::Class,
1333                    EntryClass::AccessControlTargetScope.to_value()
1334                ),
1335                (Attribute::Name, Value::new_iname("acp_invalid")),
1336                (
1337                    Attribute::Uuid,
1338                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1339                ),
1340                (Attribute::AcpReceiverGroup, Value::Bool(true)),
1341                (Attribute::AcpTargetScope, Value::Bool(true))
1342            ),
1343            AccessControlProfile
1344        );
1345
1346        // "\"Self\""
1347        acp_from_entry_ok!(
1348            &mut qs_write,
1349            entry_init!(
1350                (Attribute::Class, EntryClass::Object.to_value()),
1351                (
1352                    Attribute::Class,
1353                    EntryClass::AccessControlProfile.to_value()
1354                ),
1355                (
1356                    Attribute::Class,
1357                    EntryClass::AccessControlReceiverGroup.to_value()
1358                ),
1359                (
1360                    Attribute::Class,
1361                    EntryClass::AccessControlTargetScope.to_value()
1362                ),
1363                (Attribute::Name, Value::new_iname("acp_valid")),
1364                (
1365                    Attribute::Uuid,
1366                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1367                ),
1368                (
1369                    Attribute::AcpReceiverGroup,
1370                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1371                ),
1372                (
1373                    Attribute::AcpTargetScope,
1374                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1375                )
1376            ),
1377            AccessControlProfile
1378        );
1379    }
1380
1381    #[qs_test]
1382    async fn test_access_acp_delete_parser(qs: &QueryServer) {
1383        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1384
1385        acp_from_entry_err!(
1386            &mut qs_write,
1387            entry_init!(
1388                (Attribute::Class, EntryClass::Object.to_value()),
1389                (
1390                    Attribute::Class,
1391                    EntryClass::AccessControlProfile.to_value()
1392                ),
1393                (Attribute::Name, Value::new_iname("acp_valid")),
1394                (
1395                    Attribute::Uuid,
1396                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1397                ),
1398                (
1399                    Attribute::AcpReceiverGroup,
1400                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1401                ),
1402                (
1403                    Attribute::AcpTargetScope,
1404                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1405                )
1406            ),
1407            AccessControlDelete
1408        );
1409
1410        acp_from_entry_ok!(
1411            &mut qs_write,
1412            entry_init!(
1413                (Attribute::Class, EntryClass::Object.to_value()),
1414                (
1415                    Attribute::Class,
1416                    EntryClass::AccessControlProfile.to_value()
1417                ),
1418                (Attribute::Class, EntryClass::AccessControlDelete.to_value()),
1419                (Attribute::Name, Value::new_iname("acp_valid")),
1420                (
1421                    Attribute::Uuid,
1422                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1423                ),
1424                (
1425                    Attribute::AcpReceiverGroup,
1426                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1427                ),
1428                (
1429                    Attribute::AcpTargetScope,
1430                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1431                )
1432            ),
1433            AccessControlDelete
1434        );
1435    }
1436
1437    #[qs_test]
1438    async fn test_access_acp_search_parser(qs: &QueryServer) {
1439        // Test that parsing search access controls works.
1440        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1441
1442        // Missing class acp
1443        acp_from_entry_err!(
1444            &mut qs_write,
1445            entry_init!(
1446                (Attribute::Class, EntryClass::Object.to_value()),
1447                (Attribute::Class, EntryClass::AccessControlSearch.to_value()),
1448                (Attribute::Name, Value::new_iname("acp_valid")),
1449                (
1450                    Attribute::Uuid,
1451                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1452                ),
1453                (
1454                    Attribute::AcpReceiverGroup,
1455                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1456                ),
1457                (
1458                    Attribute::AcpTargetScope,
1459                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1460                ),
1461                (
1462                    Attribute::AcpSearchAttr,
1463                    Value::new_iutf8n(Attribute::Name.as_str())
1464                ),
1465                (
1466                    Attribute::AcpSearchAttr,
1467                    Value::new_iutf8n(Attribute::Class.as_str())
1468                )
1469            ),
1470            AccessControlSearch
1471        );
1472
1473        // Missing class acs
1474        acp_from_entry_err!(
1475            &mut qs_write,
1476            entry_init!(
1477                (Attribute::Class, EntryClass::Object.to_value()),
1478                (
1479                    Attribute::Class,
1480                    EntryClass::AccessControlProfile.to_value()
1481                ),
1482                (Attribute::Name, Value::new_iname("acp_valid")),
1483                (
1484                    Attribute::Uuid,
1485                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1486                ),
1487                (
1488                    Attribute::AcpReceiverGroup,
1489                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1490                ),
1491                (
1492                    Attribute::AcpTargetScope,
1493                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1494                ),
1495                (
1496                    Attribute::AcpSearchAttr,
1497                    Value::new_iutf8n(Attribute::Name.as_str())
1498                ),
1499                (
1500                    Attribute::AcpSearchAttr,
1501                    Value::new_iutf8n(Attribute::Class.as_str())
1502                )
1503            ),
1504            AccessControlSearch
1505        );
1506
1507        // Missing attr acp_search_attr
1508        acp_from_entry_err!(
1509            &mut qs_write,
1510            entry_init!(
1511                (Attribute::Class, EntryClass::Object.to_value()),
1512                (
1513                    Attribute::Class,
1514                    EntryClass::AccessControlProfile.to_value()
1515                ),
1516                (Attribute::Class, EntryClass::AccessControlSearch.to_value()),
1517                (Attribute::Name, Value::new_iname("acp_valid")),
1518                (
1519                    Attribute::Uuid,
1520                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1521                ),
1522                (
1523                    Attribute::AcpReceiverGroup,
1524                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1525                ),
1526                (
1527                    Attribute::AcpTargetScope,
1528                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1529                )
1530            ),
1531            AccessControlSearch
1532        );
1533
1534        // All good!
1535        acp_from_entry_ok!(
1536            &mut qs_write,
1537            entry_init!(
1538                (Attribute::Class, EntryClass::Object.to_value()),
1539                (
1540                    Attribute::Class,
1541                    EntryClass::AccessControlProfile.to_value()
1542                ),
1543                (Attribute::Class, EntryClass::AccessControlSearch.to_value()),
1544                (Attribute::Name, Value::new_iname("acp_valid")),
1545                (
1546                    Attribute::Uuid,
1547                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1548                ),
1549                (
1550                    Attribute::AcpReceiverGroup,
1551                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1552                ),
1553                (
1554                    Attribute::AcpTargetScope,
1555                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1556                ),
1557                (
1558                    Attribute::AcpSearchAttr,
1559                    Value::new_iutf8n(Attribute::Name.as_str())
1560                ),
1561                (
1562                    Attribute::AcpSearchAttr,
1563                    Value::new_iutf8n(Attribute::Class.as_str())
1564                )
1565            ),
1566            AccessControlSearch
1567        );
1568    }
1569
1570    #[qs_test]
1571    async fn test_access_acp_modify_parser(qs: &QueryServer) {
1572        // Test that parsing modify access controls works.
1573        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1574
1575        acp_from_entry_err!(
1576            &mut qs_write,
1577            entry_init!(
1578                (Attribute::Class, EntryClass::Object.to_value()),
1579                (
1580                    Attribute::Class,
1581                    EntryClass::AccessControlProfile.to_value()
1582                ),
1583                (Attribute::Name, Value::new_iname("acp_invalid")),
1584                (
1585                    Attribute::Uuid,
1586                    Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1587                ),
1588                (
1589                    Attribute::AcpReceiverGroup,
1590                    Value::ReferN(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1591                ),
1592                (
1593                    Attribute::AcpTargetScope,
1594                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1595                )
1596            ),
1597            AccessControlModify
1598        );
1599
1600        acp_from_entry_ok!(
1601            &mut qs_write,
1602            entry_init!(
1603                (Attribute::Class, EntryClass::Object.to_value()),
1604                (
1605                    Attribute::Class,
1606                    EntryClass::AccessControlProfile.to_value()
1607                ),
1608                (Attribute::Class, EntryClass::AccessControlModify.to_value()),
1609                (Attribute::Name, Value::new_iname("acp_valid")),
1610                (
1611                    Attribute::Uuid,
1612                    Value::Uuid(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1613                ),
1614                (
1615                    Attribute::AcpReceiverGroup,
1616                    Value::ReferN(uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1617                ),
1618                (
1619                    Attribute::AcpTargetScope,
1620                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1621                )
1622            ),
1623            AccessControlModify
1624        );
1625
1626        acp_from_entry_ok!(
1627            &mut qs_write,
1628            entry_init!(
1629                (Attribute::Class, EntryClass::Object.to_value()),
1630                (
1631                    Attribute::Class,
1632                    EntryClass::AccessControlProfile.to_value()
1633                ),
1634                (Attribute::Class, EntryClass::AccessControlModify.to_value()),
1635                (Attribute::Name, Value::new_iname("acp_valid")),
1636                (
1637                    Attribute::Uuid,
1638                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1639                ),
1640                (
1641                    Attribute::AcpReceiverGroup,
1642                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1643                ),
1644                (
1645                    Attribute::AcpTargetScope,
1646                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1647                ),
1648                (
1649                    Attribute::AcpModifyRemovedAttr,
1650                    Value::new_iutf8n(Attribute::Name.as_str())
1651                ),
1652                (
1653                    Attribute::AcpModifyPresentAttr,
1654                    Value::new_iutf8n(Attribute::Name.as_str())
1655                ),
1656                (Attribute::AcpModifyClass, EntryClass::Object.to_value())
1657            ),
1658            AccessControlModify
1659        );
1660    }
1661
1662    #[qs_test]
1663    async fn test_access_acp_create_parser(qs: &QueryServer) {
1664        // Test that parsing create access controls works.
1665        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1666
1667        acp_from_entry_err!(
1668            &mut qs_write,
1669            entry_init!(
1670                (Attribute::Class, EntryClass::Object.to_value()),
1671                (
1672                    Attribute::Class,
1673                    EntryClass::AccessControlProfile.to_value()
1674                ),
1675                (Attribute::Name, Value::new_iname("acp_invalid")),
1676                (
1677                    Attribute::Uuid,
1678                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1679                ),
1680                (
1681                    Attribute::AcpReceiverGroup,
1682                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1683                ),
1684                (
1685                    Attribute::AcpTargetScope,
1686                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1687                ),
1688                (
1689                    Attribute::AcpCreateAttr,
1690                    Value::new_iutf8n(Attribute::Name.as_str())
1691                ),
1692                (Attribute::AcpCreateClass, EntryClass::Object.to_value())
1693            ),
1694            AccessControlCreate
1695        );
1696
1697        acp_from_entry_ok!(
1698            &mut qs_write,
1699            entry_init!(
1700                (Attribute::Class, EntryClass::Object.to_value()),
1701                (
1702                    Attribute::Class,
1703                    EntryClass::AccessControlProfile.to_value()
1704                ),
1705                (Attribute::Class, EntryClass::AccessControlCreate.to_value()),
1706                (Attribute::Name, Value::new_iname("acp_valid")),
1707                (
1708                    Attribute::Uuid,
1709                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1710                ),
1711                (
1712                    Attribute::AcpReceiverGroup,
1713                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1714                ),
1715                (
1716                    Attribute::AcpTargetScope,
1717                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1718                )
1719            ),
1720            AccessControlCreate
1721        );
1722
1723        acp_from_entry_ok!(
1724            &mut qs_write,
1725            entry_init!(
1726                (Attribute::Class, EntryClass::Object.to_value()),
1727                (
1728                    Attribute::Class,
1729                    EntryClass::AccessControlProfile.to_value()
1730                ),
1731                (Attribute::Class, EntryClass::AccessControlCreate.to_value()),
1732                (Attribute::Name, Value::new_iname("acp_valid")),
1733                (
1734                    Attribute::Uuid,
1735                    Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1736                ),
1737                (
1738                    Attribute::AcpReceiverGroup,
1739                    Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1740                ),
1741                (
1742                    Attribute::AcpTargetScope,
1743                    Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1744                ),
1745                (
1746                    Attribute::AcpCreateAttr,
1747                    Value::new_iutf8n(Attribute::Name.as_str())
1748                ),
1749                (
1750                    Attribute::AcpCreateClass,
1751                    Value::new_iutf8n(EntryClass::Object.as_str())
1752                )
1753            ),
1754            AccessControlCreate
1755        );
1756    }
1757
1758    #[qs_test]
1759    async fn test_access_acp_compound_parser(qs: &QueryServer) {
1760        // Test that parsing compound access controls works. This means that
1761        // given a single &str, we can evaluate all types from a single record.
1762        // This is valid, and could exist, IE a rule to allow create, search and modify
1763        // over a single scope.
1764        let mut qs_write = qs.write(duration_from_epoch_now()).await.unwrap();
1765
1766        let e = entry_init!(
1767            (Attribute::Class, EntryClass::Object.to_value()),
1768            (
1769                Attribute::Class,
1770                EntryClass::AccessControlProfile.to_value()
1771            ),
1772            (Attribute::Class, EntryClass::AccessControlCreate.to_value()),
1773            (Attribute::Class, EntryClass::AccessControlDelete.to_value()),
1774            (Attribute::Class, EntryClass::AccessControlModify.to_value()),
1775            (Attribute::Class, EntryClass::AccessControlSearch.to_value()),
1776            (Attribute::Name, Value::new_iname("acp_valid")),
1777            (
1778                Attribute::Uuid,
1779                Value::Uuid(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1780            ),
1781            (
1782                Attribute::AcpReceiverGroup,
1783                Value::ReferN(uuid::uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"))
1784            ),
1785            (
1786                Attribute::AcpTargetScope,
1787                Value::new_json_filter_s("{\"eq\":[\"name\",\"a\"]}").expect("filter")
1788            ),
1789            (
1790                Attribute::AcpSearchAttr,
1791                Value::new_iutf8n(Attribute::Name.as_str())
1792            ),
1793            (
1794                Attribute::AcpCreateClass,
1795                Value::new_iutf8n(EntryClass::Class.as_str())
1796            ),
1797            (
1798                Attribute::AcpCreateAttr,
1799                Value::new_iutf8n(Attribute::Name.as_str())
1800            ),
1801            (
1802                Attribute::AcpModifyRemovedAttr,
1803                Value::new_iutf8n(Attribute::Name.as_str())
1804            ),
1805            (
1806                Attribute::AcpModifyPresentAttr,
1807                Value::new_iutf8n(Attribute::Name.as_str())
1808            ),
1809            (
1810                Attribute::AcpModifyClass,
1811                Value::new_iutf8n(EntryClass::Object.as_str())
1812            )
1813        );
1814
1815        acp_from_entry_ok!(&mut qs_write, e.clone(), AccessControlCreate);
1816        acp_from_entry_ok!(&mut qs_write, e.clone(), AccessControlDelete);
1817        acp_from_entry_ok!(&mut qs_write, e.clone(), AccessControlModify);
1818        acp_from_entry_ok!(&mut qs_write, e, AccessControlSearch);
1819    }
1820
1821    macro_rules! test_acp_search {
1822        (
1823            $se:expr,
1824            $controls:expr,
1825            $entries:expr,
1826            $expect:expr
1827        ) => {{
1828            let ac = AccessControls::default();
1829            let mut acw = ac.write();
1830            acw.update_search($controls).expect("Failed to update");
1831            let acw = acw;
1832
1833            let res = acw
1834                .search_filter_entries(&mut $se, $entries)
1835                .expect("op failed");
1836            debug!("result --> {:?}", res);
1837            debug!("expect --> {:?}", $expect);
1838            // should be ok, and same as expect.
1839            assert_eq!(res, $expect);
1840        }};
1841    }
1842
1843    fn test_acp_search_reduce(
1844        se: &SearchEvent,
1845        controls: Vec<AccessControlSearch>,
1846        entries: Vec<Arc<EntrySealedCommitted>>,
1847        expect: Vec<EntrySealedCommitted>,
1848    ) {
1849        let ac = AccessControls::default();
1850        let mut acw = ac.write();
1851        acw.update_search(controls).expect("Failed to update");
1852        let acw = acw;
1853
1854        // We still have to reduce the entries to be sure that we are good.
1855        let res = acw
1856            .search_filter_entries(se, entries)
1857            .expect("operation failed");
1858        // Now on the reduced entries, reduce the entries attrs.
1859        let reduced = acw
1860            .search_filter_entry_attributes(se, res)
1861            .expect("operation failed");
1862
1863        // Help the type checker for the expect set.
1864        let expect_set: Vec<EntryReducedCommitted> =
1865            expect.into_iter().map(|e| e.into_reduced()).collect();
1866
1867        debug!("expect --> {:?}", expect_set);
1868        debug!("result --> {:?}", reduced);
1869        // should be ok, and same as expect.
1870        assert_eq!(reduced, expect_set);
1871    }
1872
1873    #[test]
1874    fn test_access_internal_search() {
1875        // Test that an internal search bypasses ACS
1876        let se = SearchEvent::new_internal_invalid(filter!(f_pres(Attribute::Class)));
1877
1878        let expect = vec![E_TEST_ACCOUNT_1.clone()];
1879        let entries = vec![E_TEST_ACCOUNT_1.clone()];
1880
1881        // This acp basically is "allow access to stuff, but not this".
1882        test_acp_search!(
1883            &se,
1884            vec![AccessControlSearch::from_raw(
1885                "test_acp",
1886                Uuid::new_v4(),
1887                UUID_TEST_GROUP_1,
1888                filter_valid!(f_pres(Attribute::NonExist)), // apply to none - ie no allowed results
1889                Attribute::Name.as_ref(), // allow to this attr, but we don't eval this.
1890            )],
1891            entries,
1892            expect
1893        );
1894    }
1895
1896    #[test]
1897    fn test_access_enforce_search() {
1898        // Test that entries from a search are reduced by acps
1899        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
1900        let ev2 = E_TESTPERSON_2.clone().into_sealed_committed();
1901
1902        let r_set = vec![Arc::new(ev1.clone()), Arc::new(ev2)];
1903
1904        let se_a = SearchEvent::new_impersonate_entry(
1905            E_TEST_ACCOUNT_1.clone(),
1906            filter_all!(f_pres(Attribute::Name)),
1907        );
1908        let ex_a = vec![Arc::new(ev1)];
1909
1910        let se_b = SearchEvent::new_impersonate_entry(
1911            E_TEST_ACCOUNT_2.clone(),
1912            filter_all!(f_pres(Attribute::Name)),
1913        );
1914        let ex_b = vec![];
1915
1916        let acp = AccessControlSearch::from_raw(
1917            "test_acp",
1918            Uuid::new_v4(),
1919            // apply to admin only
1920            UUID_TEST_GROUP_1,
1921            // Allow admin to read only testperson1
1922            filter_valid!(f_eq(
1923                Attribute::Name,
1924                PartialValue::new_iname("testperson1")
1925            )),
1926            // In that read, admin may only view the "name" attribute, or query on
1927            // the name attribute. Any other query (should be) rejected.
1928            Attribute::Name.as_ref(),
1929        );
1930
1931        // Check the admin search event
1932        test_acp_search!(&se_a, vec![acp.clone()], r_set.clone(), ex_a);
1933
1934        // Check the anonymous
1935        test_acp_search!(&se_b, vec![acp], r_set, ex_b);
1936    }
1937
1938    #[test]
1939    fn test_access_enforce_scope_search() {
1940        sketching::test_init();
1941        // Test that identities are bound by their access scope.
1942        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
1943
1944        let ex_some = vec![Arc::new(ev1.clone())];
1945
1946        let r_set = vec![Arc::new(ev1)];
1947
1948        let se_ro = SearchEvent::new_impersonate_identity(
1949            Identity::from_impersonate_entry_readonly(E_TEST_ACCOUNT_1.clone()),
1950            filter_all!(f_pres(Attribute::Name)),
1951        );
1952
1953        let se_rw = SearchEvent::new_impersonate_identity(
1954            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
1955            filter_all!(f_pres(Attribute::Name)),
1956        );
1957
1958        let acp = AccessControlSearch::from_raw(
1959            "test_acp",
1960            Uuid::new_v4(),
1961            // apply to admin only
1962            UUID_TEST_GROUP_1,
1963            // Allow admin to read only testperson1
1964            filter_valid!(f_eq(
1965                Attribute::Name,
1966                PartialValue::new_iname("testperson1")
1967            )),
1968            // In that read, admin may only view the "name" attribute, or query on
1969            // the name attribute. Any other query (should be) rejected.
1970            Attribute::Name.as_ref(),
1971        );
1972
1973        // Check the admin search event
1974        test_acp_search!(&se_ro, vec![acp.clone()], r_set.clone(), ex_some);
1975
1976        test_acp_search!(&se_rw, vec![acp], r_set, ex_some);
1977    }
1978
1979    #[test]
1980    fn test_access_enforce_scope_search_attrs() {
1981        // Test that in ident only mode that all attrs are always denied. The op should already have
1982        // "nothing to do" based on search_filter_entries, but we do the "right thing" anyway.
1983
1984        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
1985        let r_set = vec![Arc::new(ev1)];
1986
1987        let exv1 = E_TESTPERSON_1_REDUCED.clone().into_sealed_committed();
1988
1989        let ex_anon_some = vec![exv1];
1990
1991        let se_anon_ro = SearchEvent::new_impersonate_identity(
1992            Identity::from_impersonate_entry_readonly(E_TEST_ACCOUNT_1.clone()),
1993            filter_all!(f_pres(Attribute::Name)),
1994        );
1995
1996        let acp = AccessControlSearch::from_raw(
1997            "test_acp",
1998            Uuid::new_v4(),
1999            // apply to all accounts.
2000            UUID_TEST_GROUP_1,
2001            // Allow anonymous to read only testperson1
2002            filter_valid!(f_eq(
2003                Attribute::Name,
2004                PartialValue::new_iname("testperson1")
2005            )),
2006            // In that read, admin may only view the "name" attribute, or query on
2007            // the name attribute. Any other query (should be) rejected.
2008            Attribute::Name.as_ref(),
2009        );
2010
2011        // Finally test it!
2012        test_acp_search_reduce(&se_anon_ro, vec![acp], r_set, ex_anon_some);
2013    }
2014
2015    pub static E_TESTPERSON_1_REDUCED: LazyLock<EntryInitNew> =
2016        LazyLock::new(|| entry_init_fn([(Attribute::Name, Value::new_iname("testperson1"))]));
2017
2018    #[test]
2019    fn test_access_enforce_search_attrs() {
2020        // Test that attributes are correctly limited.
2021        // In this case, we test that a user can only see "name" despite the
2022        // class and uuid being present.
2023        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2024        let r_set = vec![Arc::new(ev1)];
2025
2026        let exv1 = E_TESTPERSON_1_REDUCED.clone().into_sealed_committed();
2027        let ex_anon = vec![exv1];
2028
2029        let se_anon = SearchEvent::new_impersonate_entry(
2030            E_TEST_ACCOUNT_1.clone(),
2031            filter_all!(f_eq(
2032                Attribute::Name,
2033                PartialValue::new_iname("testperson1")
2034            )),
2035        );
2036
2037        let acp = AccessControlSearch::from_raw(
2038            "test_acp",
2039            Uuid::new_v4(),
2040            // apply to anonymous only
2041            UUID_TEST_GROUP_1,
2042            // Allow anonymous to read only testperson1
2043            filter_valid!(f_eq(
2044                Attribute::Name,
2045                PartialValue::new_iname("testperson1")
2046            )),
2047            // In that read, admin may only view the "name" attribute, or query on
2048            // the name attribute. Any other query (should be) rejected.
2049            Attribute::Name.as_ref(),
2050        );
2051
2052        // Finally test it!
2053        test_acp_search_reduce(&se_anon, vec![acp], r_set, ex_anon);
2054    }
2055
2056    #[test]
2057    fn test_access_enforce_search_attrs_req() {
2058        sketching::test_init();
2059
2060        // Test that attributes are correctly limited by the request.
2061        // In this case, we test that a user can only see "name" despite the
2062        // class and uuid being present.
2063        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2064
2065        let r_set = vec![Arc::new(ev1)];
2066
2067        let exv1 = E_TESTPERSON_1_REDUCED.clone().into_sealed_committed();
2068        let ex_anon = vec![exv1];
2069
2070        let mut se_anon = SearchEvent::new_impersonate_entry(
2071            E_TEST_ACCOUNT_1.clone(),
2072            filter_all!(f_eq(
2073                Attribute::Name,
2074                PartialValue::new_iname("testperson1")
2075            )),
2076        );
2077        // the requested attrs here.
2078        se_anon.attrs = Some(btreeset![Attribute::Name]);
2079
2080        let acp = AccessControlSearch::from_raw(
2081            "test_acp",
2082            Uuid::new_v4(),
2083            // apply to anonymous only
2084            UUID_TEST_GROUP_1,
2085            // Allow anonymous to read only testperson1
2086            filter_valid!(f_eq(
2087                Attribute::Name,
2088                PartialValue::new_iname("testperson1")
2089            )),
2090            // In that read, admin may only view the "name" attribute, or query on
2091            // the name attribute. Any other query (should be) rejected.
2092            "name uuid",
2093        );
2094
2095        trace!(?acp);
2096
2097        // Finally test it!
2098        test_acp_search_reduce(&se_anon, vec![acp], r_set, ex_anon);
2099    }
2100
2101    macro_rules! test_acp_modify {
2102        (
2103            $me:expr,
2104            $controls:expr,
2105            $entries:expr,
2106            $expect:expr
2107        ) => {{
2108            let ac = AccessControls::default();
2109            let mut acw = ac.write();
2110            acw.update_modify($controls).expect("Failed to update");
2111            let acw = acw;
2112
2113            let res = acw
2114                .modify_allow_operation(&mut $me, $entries)
2115                .expect("op failed");
2116
2117            debug!("result --> {:?}", res);
2118            debug!("expect --> {:?}", $expect);
2119            // should be ok, and same as expect.
2120            assert_eq!($expect, res);
2121        }};
2122        (
2123            $me:expr,
2124            $controls:expr,
2125            $sync_uuid:expr,
2126            $sync_yield_attr:expr,
2127            $entries:expr,
2128            $expect:expr
2129        ) => {{
2130            let ac = AccessControls::default();
2131            let mut acw = ac.write();
2132            acw.update_modify($controls).expect("Failed to update");
2133            let mut sync_agmt = HashMap::new();
2134            let mut set = BTreeSet::new();
2135            set.insert($sync_yield_attr);
2136            sync_agmt.insert($sync_uuid, set);
2137            acw.update_sync_agreements(sync_agmt);
2138            let acw = acw;
2139
2140            let res = acw
2141                .modify_allow_operation(&mut $me, $entries)
2142                .expect("op failed");
2143
2144            debug!("result --> {:?}", res);
2145            debug!("expect --> {:?}", $expect);
2146            // should be ok, and same as expect.
2147            assert_eq!($expect, res);
2148        }};
2149    }
2150
2151    #[test]
2152    fn test_access_enforce_modify() {
2153        sketching::test_init();
2154
2155        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2156        let r_set = vec![Arc::new(ev1)];
2157
2158        // Name present
2159        let me_pres = ModifyEvent::new_impersonate_entry(
2160            E_TEST_ACCOUNT_1.clone(),
2161            filter_all!(f_eq(
2162                Attribute::Name,
2163                PartialValue::new_iname("testperson1")
2164            )),
2165            modlist!([m_pres(Attribute::Name, &Value::new_iname("value"))]),
2166        );
2167        // Name rem
2168        let me_rem = ModifyEvent::new_impersonate_entry(
2169            E_TEST_ACCOUNT_1.clone(),
2170            filter_all!(f_eq(
2171                Attribute::Name,
2172                PartialValue::new_iname("testperson1")
2173            )),
2174            modlist!([m_remove(Attribute::Name, &PartialValue::new_iname("value"))]),
2175        );
2176        // Name purge
2177        let me_purge = ModifyEvent::new_impersonate_entry(
2178            E_TEST_ACCOUNT_1.clone(),
2179            filter_all!(f_eq(
2180                Attribute::Name,
2181                PartialValue::new_iname("testperson1")
2182            )),
2183            modlist!([m_purge(Attribute::Name)]),
2184        );
2185
2186        // Name Set
2187        let me_set = ModifyEvent::new_impersonate_entry(
2188            E_TEST_ACCOUNT_1.clone(),
2189            filter_all!(f_eq(
2190                Attribute::Name,
2191                PartialValue::new_iname("testperson1")
2192            )),
2193            modlist!([Modify::Set(Attribute::Name, ValueSetIname::new("value"))]),
2194        );
2195
2196        // Class account pres
2197        let me_pres_class = ModifyEvent::new_impersonate_entry(
2198            E_TEST_ACCOUNT_1.clone(),
2199            filter_all!(f_eq(
2200                Attribute::Name,
2201                PartialValue::new_iname("testperson1")
2202            )),
2203            modlist!([m_pres(Attribute::Class, &EntryClass::Account.to_value())]),
2204        );
2205        // Class account rem
2206        let me_rem_class = ModifyEvent::new_impersonate_entry(
2207            E_TEST_ACCOUNT_1.clone(),
2208            filter_all!(f_eq(
2209                Attribute::Name,
2210                PartialValue::new_iname("testperson1")
2211            )),
2212            modlist!([m_remove(
2213                Attribute::Class,
2214                &EntryClass::Account.to_partialvalue()
2215            )]),
2216        );
2217        // Class purge
2218        let me_purge_class = ModifyEvent::new_impersonate_entry(
2219            E_TEST_ACCOUNT_1.clone(),
2220            filter_all!(f_eq(
2221                Attribute::Name,
2222                PartialValue::new_iname("testperson1")
2223            )),
2224            modlist!([m_purge(Attribute::Class)]),
2225        );
2226
2227        // Set Class
2228        let me_set_class = ModifyEvent::new_impersonate_entry(
2229            E_TEST_ACCOUNT_1.clone(),
2230            filter_all!(f_eq(
2231                Attribute::Name,
2232                PartialValue::new_iname("testperson1")
2233            )),
2234            modlist!([Modify::Set(
2235                Attribute::Class,
2236                ValueSetIutf8N::from_iter([EntryClass::Account.into(), EntryClass::Object.into(),])
2237                    .unwrap()
2238            )]),
2239        );
2240
2241        // Allow name and class, class is account
2242        let acp_allow = AccessControlModify::from_raw(
2243            "test_modify_allow",
2244            Uuid::new_v4(),
2245            // Apply to admin
2246            UUID_TEST_GROUP_1,
2247            // To modify testperson
2248            filter_valid!(f_eq(
2249                Attribute::Name,
2250                PartialValue::new_iname("testperson1")
2251            )),
2252            // Allow pres name and class
2253            "name class",
2254            // Allow rem name and class
2255            "name class",
2256            // And the class present allowed is account
2257            EntryClass::Account.into(),
2258            // And the class removed allowed is person
2259            "account person",
2260        );
2261        // Allow member, class is group. IE not account
2262        let acp_deny = AccessControlModify::from_raw(
2263            "test_modify_deny",
2264            Uuid::new_v4(),
2265            // Apply to admin
2266            UUID_TEST_GROUP_1,
2267            // To modify testperson
2268            filter_valid!(f_eq(
2269                Attribute::Name,
2270                PartialValue::new_iname("testperson1")
2271            )),
2272            // Allow pres name and class
2273            "member class",
2274            // Allow rem name and class
2275            "member class",
2276            EntryClass::Group.into(),
2277            EntryClass::Group.into(),
2278        );
2279        // Does not have a pres or rem class in attrs
2280        let acp_no_class = AccessControlModify::from_raw(
2281            "test_modify_no_class",
2282            Uuid::new_v4(),
2283            // Apply to admin
2284            UUID_TEST_GROUP_1,
2285            // To modify testperson
2286            filter_valid!(f_eq(
2287                Attribute::Name,
2288                PartialValue::new_iname("testperson1")
2289            )),
2290            // Allow pres name and class
2291            "name class",
2292            // Allow rem name and class
2293            "name class",
2294            // And the class allowed is NOT an account ...
2295            EntryClass::Group.into(),
2296            EntryClass::Group.into(),
2297        );
2298
2299        // Test allowed pres
2300        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r_set, true);
2301        // test allowed rem
2302        test_acp_modify!(&me_rem, vec![acp_allow.clone()], &r_set, true);
2303        // test allowed purge
2304        test_acp_modify!(&me_purge, vec![acp_allow.clone()], &r_set, true);
2305        // test allowed set
2306        test_acp_modify!(&me_set, vec![acp_allow.clone()], &r_set, true);
2307
2308        // Test rejected pres
2309        test_acp_modify!(&me_pres, vec![acp_deny.clone()], &r_set, false);
2310        // Test rejected rem
2311        test_acp_modify!(&me_rem, vec![acp_deny.clone()], &r_set, false);
2312        // Test rejected purge
2313        test_acp_modify!(&me_purge, vec![acp_deny.clone()], &r_set, false);
2314        // Test rejected set
2315        test_acp_modify!(&me_set, vec![acp_deny.clone()], &r_set, false);
2316
2317        // test allowed pres class
2318        test_acp_modify!(&me_pres_class, vec![acp_allow.clone()], &r_set, true);
2319        // test allowed rem class
2320        test_acp_modify!(&me_rem_class, vec![acp_allow.clone()], &r_set, true);
2321        // test reject purge-class even if class present in allowed remattrs
2322        test_acp_modify!(&me_purge_class, vec![acp_allow.clone()], &r_set, false);
2323        // test allowed set class
2324        test_acp_modify!(&me_set_class, vec![acp_allow], &r_set, true);
2325
2326        // Test reject pres class, but class not in classes
2327        test_acp_modify!(&me_pres_class, vec![acp_no_class.clone()], &r_set, false);
2328        // Test reject pres class, class in classes but not in pres attrs
2329        test_acp_modify!(&me_pres_class, vec![acp_deny.clone()], &r_set, false);
2330        // test reject rem class, but class not in classes
2331        test_acp_modify!(&me_rem_class, vec![acp_no_class.clone()], &r_set, false);
2332        // test reject rem class, class in classes but not in pres attrs
2333        test_acp_modify!(&me_rem_class, vec![acp_deny.clone()], &r_set, false);
2334
2335        // Test reject set class, but class not in classes
2336        test_acp_modify!(&me_set_class, vec![acp_no_class], &r_set, false);
2337        // Test reject set class, class in classes but not in pres attrs
2338        test_acp_modify!(&me_set_class, vec![acp_deny], &r_set, false);
2339    }
2340
2341    #[test]
2342    fn test_access_enforce_scope_modify() {
2343        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2344        let r_set = vec![Arc::new(ev1)];
2345
2346        // Name present
2347        let me_pres_ro = ModifyEvent::new_impersonate_identity(
2348            Identity::from_impersonate_entry_readonly(E_TEST_ACCOUNT_1.clone()),
2349            filter_all!(f_eq(
2350                Attribute::Name,
2351                PartialValue::new_iname("testperson1")
2352            )),
2353            modlist!([m_pres(Attribute::Name, &Value::new_iname("value"))]),
2354        );
2355
2356        // Name present
2357        let me_pres_rw = ModifyEvent::new_impersonate_identity(
2358            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
2359            filter_all!(f_eq(
2360                Attribute::Name,
2361                PartialValue::new_iname("testperson1")
2362            )),
2363            modlist!([m_pres(Attribute::Name, &Value::new_iname("value"))]),
2364        );
2365
2366        let acp_allow = AccessControlModify::from_raw(
2367            "test_modify_allow",
2368            Uuid::new_v4(),
2369            // apply to admin only
2370            UUID_TEST_GROUP_1,
2371            // To modify testperson
2372            filter_valid!(f_eq(
2373                Attribute::Name,
2374                PartialValue::new_iname("testperson1")
2375            )),
2376            // Allow pres name and class
2377            "name class",
2378            // Allow rem name and class
2379            "name class",
2380            // And the class allowed is account
2381            EntryClass::Account.into(),
2382            EntryClass::Account.into(),
2383        );
2384
2385        test_acp_modify!(&me_pres_ro, vec![acp_allow.clone()], &r_set, false);
2386
2387        test_acp_modify!(&me_pres_rw, vec![acp_allow], &r_set, true);
2388    }
2389
2390    macro_rules! test_acp_create {
2391        (
2392            $ce:expr,
2393            $controls:expr,
2394            $entries:expr,
2395            $expect:expr
2396        ) => {{
2397            let ac = AccessControls::default();
2398            let mut acw = ac.write();
2399            acw.update_create($controls).expect("Failed to update");
2400            let acw = acw;
2401
2402            let res = acw
2403                .create_allow_operation(&mut $ce, $entries)
2404                .expect("op failed");
2405
2406            debug!("result --> {:?}", res);
2407            debug!("expect --> {:?}", $expect);
2408            // should be ok, and same as expect.
2409            assert_eq!(res, $expect);
2410        }};
2411    }
2412
2413    #[test]
2414    fn test_access_enforce_create() {
2415        sketching::test_init();
2416
2417        let ev1 = entry_init!(
2418            (Attribute::Class, EntryClass::Account.to_value()),
2419            (Attribute::Name, Value::new_iname("testperson1")),
2420            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2421        );
2422        let r1_set = vec![ev1];
2423
2424        let ev2 = entry_init!(
2425            (Attribute::Class, EntryClass::Account.to_value()),
2426            (Attribute::TestNotAllowed, Value::new_iutf8n("notallowed")),
2427            (Attribute::Name, Value::new_iname("testperson1")),
2428            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2429        );
2430
2431        let r2_set = vec![ev2];
2432
2433        let ev3 = entry_init!(
2434            (Attribute::Class, EntryClass::Account.to_value()),
2435            (Attribute::Class, Value::new_iutf8n("notallowed")),
2436            (Attribute::Name, Value::new_iname("testperson1")),
2437            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2438        );
2439        let r3_set = vec![ev3];
2440
2441        let ev4 = entry_init!(
2442            (Attribute::Class, EntryClass::Account.to_value()),
2443            (Attribute::Class, EntryClass::Group.to_value()),
2444            (Attribute::Name, Value::new_iname("testperson1")),
2445            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2446        );
2447        let r4_set = vec![ev4];
2448
2449        // In this case, we can make the create event with an empty entry
2450        // set because we only reference the entries in r_set in the test.
2451        //
2452        // In the server code, the entry set is derived from and checked
2453        // against the create event, so we have some level of trust in it.
2454
2455        let ce_admin = CreateEvent::new_impersonate_identity(
2456            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
2457            vec![],
2458        );
2459
2460        let acp = AccessControlCreate::from_raw(
2461            "test_create",
2462            Uuid::new_v4(),
2463            // Apply to admin
2464            UUID_TEST_GROUP_1,
2465            // To create matching filter testperson
2466            // Can this be empty?
2467            filter_valid!(f_eq(
2468                Attribute::Name,
2469                PartialValue::new_iname("testperson1")
2470            )),
2471            // classes
2472            EntryClass::Account.into(),
2473            // attrs
2474            "class name uuid",
2475        );
2476
2477        let acp2 = AccessControlCreate::from_raw(
2478            "test_create_2",
2479            Uuid::new_v4(),
2480            // Apply to admin
2481            UUID_TEST_GROUP_1,
2482            // To create matching filter testperson
2483            filter_valid!(f_eq(
2484                Attribute::Name,
2485                PartialValue::new_iname("testperson1")
2486            )),
2487            // classes
2488            EntryClass::Group.into(),
2489            // attrs
2490            "class name uuid",
2491        );
2492
2493        // Test allowed to create
2494        test_acp_create!(&ce_admin, vec![acp.clone()], &r1_set, true);
2495        // Test reject create (not allowed attr)
2496        test_acp_create!(&ce_admin, vec![acp.clone()], &r2_set, false);
2497        // Test reject create (not allowed class)
2498        test_acp_create!(&ce_admin, vec![acp.clone()], &r3_set, false);
2499        // Test reject create (hybrid u + g entry w_ u & g create allow)
2500        test_acp_create!(&ce_admin, vec![acp, acp2], &r4_set, false);
2501    }
2502
2503    #[test]
2504    fn test_access_enforce_scope_create() {
2505        let ev1 = entry_init!(
2506            (Attribute::Class, EntryClass::Account.to_value()),
2507            (Attribute::Name, Value::new_iname("testperson1")),
2508            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2509        );
2510        let r1_set = vec![ev1];
2511
2512        let admin = E_TEST_ACCOUNT_1.clone();
2513
2514        let ce_admin_ro = CreateEvent::new_impersonate_identity(
2515            Identity::from_impersonate_entry_readonly(admin.clone()),
2516            vec![],
2517        );
2518
2519        let ce_admin_rw = CreateEvent::new_impersonate_identity(
2520            Identity::from_impersonate_entry_readwrite(admin),
2521            vec![],
2522        );
2523
2524        let acp = AccessControlCreate::from_raw(
2525            "test_create",
2526            Uuid::new_v4(),
2527            // Apply to admin
2528            UUID_TEST_GROUP_1,
2529            // To create matching filter testperson
2530            // Can this be empty?
2531            filter_valid!(f_eq(
2532                Attribute::Name,
2533                PartialValue::new_iname("testperson1")
2534            )),
2535            // classes
2536            EntryClass::Account.into(),
2537            // attrs
2538            "class name uuid",
2539        );
2540
2541        test_acp_create!(&ce_admin_ro, vec![acp.clone()], &r1_set, false);
2542
2543        test_acp_create!(&ce_admin_rw, vec![acp], &r1_set, true);
2544    }
2545
2546    macro_rules! test_acp_delete {
2547        (
2548            $de:expr,
2549            $controls:expr,
2550            $entries:expr,
2551            $expect:expr
2552        ) => {{
2553            let ac = AccessControls::default();
2554            let mut acw = ac.write();
2555            acw.update_delete($controls).expect("Failed to update");
2556            let acw = acw;
2557
2558            let res = acw
2559                .delete_allow_operation($de, $entries)
2560                .expect("op failed");
2561
2562            debug!("result --> {:?}", res);
2563            debug!("expect --> {:?}", $expect);
2564            // should be ok, and same as expect.
2565            assert_eq!(res, $expect);
2566        }};
2567    }
2568
2569    #[test]
2570    fn test_access_enforce_delete() {
2571        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2572        let r_set = vec![Arc::new(ev1)];
2573
2574        let de_admin = DeleteEvent::new_impersonate_entry(
2575            E_TEST_ACCOUNT_1.clone(),
2576            filter_all!(f_eq(
2577                Attribute::Name,
2578                PartialValue::new_iname("testperson1")
2579            )),
2580        );
2581
2582        let de_anon = DeleteEvent::new_impersonate_entry(
2583            E_TEST_ACCOUNT_2.clone(),
2584            filter_all!(f_eq(
2585                Attribute::Name,
2586                PartialValue::new_iname("testperson1")
2587            )),
2588        );
2589
2590        let acp = AccessControlDelete::from_raw(
2591            "test_delete",
2592            Uuid::new_v4(),
2593            // Apply to admin
2594            UUID_TEST_GROUP_1,
2595            // To delete testperson
2596            filter_valid!(f_eq(
2597                Attribute::Name,
2598                PartialValue::new_iname("testperson1")
2599            )),
2600        );
2601
2602        // Test allowed to delete
2603        test_acp_delete!(&de_admin, vec![acp.clone()], &r_set, true);
2604        // Test reject delete
2605        test_acp_delete!(&de_anon, vec![acp], &r_set, false);
2606    }
2607
2608    #[test]
2609    fn test_access_enforce_scope_delete() {
2610        sketching::test_init();
2611
2612        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2613        let r_set = vec![Arc::new(ev1)];
2614
2615        let admin = E_TEST_ACCOUNT_1.clone();
2616
2617        let de_admin_ro = DeleteEvent::new_impersonate_identity(
2618            Identity::from_impersonate_entry_readonly(admin.clone()),
2619            filter_all!(f_eq(
2620                Attribute::Name,
2621                PartialValue::new_iname("testperson1")
2622            )),
2623        );
2624
2625        let de_admin_rw = DeleteEvent::new_impersonate_identity(
2626            Identity::from_impersonate_entry_readwrite(admin),
2627            filter_all!(f_eq(
2628                Attribute::Name,
2629                PartialValue::new_iname("testperson1")
2630            )),
2631        );
2632
2633        let acp = AccessControlDelete::from_raw(
2634            "test_delete",
2635            Uuid::new_v4(),
2636            // Apply to admin
2637            UUID_TEST_GROUP_1,
2638            // To delete testperson
2639            filter_valid!(f_eq(
2640                Attribute::Name,
2641                PartialValue::new_iname("testperson1")
2642            )),
2643        );
2644
2645        test_acp_delete!(&de_admin_ro, vec![acp.clone()], &r_set, false);
2646
2647        test_acp_delete!(&de_admin_rw, vec![acp], &r_set, true);
2648    }
2649
2650    macro_rules! test_acp_effective_permissions {
2651        (
2652            $ident:expr,
2653            $attrs:expr,
2654            $search_controls:expr,
2655            $modify_controls:expr,
2656            $entries:expr,
2657            $expect:expr
2658        ) => {{
2659            let ac = AccessControls::default();
2660            let mut acw = ac.write();
2661            acw.update_search($search_controls)
2662                .expect("Failed to update");
2663            acw.update_modify($modify_controls)
2664                .expect("Failed to update");
2665            let acw = acw;
2666
2667            let res = acw
2668                .effective_permission_check($ident, $attrs, $entries)
2669                .expect("Failed to apply effective_permission_check");
2670
2671            debug!("result --> {:?}", res);
2672            debug!("expect --> {:?}", $expect);
2673            // should be ok, and same as expect.
2674            assert_eq!(res, $expect);
2675        }};
2676    }
2677
2678    #[test]
2679    fn test_access_effective_permission_check_1() {
2680        sketching::test_init();
2681
2682        let admin = Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone());
2683
2684        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2685
2686        let r_set = vec![Arc::new(ev1)];
2687
2688        test_acp_effective_permissions!(
2689            &admin,
2690            None,
2691            vec![AccessControlSearch::from_raw(
2692                "test_acp",
2693                Uuid::new_v4(),
2694                // apply to admin only
2695                UUID_TEST_GROUP_1,
2696                // Allow admin to read only testperson1
2697                filter_valid!(f_eq(
2698                    Attribute::Name,
2699                    PartialValue::new_iname("testperson1")
2700                )),
2701                // They can read "name".
2702                Attribute::Name.as_ref(),
2703            )],
2704            vec![],
2705            &r_set,
2706            vec![AccessEffectivePermission {
2707                ident: UUID_TEST_ACCOUNT_1,
2708                delete: false,
2709                target: uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"),
2710                search: Access::Allow(btreeset![Attribute::Name]),
2711                modify_pres: Access::Allow(BTreeSet::new()),
2712                modify_rem: Access::Allow(BTreeSet::new()),
2713                modify_pres_class: AccessClass::Allow(BTreeSet::new()),
2714                modify_rem_class: AccessClass::Allow(BTreeSet::new()),
2715            }]
2716        )
2717    }
2718
2719    #[test]
2720    fn test_access_effective_permission_check_2() {
2721        sketching::test_init();
2722
2723        let admin = Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone());
2724
2725        let ev1 = E_TESTPERSON_1.clone().into_sealed_committed();
2726
2727        let r_set = vec![Arc::new(ev1)];
2728
2729        test_acp_effective_permissions!(
2730            &admin,
2731            None,
2732            vec![],
2733            vec![AccessControlModify::from_raw(
2734                "test_acp",
2735                Uuid::new_v4(),
2736                // apply to admin only
2737                UUID_TEST_GROUP_1,
2738                // Allow admin to read only testperson1
2739                filter_valid!(f_eq(
2740                    Attribute::Name,
2741                    PartialValue::new_iname("testperson1")
2742                )),
2743                // They can read "name".
2744                Attribute::Name.as_ref(),
2745                Attribute::Name.as_ref(),
2746                EntryClass::Object.into(),
2747                EntryClass::Object.into(),
2748            )],
2749            &r_set,
2750            vec![AccessEffectivePermission {
2751                ident: UUID_TEST_ACCOUNT_1,
2752                delete: false,
2753                target: uuid!("cc8e95b4-c24f-4d68-ba54-8bed76f63930"),
2754                search: Access::Allow(BTreeSet::new()),
2755                modify_pres: Access::Allow(btreeset![Attribute::Name]),
2756                modify_rem: Access::Allow(btreeset![Attribute::Name]),
2757                modify_pres_class: AccessClass::Allow(btreeset![EntryClass::Object.into()]),
2758                modify_rem_class: AccessClass::Allow(btreeset![EntryClass::Object.into()]),
2759            }]
2760        )
2761    }
2762
2763    #[test]
2764    fn test_access_sync_authority_create() {
2765        sketching::test_init();
2766
2767        let ce_admin = CreateEvent::new_impersonate_identity(
2768            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
2769            vec![],
2770        );
2771
2772        // We can create without a sync class.
2773        let ev1 = entry_init!(
2774            (Attribute::Class, EntryClass::Account.to_value()),
2775            (Attribute::Name, Value::new_iname("testperson1")),
2776            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2777        );
2778        let r1_set = vec![ev1];
2779
2780        let ev2 = entry_init!(
2781            (Attribute::Class, EntryClass::Account.to_value()),
2782            (Attribute::Class, EntryClass::SyncObject.to_value()),
2783            (Attribute::Name, Value::new_iname("testperson1")),
2784            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2785        );
2786        let r2_set = vec![ev2];
2787
2788        let acp = AccessControlCreate::from_raw(
2789            "test_create",
2790            Uuid::new_v4(),
2791            // Apply to admin
2792            UUID_TEST_GROUP_1,
2793            // To create matching filter testperson
2794            // Can this be empty?
2795            filter_valid!(f_eq(
2796                Attribute::Name,
2797                PartialValue::new_iname("testperson1")
2798            )),
2799            // classes
2800            "account sync_object",
2801            // attrs
2802            "class name uuid",
2803        );
2804
2805        // Test allowed to create
2806        test_acp_create!(&ce_admin, vec![acp.clone()], &r1_set, true);
2807        // Test Fails due to protected from sync object
2808        test_acp_create!(&ce_admin, vec![acp], &r2_set, false);
2809    }
2810
2811    #[test]
2812    fn test_access_sync_authority_delete() {
2813        sketching::test_init();
2814
2815        let ev1 = entry_init!(
2816            (Attribute::Class, EntryClass::Account.to_value()),
2817            (Attribute::Name, Value::new_iname("testperson1")),
2818            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2819        )
2820        .into_sealed_committed();
2821        let r1_set = vec![Arc::new(ev1)];
2822
2823        let ev2 = entry_init!(
2824            (Attribute::Class, EntryClass::Account.to_value()),
2825            (Attribute::Class, EntryClass::SyncObject.to_value()),
2826            (Attribute::Name, Value::new_iname("testperson1")),
2827            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2828        )
2829        .into_sealed_committed();
2830        let r2_set = vec![Arc::new(ev2)];
2831
2832        let de_admin = DeleteEvent::new_impersonate_entry(
2833            E_TEST_ACCOUNT_1.clone(),
2834            filter_all!(f_eq(
2835                Attribute::Name,
2836                PartialValue::new_iname("testperson1")
2837            )),
2838        );
2839
2840        let acp = AccessControlDelete::from_raw(
2841            "test_delete",
2842            Uuid::new_v4(),
2843            // Apply to admin
2844            UUID_TEST_GROUP_1,
2845            // To delete testperson
2846            filter_valid!(f_eq(
2847                Attribute::Name,
2848                PartialValue::new_iname("testperson1")
2849            )),
2850        );
2851
2852        // Test allowed to delete
2853        test_acp_delete!(&de_admin, vec![acp.clone()], &r1_set, true);
2854        // Test reject delete
2855        test_acp_delete!(&de_admin, vec![acp], &r2_set, false);
2856    }
2857
2858    #[test]
2859    fn test_access_sync_authority_modify() {
2860        sketching::test_init();
2861
2862        let ev1 = entry_init!(
2863            (Attribute::Class, EntryClass::Account.to_value()),
2864            (Attribute::Name, Value::new_iname("testperson1")),
2865            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2866        )
2867        .into_sealed_committed();
2868        let r1_set = vec![Arc::new(ev1)];
2869
2870        let sync_uuid = Uuid::new_v4();
2871        let ev2 = entry_init!(
2872            (Attribute::Class, EntryClass::Account.to_value()),
2873            (Attribute::Class, EntryClass::SyncObject.to_value()),
2874            (Attribute::SyncParentUuid, Value::Refer(sync_uuid)),
2875            (Attribute::Name, Value::new_iname("testperson1")),
2876            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
2877        )
2878        .into_sealed_committed();
2879        let r2_set = vec![Arc::new(ev2)];
2880
2881        // Allow name and class, class is account
2882        let acp_allow = AccessControlModify::from_raw(
2883            "test_modify_allow",
2884            Uuid::new_v4(),
2885            // Apply to admin
2886            UUID_TEST_GROUP_1,
2887            // To modify testperson
2888            filter_valid!(f_eq(
2889                Attribute::Name,
2890                PartialValue::new_iname("testperson1")
2891            )),
2892            // Allow pres user_auth_token_session
2893            &format!("{} {}", Attribute::UserAuthTokenSession, Attribute::Name),
2894            // Allow user_auth_token_session
2895            &format!("{} {}", Attribute::UserAuthTokenSession, Attribute::Name),
2896            // And the class allowed is account, we don't use it though.
2897            EntryClass::Account.into(),
2898            EntryClass::Account.into(),
2899        );
2900
2901        // NOTE! Syntax doesn't matter here, we just need to assert if the attr exists
2902        // and is being modified.
2903        // Name present
2904        let me_pres = ModifyEvent::new_impersonate_entry(
2905            E_TEST_ACCOUNT_1.clone(),
2906            filter_all!(f_eq(
2907                Attribute::Name,
2908                PartialValue::new_iname("testperson1")
2909            )),
2910            modlist!([m_pres(
2911                Attribute::UserAuthTokenSession,
2912                &Value::new_iname("value")
2913            )]),
2914        );
2915        // Name rem
2916        let me_rem = ModifyEvent::new_impersonate_entry(
2917            E_TEST_ACCOUNT_1.clone(),
2918            filter_all!(f_eq(
2919                Attribute::Name,
2920                PartialValue::new_iname("testperson1")
2921            )),
2922            modlist!([m_remove(
2923                Attribute::UserAuthTokenSession,
2924                &PartialValue::new_iname("value")
2925            )]),
2926        );
2927        // Name purge
2928        let me_purge = ModifyEvent::new_impersonate_entry(
2929            E_TEST_ACCOUNT_1.clone(),
2930            filter_all!(f_eq(
2931                Attribute::Name,
2932                PartialValue::new_iname("testperson1")
2933            )),
2934            modlist!([m_purge(Attribute::UserAuthTokenSession)]),
2935        );
2936
2937        // Test allowed pres
2938        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r1_set, true);
2939        // test allowed rem
2940        test_acp_modify!(&me_rem, vec![acp_allow.clone()], &r1_set, true);
2941        // test allowed purge
2942        test_acp_modify!(&me_purge, vec![acp_allow.clone()], &r1_set, true);
2943
2944        // Test allow pres
2945        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r2_set, true);
2946        // Test allow rem
2947        test_acp_modify!(&me_rem, vec![acp_allow.clone()], &r2_set, true);
2948        // Test allow purge
2949        test_acp_modify!(&me_purge, vec![acp_allow.clone()], &r2_set, true);
2950
2951        // But other attrs are blocked.
2952        let me_pres = ModifyEvent::new_impersonate_entry(
2953            E_TEST_ACCOUNT_1.clone(),
2954            filter_all!(f_eq(
2955                Attribute::Name,
2956                PartialValue::new_iname("testperson1")
2957            )),
2958            modlist!([m_pres(Attribute::Name, &Value::new_iname("value"))]),
2959        );
2960        // Name rem
2961        let me_rem = ModifyEvent::new_impersonate_entry(
2962            E_TEST_ACCOUNT_1.clone(),
2963            filter_all!(f_eq(
2964                Attribute::Name,
2965                PartialValue::new_iname("testperson1")
2966            )),
2967            modlist!([m_remove(Attribute::Name, &PartialValue::new_iname("value"))]),
2968        );
2969        // Name purge
2970        let me_purge = ModifyEvent::new_impersonate_entry(
2971            E_TEST_ACCOUNT_1.clone(),
2972            filter_all!(f_eq(
2973                Attribute::Name,
2974                PartialValue::new_iname("testperson1")
2975            )),
2976            modlist!([m_purge(Attribute::Name)]),
2977        );
2978
2979        // Test reject pres
2980        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r2_set, false);
2981        // Test reject rem
2982        test_acp_modify!(&me_rem, vec![acp_allow.clone()], &r2_set, false);
2983        // Test reject purge
2984        test_acp_modify!(&me_purge, vec![acp_allow.clone()], &r2_set, false);
2985
2986        // Test that when an attribute is in the sync_yield state that it can be
2987        // modified by a user.
2988
2989        // Test allow pres
2990        test_acp_modify!(
2991            &me_pres,
2992            vec![acp_allow.clone()],
2993            sync_uuid,
2994            Attribute::Name,
2995            &r2_set,
2996            true
2997        );
2998        // Test allow rem
2999        test_acp_modify!(
3000            &me_rem,
3001            vec![acp_allow.clone()],
3002            sync_uuid,
3003            Attribute::Name,
3004            &r2_set,
3005            true
3006        );
3007        // Test allow purge
3008        test_acp_modify!(
3009            &me_purge,
3010            vec![acp_allow],
3011            sync_uuid,
3012            Attribute::Name,
3013            &r2_set,
3014            true
3015        );
3016    }
3017
3018    #[test]
3019    fn test_access_oauth2_dyn_search() {
3020        sketching::test_init();
3021        // Test that an account that is granted a scope to an oauth2 rs is granted
3022        // the ability to search that rs.
3023        let rs_uuid = Uuid::new_v4();
3024        let ev1 = entry_init!(
3025            (Attribute::Class, EntryClass::Object.to_value()),
3026            (
3027                Attribute::Class,
3028                EntryClass::OAuth2ResourceServer.to_value()
3029            ),
3030            (
3031                Attribute::Class,
3032                EntryClass::OAuth2ResourceServerBasic.to_value()
3033            ),
3034            (Attribute::Uuid, Value::Uuid(rs_uuid)),
3035            (Attribute::Name, Value::new_iname("test_resource_server")),
3036            (
3037                Attribute::DisplayName,
3038                Value::new_utf8s("test_resource_server")
3039            ),
3040            (
3041                Attribute::OAuth2RsOriginLanding,
3042                Value::new_url_s("https://demo.example.com").unwrap()
3043            ),
3044            (
3045                Attribute::OAuth2RsOrigin,
3046                Value::new_url_s("app://hidden").unwrap()
3047            ),
3048            (
3049                Attribute::OAuth2RsScopeMap,
3050                Value::new_oauthscopemap(UUID_TEST_GROUP_1, btreeset!["groups".to_string()])
3051                    .expect("invalid oauthscope")
3052            ),
3053            (
3054                Attribute::OAuth2RsSupScopeMap,
3055                Value::new_oauthscopemap(UUID_TEST_GROUP_1, btreeset!["supplement".to_string()])
3056                    .expect("invalid oauthscope")
3057            ),
3058            (
3059                Attribute::OAuth2AllowInsecureClientDisablePkce,
3060                Value::new_bool(true)
3061            ),
3062            (
3063                Attribute::OAuth2JwtLegacyCryptoEnable,
3064                Value::new_bool(false)
3065            ),
3066            (Attribute::OAuth2PreferShortUsername, Value::new_bool(false))
3067        )
3068        .into_sealed_committed();
3069
3070        let ev1_reduced = entry_init!(
3071            (Attribute::Class, EntryClass::Object.to_value()),
3072            (
3073                Attribute::Class,
3074                EntryClass::OAuth2ResourceServer.to_value()
3075            ),
3076            (
3077                Attribute::Class,
3078                EntryClass::OAuth2ResourceServerBasic.to_value()
3079            ),
3080            (Attribute::Uuid, Value::Uuid(rs_uuid)),
3081            (Attribute::Name, Value::new_iname("test_resource_server")),
3082            (
3083                Attribute::DisplayName,
3084                Value::new_utf8s("test_resource_server")
3085            ),
3086            (
3087                Attribute::OAuth2RsOriginLanding,
3088                Value::new_url_s("https://demo.example.com").unwrap()
3089            )
3090        )
3091        .into_sealed_committed();
3092
3093        let ev2 = entry_init!(
3094            (Attribute::Class, EntryClass::Object.to_value()),
3095            (
3096                Attribute::Class,
3097                EntryClass::OAuth2ResourceServer.to_value()
3098            ),
3099            (
3100                Attribute::Class,
3101                EntryClass::OAuth2ResourceServerBasic.to_value()
3102            ),
3103            (Attribute::Uuid, Value::Uuid(Uuid::new_v4())),
3104            (Attribute::Name, Value::new_iname("second_resource_server")),
3105            (
3106                Attribute::DisplayName,
3107                Value::new_utf8s("second_resource_server")
3108            ),
3109            (
3110                Attribute::OAuth2RsOriginLanding,
3111                Value::new_url_s("https://noaccess.example.com").unwrap()
3112            ),
3113            (
3114                Attribute::OAuth2RsOrigin,
3115                Value::new_url_s("app://hidden").unwrap()
3116            ),
3117            (
3118                Attribute::OAuth2RsScopeMap,
3119                Value::new_oauthscopemap(UUID_SYSTEM_ADMINS, btreeset!["groups".to_string()])
3120                    .expect("invalid oauthscope")
3121            ),
3122            (
3123                Attribute::OAuth2RsSupScopeMap,
3124                Value::new_oauthscopemap(
3125                    // This is NOT the scope map that is access checked!
3126                    UUID_TEST_GROUP_1,
3127                    btreeset!["supplement".to_string()]
3128                )
3129                .expect("invalid oauthscope")
3130            ),
3131            (
3132                Attribute::OAuth2AllowInsecureClientDisablePkce,
3133                Value::new_bool(true)
3134            ),
3135            (
3136                Attribute::OAuth2JwtLegacyCryptoEnable,
3137                Value::new_bool(false)
3138            ),
3139            (Attribute::OAuth2PreferShortUsername, Value::new_bool(false))
3140        )
3141        .into_sealed_committed();
3142
3143        let r_set = vec![Arc::new(ev1.clone()), Arc::new(ev2)];
3144
3145        // Check the authorisation search event, and that it reduces correctly.
3146        let se_a = SearchEvent::new_impersonate_entry(
3147            E_TEST_ACCOUNT_1.clone(),
3148            filter_all!(f_pres(Attribute::Name)),
3149        );
3150        let ex_a = vec![Arc::new(ev1)];
3151        let ex_a_reduced = vec![ev1_reduced];
3152
3153        test_acp_search!(&se_a, vec![], r_set.clone(), ex_a);
3154        test_acp_search_reduce(&se_a, vec![], r_set.clone(), ex_a_reduced);
3155
3156        // Check that anonymous is denied even though it's a member of the group.
3157        let anon: EntryInitNew = BUILTIN_ACCOUNT_ANONYMOUS.clone().into();
3158        let mut anon = anon.into_invalid_new();
3159        anon.set_ava_set(&Attribute::MemberOf, ValueSetReferN::new(UUID_TEST_GROUP_1));
3160
3161        let anon = Arc::new(anon.into_sealed_committed());
3162
3163        let se_anon =
3164            SearchEvent::new_impersonate_entry(anon, filter_all!(f_pres(Attribute::Name)));
3165        let ex_anon = vec![];
3166        test_acp_search!(&se_anon, vec![], r_set.clone(), ex_anon);
3167
3168        // Check the deny case.
3169        let se_b = SearchEvent::new_impersonate_entry(
3170            E_TEST_ACCOUNT_2.clone(),
3171            filter_all!(f_pres(Attribute::Name)),
3172        );
3173        let ex_b = vec![];
3174
3175        test_acp_search!(&se_b, vec![], r_set, ex_b);
3176    }
3177
3178    #[test]
3179    fn test_access_sync_account_dyn_search() {
3180        sketching::test_init();
3181        // Test that an account that has been synchronised from external
3182        // sources is able to read the sync providers credential portal
3183        // url.
3184
3185        let sync_uuid = Uuid::new_v4();
3186        let portal_url = Url::parse("https://localhost/portal").unwrap();
3187
3188        let ev1 = entry_init!(
3189            (Attribute::Class, EntryClass::Object.to_value()),
3190            (Attribute::Class, EntryClass::SyncAccount.to_value()),
3191            (Attribute::Uuid, Value::Uuid(sync_uuid)),
3192            (Attribute::Name, Value::new_iname("test_sync_account")),
3193            (
3194                Attribute::SyncCredentialPortal,
3195                Value::Url(portal_url.clone())
3196            )
3197        )
3198        .into_sealed_committed();
3199
3200        let ev1_reduced = entry_init!(
3201            (Attribute::Class, EntryClass::Object.to_value()),
3202            (Attribute::Class, EntryClass::SyncAccount.to_value()),
3203            (Attribute::Uuid, Value::Uuid(sync_uuid)),
3204            (
3205                Attribute::SyncCredentialPortal,
3206                Value::Url(portal_url.clone())
3207            )
3208        )
3209        .into_sealed_committed();
3210
3211        let ev2 = entry_init!(
3212            (Attribute::Class, EntryClass::Object.to_value()),
3213            (Attribute::Class, EntryClass::SyncAccount.to_value()),
3214            (Attribute::Uuid, Value::Uuid(Uuid::new_v4())),
3215            (Attribute::Name, Value::new_iname("test_sync_account")),
3216            (
3217                Attribute::SyncCredentialPortal,
3218                Value::Url(portal_url.clone())
3219            )
3220        )
3221        .into_sealed_committed();
3222
3223        let sync_test_account: Arc<EntrySealedCommitted> = Arc::new(
3224            entry_init!(
3225                (Attribute::Class, EntryClass::Object.to_value()),
3226                (Attribute::Class, EntryClass::Account.to_value()),
3227                (Attribute::Class, EntryClass::SyncObject.to_value()),
3228                (Attribute::Name, Value::new_iname("test_account_1")),
3229                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3230                (Attribute::MemberOf, Value::ReferN(UUID_TEST_GROUP_1)),
3231                (Attribute::SyncParentUuid, Value::Refer(sync_uuid))
3232            )
3233            .into_sealed_committed(),
3234        );
3235
3236        // Check the authorised search event, and that it reduces correctly.
3237        let r_set = vec![Arc::new(ev1.clone()), Arc::new(ev2)];
3238
3239        let se_a = SearchEvent::new_impersonate_entry(
3240            sync_test_account,
3241            filter_all!(f_pres(Attribute::SyncCredentialPortal)),
3242        );
3243        let ex_a = vec![Arc::new(ev1)];
3244        let ex_a_reduced = vec![ev1_reduced];
3245
3246        test_acp_search!(&se_a, vec![], r_set.clone(), ex_a);
3247        test_acp_search_reduce(&se_a, vec![], r_set.clone(), ex_a_reduced);
3248
3249        // Test a non-synced account aka the deny case
3250        let se_b = SearchEvent::new_impersonate_entry(
3251            E_TEST_ACCOUNT_2.clone(),
3252            filter_all!(f_pres(Attribute::SyncCredentialPortal)),
3253        );
3254        let ex_b = vec![];
3255
3256        test_acp_search!(&se_b, vec![], r_set, ex_b);
3257    }
3258
3259    #[test]
3260    fn test_access_entry_managed_by_search() {
3261        sketching::test_init();
3262
3263        let test_entry = Arc::new(
3264            entry_init!(
3265                (Attribute::Class, EntryClass::Object.to_value()),
3266                (Attribute::Name, Value::new_iname("testperson1")),
3267                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3268                (Attribute::EntryManagedBy, Value::Refer(UUID_TEST_GROUP_1))
3269            )
3270            .into_sealed_committed(),
3271        );
3272
3273        let data_set = vec![test_entry.clone()];
3274
3275        let se_a = SearchEvent::new_impersonate_entry(
3276            E_TEST_ACCOUNT_1.clone(),
3277            filter_all!(f_pres(Attribute::Name)),
3278        );
3279        let expect_a = vec![test_entry];
3280
3281        let se_b = SearchEvent::new_impersonate_entry(
3282            E_TEST_ACCOUNT_2.clone(),
3283            filter_all!(f_pres(Attribute::Name)),
3284        );
3285        let expect_b = vec![];
3286
3287        let acp = AccessControlSearch::from_managed_by(
3288            "test_acp",
3289            Uuid::new_v4(),
3290            // Allow admin to read only testperson1
3291            AccessControlTarget::Scope(filter_valid!(f_eq(
3292                Attribute::Name,
3293                PartialValue::new_iname("testperson1")
3294            ))),
3295            // In that read, admin may only view the "name" attribute, or query on
3296            // the name attribute. Any other query (should be) rejected.
3297            Attribute::Name.as_ref(),
3298        );
3299
3300        // Check where allowed
3301        test_acp_search!(&se_a, vec![acp.clone()], data_set.clone(), expect_a);
3302
3303        // And where not
3304        test_acp_search!(&se_b, vec![acp], data_set, expect_b);
3305    }
3306
3307    #[test]
3308    fn test_access_entry_managed_by_create() {
3309        sketching::test_init();
3310
3311        let test_entry = entry_init!(
3312            (Attribute::Class, EntryClass::Object.to_value()),
3313            (Attribute::Name, Value::new_iname("testperson1")),
3314            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3315            (Attribute::EntryManagedBy, Value::Refer(UUID_TEST_GROUP_1))
3316        );
3317
3318        let data_set = vec![test_entry];
3319
3320        let ce = CreateEvent::new_impersonate_identity(
3321            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
3322            vec![],
3323        );
3324
3325        let acp = AccessControlCreate::from_managed_by(
3326            "test_create",
3327            Uuid::new_v4(),
3328            AccessControlTarget::Scope(filter_valid!(f_eq(
3329                Attribute::Name,
3330                PartialValue::new_iname("testperson1")
3331            ))),
3332            // classes
3333            EntryClass::Account.into(),
3334            // attrs
3335            "class name uuid",
3336        );
3337
3338        // Test reject create (not allowed attr). This is because entry
3339        // managed by is non-sensical with creates!
3340        test_acp_create!(&ce, vec![acp.clone()], &data_set, false);
3341    }
3342
3343    #[test]
3344    fn test_access_entry_managed_by_modify() {
3345        let test_entry = Arc::new(
3346            entry_init!(
3347                (Attribute::Class, EntryClass::Object.to_value()),
3348                (Attribute::Name, Value::new_iname("testperson1")),
3349                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3350                (Attribute::EntryManagedBy, Value::Refer(UUID_TEST_GROUP_1))
3351            )
3352            .into_sealed_committed(),
3353        );
3354
3355        let data_set = vec![test_entry];
3356
3357        // Name present
3358        let me_pres = ModifyEvent::new_impersonate_entry(
3359            E_TEST_ACCOUNT_1.clone(),
3360            filter_all!(f_eq(
3361                Attribute::Name,
3362                PartialValue::new_iname("testperson1")
3363            )),
3364            modlist!([m_pres(Attribute::Name, &Value::new_iname("value"))]),
3365        );
3366        // Name rem
3367        let me_rem = ModifyEvent::new_impersonate_entry(
3368            E_TEST_ACCOUNT_1.clone(),
3369            filter_all!(f_eq(
3370                Attribute::Name,
3371                PartialValue::new_iname("testperson1")
3372            )),
3373            modlist!([m_remove(Attribute::Name, &PartialValue::new_iname("value"))]),
3374        );
3375        // Name purge
3376        let me_purge = ModifyEvent::new_impersonate_entry(
3377            E_TEST_ACCOUNT_1.clone(),
3378            filter_all!(f_eq(
3379                Attribute::Name,
3380                PartialValue::new_iname("testperson1")
3381            )),
3382            modlist!([m_purge(Attribute::Name)]),
3383        );
3384
3385        let acp_allow = AccessControlModify::from_managed_by(
3386            "test_modify_allow",
3387            Uuid::new_v4(),
3388            // To modify testperson
3389            AccessControlTarget::Scope(filter_valid!(f_eq(
3390                Attribute::Name,
3391                PartialValue::new_iname("testperson1")
3392            ))),
3393            // Allow pres name and class
3394            "name class",
3395            // Allow rem name and class
3396            "name class",
3397            // And the class allowed is account
3398            EntryClass::Account.into(),
3399            EntryClass::Account.into(),
3400        );
3401
3402        // Test allowed pres
3403        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &data_set, true);
3404        // test allowed rem
3405        test_acp_modify!(&me_rem, vec![acp_allow.clone()], &data_set, true);
3406        // test allowed purge
3407        test_acp_modify!(&me_purge, vec![acp_allow.clone()], &data_set, true);
3408    }
3409
3410    #[test]
3411    fn test_access_entry_managed_by_delete() {
3412        let test_entry = Arc::new(
3413            entry_init!(
3414                (Attribute::Class, EntryClass::Object.to_value()),
3415                (Attribute::Name, Value::new_iname("testperson1")),
3416                (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3417                (Attribute::EntryManagedBy, Value::Refer(UUID_TEST_GROUP_1))
3418            )
3419            .into_sealed_committed(),
3420        );
3421
3422        let data_set = vec![test_entry];
3423
3424        let de_a = DeleteEvent::new_impersonate_entry(
3425            E_TEST_ACCOUNT_1.clone(),
3426            filter_all!(f_eq(
3427                Attribute::Name,
3428                PartialValue::new_iname("testperson1")
3429            )),
3430        );
3431
3432        let de_b = DeleteEvent::new_impersonate_entry(
3433            E_TEST_ACCOUNT_2.clone(),
3434            filter_all!(f_eq(
3435                Attribute::Name,
3436                PartialValue::new_iname("testperson1")
3437            )),
3438        );
3439
3440        let acp = AccessControlDelete::from_managed_by(
3441            "test_delete",
3442            Uuid::new_v4(),
3443            // To delete testperson
3444            AccessControlTarget::Scope(filter_valid!(f_eq(
3445                Attribute::Name,
3446                PartialValue::new_iname("testperson1")
3447            ))),
3448        );
3449
3450        // Test allowed to delete
3451        test_acp_delete!(&de_a, vec![acp.clone()], &data_set, true);
3452        // Test reject delete
3453        test_acp_delete!(&de_b, vec![acp], &data_set, false);
3454    }
3455
3456    #[test]
3457    fn test_access_delete_protect_system_ranges() {
3458        let ev1: EntryInitNew = BUILTIN_ACCOUNT_ANONYMOUS.clone().into();
3459        let ev1 = ev1.into_sealed_committed();
3460        let r_set = vec![Arc::new(ev1)];
3461
3462        let de_account = DeleteEvent::new_impersonate_entry(
3463            E_TEST_ACCOUNT_1.clone(),
3464            filter_all!(f_eq(
3465                Attribute::Name,
3466                PartialValue::new_iname("testperson1")
3467            )),
3468        );
3469
3470        let acp = AccessControlDelete::from_raw(
3471            "test_delete",
3472            Uuid::new_v4(),
3473            UUID_TEST_GROUP_1,
3474            // To delete testperson
3475            filter_valid!(f_eq(Attribute::Name, PartialValue::new_iname("anonymous"))),
3476        );
3477
3478        // Test reject delete, can not delete due to system protection
3479        test_acp_delete!(&de_account, vec![acp], &r_set, false);
3480    }
3481
3482    #[test]
3483    fn test_access_sync_memberof_implies_directmemberof() {
3484        sketching::test_init();
3485
3486        let ev1 = entry_init!(
3487            (Attribute::Class, EntryClass::Object.to_value()),
3488            (Attribute::Name, Value::new_iname("test_account_1")),
3489            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1)),
3490            (Attribute::MemberOf, Value::ReferN(UUID_TEST_GROUP_1)),
3491            (Attribute::DirectMemberOf, Value::Refer(UUID_TEST_GROUP_1))
3492        )
3493        .into_sealed_committed();
3494        let r_set = vec![Arc::new(ev1)];
3495
3496        let exv1 = entry_init!(
3497            (Attribute::Name, Value::new_iname("test_account_1")),
3498            (Attribute::MemberOf, Value::ReferN(UUID_TEST_GROUP_1)),
3499            (Attribute::DirectMemberOf, Value::Refer(UUID_TEST_GROUP_1))
3500        )
3501        .into_sealed_committed();
3502
3503        let ex_anon_some = vec![exv1];
3504
3505        let se_anon_ro = SearchEvent::new_impersonate_identity(
3506            Identity::from_impersonate_entry_readonly(E_TEST_ACCOUNT_1.clone()),
3507            filter_all!(f_pres(Attribute::Name)),
3508        );
3509
3510        let acp = AccessControlSearch::from_raw(
3511            "test_acp",
3512            Uuid::new_v4(),
3513            // apply to all accounts.
3514            UUID_TEST_GROUP_1,
3515            // Allow anonymous to read only testperson1
3516            filter_valid!(f_eq(
3517                Attribute::Uuid,
3518                PartialValue::Uuid(UUID_TEST_ACCOUNT_1)
3519            )),
3520            // May query on name, and see memberof. MemberOf implies direct
3521            // memberof.
3522            format!("{} {}", Attribute::Name, Attribute::MemberOf).as_str(),
3523        );
3524
3525        // Finally test it!
3526        test_acp_search_reduce(&se_anon_ro, vec![acp], r_set, ex_anon_some);
3527    }
3528
3529    #[test]
3530    fn test_access_protected_deny_create() {
3531        sketching::test_init();
3532
3533        let ev1 = entry_init!(
3534            (Attribute::Class, EntryClass::Account.to_value()),
3535            (Attribute::Name, Value::new_iname("testperson1")),
3536            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3537        );
3538        let r1_set = vec![ev1];
3539
3540        let ev2 = entry_init!(
3541            (Attribute::Class, EntryClass::Account.to_value()),
3542            (Attribute::Class, EntryClass::System.to_value()),
3543            (Attribute::Name, Value::new_iname("testperson1")),
3544            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3545        );
3546
3547        let r2_set = vec![ev2];
3548
3549        let ce_admin = CreateEvent::new_impersonate_identity(
3550            Identity::from_impersonate_entry_readwrite(E_TEST_ACCOUNT_1.clone()),
3551            vec![],
3552        );
3553
3554        let acp = AccessControlCreate::from_raw(
3555            "test_create",
3556            Uuid::new_v4(),
3557            // Apply to admin
3558            UUID_TEST_GROUP_1,
3559            // To create matching filter testperson
3560            // Can this be empty?
3561            filter_valid!(f_eq(
3562                Attribute::Name,
3563                PartialValue::new_iname("testperson1")
3564            )),
3565            // classes
3566            EntryClass::Account.into(),
3567            // attrs
3568            "class name uuid",
3569        );
3570
3571        // Test allowed to create
3572        test_acp_create!(&ce_admin, vec![acp.clone()], &r1_set, true);
3573        // Test reject create (not allowed attr)
3574        test_acp_create!(&ce_admin, vec![acp.clone()], &r2_set, false);
3575    }
3576
3577    #[test]
3578    fn test_access_protected_deny_delete() {
3579        sketching::test_init();
3580
3581        let ev1 = entry_init!(
3582            (Attribute::Class, EntryClass::Account.to_value()),
3583            (Attribute::Name, Value::new_iname("testperson1")),
3584            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3585        )
3586        .into_sealed_committed();
3587        let r1_set = vec![Arc::new(ev1)];
3588
3589        let ev2 = entry_init!(
3590            (Attribute::Class, EntryClass::Account.to_value()),
3591            (Attribute::Class, EntryClass::System.to_value()),
3592            (Attribute::Name, Value::new_iname("testperson1")),
3593            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3594        )
3595        .into_sealed_committed();
3596
3597        let r2_set = vec![Arc::new(ev2)];
3598
3599        let de = DeleteEvent::new_impersonate_entry(
3600            E_TEST_ACCOUNT_1.clone(),
3601            filter_all!(f_eq(
3602                Attribute::Name,
3603                PartialValue::new_iname("testperson1")
3604            )),
3605        );
3606
3607        let acp = AccessControlDelete::from_raw(
3608            "test_delete",
3609            Uuid::new_v4(),
3610            // Apply to admin
3611            UUID_TEST_GROUP_1,
3612            // To delete testperson
3613            filter_valid!(f_eq(
3614                Attribute::Name,
3615                PartialValue::new_iname("testperson1")
3616            )),
3617        );
3618
3619        // Test allowed to delete
3620        test_acp_delete!(&de, vec![acp.clone()], &r1_set, true);
3621        // Test not allowed to delete
3622        test_acp_delete!(&de, vec![acp.clone()], &r2_set, false);
3623    }
3624
3625    #[test]
3626    fn test_access_protected_deny_modify() {
3627        sketching::test_init();
3628
3629        let ev1 = entry_init!(
3630            (Attribute::Class, EntryClass::Account.to_value()),
3631            (Attribute::Name, Value::new_iname("testperson1")),
3632            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3633        )
3634        .into_sealed_committed();
3635        let r1_set = vec![Arc::new(ev1)];
3636
3637        let ev2 = entry_init!(
3638            (Attribute::Class, EntryClass::Account.to_value()),
3639            (Attribute::Class, EntryClass::System.to_value()),
3640            (Attribute::Name, Value::new_iname("testperson1")),
3641            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3642        )
3643        .into_sealed_committed();
3644
3645        let r2_set = vec![Arc::new(ev2)];
3646
3647        // Allow name and class, class is account
3648        let acp_allow = AccessControlModify::from_raw(
3649            "test_modify_allow",
3650            Uuid::new_v4(),
3651            // Apply to admin
3652            UUID_TEST_GROUP_1,
3653            // To modify testperson
3654            filter_valid!(f_eq(
3655                Attribute::Name,
3656                PartialValue::new_iname("testperson1")
3657            )),
3658            // Allow pres disp name and class
3659            "displayname class",
3660            // Allow rem disp name and class
3661            "displayname class",
3662            // And the classes allowed to add/rem are as such
3663            "system recycled",
3664            "system recycled",
3665        );
3666
3667        let me_pres = ModifyEvent::new_impersonate_entry(
3668            E_TEST_ACCOUNT_1.clone(),
3669            filter_all!(f_eq(
3670                Attribute::Name,
3671                PartialValue::new_iname("testperson1")
3672            )),
3673            modlist!([m_pres(Attribute::DisplayName, &Value::new_utf8s("value"))]),
3674        );
3675
3676        // Test allowed pres
3677        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r1_set, true);
3678
3679        // Test not allowed pres (due to system class)
3680        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r2_set, false);
3681
3682        // Test that we can not remove class::system
3683        let me_rem_sys = ModifyEvent::new_impersonate_entry(
3684            E_TEST_ACCOUNT_1.clone(),
3685            filter_all!(f_eq(
3686                Attribute::Class,
3687                PartialValue::new_iname("testperson1")
3688            )),
3689            modlist!([m_remove(
3690                Attribute::Class,
3691                &EntryClass::System.to_partialvalue()
3692            )]),
3693        );
3694
3695        test_acp_modify!(&me_rem_sys, vec![acp_allow.clone()], &r2_set, false);
3696
3697        // Ensure that we can't add recycled.
3698        let me_pres = ModifyEvent::new_impersonate_entry(
3699            E_TEST_ACCOUNT_1.clone(),
3700            filter_all!(f_eq(
3701                Attribute::Name,
3702                PartialValue::new_iname("testperson1")
3703            )),
3704            modlist!([m_pres(Attribute::Class, &EntryClass::Recycled.to_value())]),
3705        );
3706
3707        test_acp_modify!(&me_pres, vec![acp_allow.clone()], &r1_set, false);
3708    }
3709
3710    #[test]
3711    fn test_access_modify_set_bypass() {
3712        sketching::test_init();
3713
3714        let ev1 = entry_init!(
3715            (Attribute::Class, EntryClass::Account.to_value()),
3716            (Attribute::Name, Value::new_iname("testperson1")),
3717            (Attribute::Uuid, Value::Uuid(UUID_TEST_ACCOUNT_1))
3718        )
3719        .into_sealed_committed();
3720        let r1_set = vec![Arc::new(ev1)];
3721
3722        let me_pres = ModifyEvent::new_impersonate_entry(
3723            E_TEST_ACCOUNT_1.clone(),
3724            filter_all!(f_eq(
3725                Attribute::Name,
3726                PartialValue::new_iname("testperson1")
3727            )),
3728            modlist!([Modify::Set(
3729                Attribute::DisplayName,
3730                ValueSetUtf8::new("value".to_string())
3731            )]),
3732        );
3733
3734        // Notice that there are no allowing access controls, and that the result must be a denial.
3735        test_acp_modify!(&me_pres, vec![], &r1_set, false);
3736
3737        let me_empty = ModifyEvent::new_impersonate_entry(
3738            E_TEST_ACCOUNT_1.clone(),
3739            filter_all!(f_eq(
3740                Attribute::Name,
3741                PartialValue::new_iname("testperson1")
3742            )),
3743            modlist!([]),
3744        );
3745
3746        // If there is no request changes, deny.
3747        test_acp_modify!(&me_empty, vec![], &r1_set, false);
3748    }
3749}