Skip to main content

coqui_access_acl/
check.rs

1//! Checking a request against one ACL.
2
3use alloc::vec::Vec;
4use core::fmt;
5
6use coqui_access::{Person, Subject};
7
8use crate::condition::{Conditions, Truth};
9use crate::entry::{Acl, Effect, Entry, ItemAcl, Mode};
10use crate::error::AclError;
11use crate::options::Options;
12use crate::principal::Principal;
13use crate::rights::{Rights, RightsSchema};
14
15/// Everything a check needs besides the ACL and the rights wanted: the schema, who asks,
16/// the item's owner, the consumer's conditions and the options.
17#[derive(Clone)]
18pub struct Context<'a> {
19    pub(crate) schema: &'a RightsSchema,
20    pub(crate) person: Option<&'a Person>,
21    pub(crate) owner: Option<&'a Subject>,
22    pub(crate) owner_group: Option<&'a Subject>,
23    pub(crate) owner_rights: Rights,
24    pub(crate) conditions: Option<&'a dyn Conditions>,
25    pub(crate) item: &'a str,
26    pub(crate) options: Options,
27}
28
29impl fmt::Debug for Context<'_> {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        formatter
32            .debug_struct("Context")
33            .field("signed_in", &self.person.is_some())
34            .field("owner", &self.owner)
35            .field("owner_group", &self.owner_group)
36            .field("owner_rights", &self.owner_rights)
37            .field("conditions", &self.conditions.is_some())
38            .field("options", &self.options)
39            .finish_non_exhaustive()
40    }
41}
42
43impl<'a> Context<'a> {
44    /// A check by nobody signed in, of an item with no owner, with default options.
45    pub fn new(schema: &'a RightsSchema) -> Self {
46        Self {
47            schema,
48            person: None,
49            owner: None,
50            owner_group: None,
51            owner_rights: Rights::new(),
52            conditions: None,
53            item: "",
54            options: Options::default(),
55        }
56    }
57
58    /// Who asks.
59    #[must_use]
60    pub fn person(mut self, person: &'a Person) -> Self {
61        self.person = Some(person);
62        self
63    }
64
65    /// The item's owner. [`ItemAcl::check`] sets it from the item.
66    #[must_use]
67    pub fn owner(mut self, owner: Option<&'a Subject>) -> Self {
68        self.owner = owner;
69        self
70    }
71
72    /// The item's owning group. [`ItemAcl::check`] sets it from the item.
73    #[must_use]
74    pub fn owner_group(mut self, group: Option<&'a Subject>) -> Self {
75        self.owner_group = group;
76        self
77    }
78
79    /// Rights the owner holds whatever the entries say, unless an entry names `Owner`
80    /// (Windows grants READ_CONTROL and WRITE_DAC, dropped by an OWNER RIGHTS entry).
81    /// Default none.
82    #[must_use]
83    pub fn owner_rights(mut self, rights: Rights) -> Self {
84        self.owner_rights = rights;
85        self
86    }
87
88    /// The consumer's conditions; without them every condition is unknown.
89    #[must_use]
90    pub fn conditions(mut self, conditions: &'a dyn Conditions) -> Self {
91        self.conditions = Some(conditions);
92        self
93    }
94
95    /// The item checked, as conditions are told it.
96    #[must_use]
97    pub fn item(mut self, item: &'a str) -> Self {
98        self.item = item;
99        self
100    }
101
102    /// The options.
103    #[must_use]
104    pub fn options(mut self, options: Options) -> Self {
105        self.options = options;
106        self
107    }
108
109    fn truth(&self, condition: &str) -> Truth {
110        match (self.conditions, self.person) {
111            (Some(conditions), Some(person)) => conditions.holds(condition, self.item, person),
112            _ => Truth::Unknown,
113        }
114    }
115
116    fn is(&self, principal: &Principal) -> bool {
117        principal.matches(self.person, self.owner, self.owner_group)
118    }
119
120    /// Whether `entry` applies to this request at all: its principal matches and its
121    /// condition lets it (an allow needs `True`, a deny anything but `False`).
122    pub(crate) fn applies(&self, entry: &Entry) -> bool {
123        self.is(&entry.principal)
124            && entry.condition.as_deref().is_none_or(|condition| {
125                match (entry.effect, self.truth(condition)) {
126                    (_, Truth::True) => true,
127                    (_, Truth::False) => false,
128                    (Effect::Allow, Truth::Unknown) => false,
129                    (Effect::Deny, Truth::Unknown) => true,
130                }
131            })
132    }
133
134    /// The owner's standing rights, unless an entry names the owner.
135    pub(crate) fn owner_grant(&self, acl: &Acl) -> Rights {
136        let named = acl
137            .entries
138            .iter()
139            .any(|entry| entry.principal == Principal::Owner);
140        if !named && self.is(&Principal::Owner) {
141            self.owner_rights.clone()
142        } else {
143            Rights::new()
144        }
145    }
146}
147
148/// What a check came to.
149#[derive(Debug, Clone, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct Decision {
152    /// Whether every wanted right is granted.
153    pub allowed: bool,
154    /// The rights asked for.
155    pub wanted: Rights,
156    /// The rights the ACL grants this requester, whether asked for or not.
157    pub granted: Rights,
158    /// The rights an entry refused this requester.
159    pub denied: Rights,
160    /// The entry that decided, for an audit record: the deny that refused, the allow that
161    /// completed the grant, or the cancelling entry; `None` when no entry decided.
162    pub deciding: Option<usize>,
163    /// Whether a cancelling name refused everything.
164    pub cancelled: bool,
165}
166
167impl Decision {
168    pub(crate) fn nothing(wanted: &Rights) -> Self {
169        Self::from_sets(wanted, Rights::new(), Rights::new(), None)
170    }
171
172    pub(crate) fn from_sets(
173        wanted: &Rights,
174        granted: Rights,
175        denied: Rights,
176        deciding: Option<usize>,
177    ) -> Self {
178        Self {
179            allowed: wanted.is_subset(&granted),
180            wanted: wanted.clone(),
181            granted,
182            denied,
183            deciding,
184            cancelled: false,
185        }
186    }
187
188    pub(crate) fn cancelled(schema: &RightsSchema, wanted: &Rights, entry: usize) -> Self {
189        Self {
190            allowed: false,
191            wanted: wanted.clone(),
192            granted: Rights::new(),
193            denied: schema.all(),
194            deciding: Some(entry),
195            cancelled: true,
196        }
197    }
198
199    /// Both decisions at once, for a token with an ACL of its own or a read-only token
200    /// (Proxmox privilege separation, NetBox `write_enabled`): granted only what both
201    /// grant, denied what either denies, allowed only if both allow. `deciding` is the
202    /// first refusing side's, else this one's.
203    #[must_use]
204    pub fn intersect(&self, other: &Decision) -> Decision {
205        let deciding = if !self.allowed || other.allowed {
206            self.deciding
207        } else {
208            other.deciding
209        };
210        Decision {
211            allowed: self.allowed && other.allowed,
212            wanted: &self.wanted | &other.wanted,
213            granted: &self.granted & &other.granted,
214            denied: &self.denied | &other.denied,
215            deciding,
216            cancelled: self.cancelled || other.cancelled,
217        }
218    }
219
220    /// This decision, with `other` deciding the rights this one left unset (neither
221    /// granted nor denied): a second parent such as a Proxmox pool. A cancelled side wins
222    /// (this one first).
223    #[must_use]
224    pub fn union_where_unset(&self, other: &Decision) -> Decision {
225        if self.cancelled {
226            return self.clone();
227        }
228        if other.cancelled {
229            return other.clone();
230        }
231        let set = &self.granted | &self.denied;
232        let granted = &self.granted | &(&other.granted - &set);
233        let denied = &self.denied | &(&other.denied - &set);
234        let wanted = &self.wanted | &other.wanted;
235        let deciding = if wanted.is_subset(&set) {
236            self.deciding
237        } else {
238            other.deciding.or(self.deciding)
239        };
240        Decision::from_sets(&wanted, granted, denied, deciding)
241    }
242}
243
244/// One entry compiled against the schema.
245pub(crate) struct Compiled {
246    pub(crate) rights: Rights,
247    pub(crate) cancels: bool,
248}
249
250impl Acl {
251    /// Checks this ACL against `schema` and `limits` without evaluating it.
252    ///
253    /// # Errors
254    ///
255    /// As [`check`](Acl::check).
256    pub fn validate(&self, schema: &RightsSchema, options: &Options) -> Result<(), AclError> {
257        self.compile(schema, options).map(drop)
258    }
259
260    pub(crate) fn compile(
261        &self,
262        schema: &RightsSchema,
263        options: &Options,
264    ) -> Result<Vec<Compiled>, AclError> {
265        if options
266            .limits
267            .entries
268            .is_some_and(|max| self.entries.len() > max)
269        {
270            return Err(AclError::TooManyEntries);
271        }
272        let mut masks = [0u8; 2];
273        self.entries
274            .iter()
275            .enumerate()
276            .map(|(at, entry)| {
277                let denies = !matches!(self.mode, Mode::Ordered | Mode::DenyOverrides);
278                if denies && entry.effect == Effect::Deny {
279                    return Err(AclError::DenyNotAllowed { entry: at });
280                }
281                let posix = self.mode == Mode::Posix;
282                let refused = match entry.principal {
283                    // One mask in force and one passed to children (a POSIX default ACL).
284                    Principal::Mask => {
285                        let slot = usize::from(entry.inherit.inherit_only);
286                        masks[slot] += 1;
287                        !posix || masks[slot] > 1
288                    }
289                    Principal::Authenticated => posix,
290                    _ => false,
291                };
292                if refused {
293                    return Err(AclError::PrincipalNotAllowed { entry: at });
294                }
295                let (rights, cancels) =
296                    schema
297                        .compile(&entry.rights)
298                        .map_err(|name| AclError::UnknownRight {
299                            entry: Some(at),
300                            at: name,
301                        })?;
302                Ok(Compiled { rights, cancels })
303            })
304            .collect()
305    }
306
307    /// Whether the requester in `context` holds every right in `wanted` on an item with this
308    /// ACL. Entries marked `inherit_only` do not apply here. An applicable entry naming a
309    /// cancelling name refuses everything, in every mode.
310    ///
311    /// An empty `wanted` is allowed: nothing was asked for.
312    ///
313    /// # Errors
314    ///
315    /// The ACL is not usable with this schema and these options: more entries than
316    /// [`Limits::entries`](crate::Limits::entries), a name the schema lacks, a deny where
317    /// the mode has none, a principal the mode does not take.
318    pub fn check(&self, context: &Context<'_>, wanted: &Rights) -> Result<Decision, AclError> {
319        let compiled = self.compile(context.schema, &context.options)?;
320        let applicable: Vec<(usize, &Entry, &Compiled)> = self
321            .entries
322            .iter()
323            .zip(&compiled)
324            .enumerate()
325            .filter(|(_, (entry, _))| !entry.inherit.inherit_only && context.applies(entry))
326            .map(|(at, (entry, compiled))| (at, entry, compiled))
327            .collect();
328        if self.mode != Mode::MostSpecific
329            && let Some((at, ..)) = applicable.iter().find(|(_, _, compiled)| compiled.cancels)
330        {
331            return Ok(Decision::cancelled(context.schema, wanted, *at));
332        }
333        let owner = context.owner_grant(self);
334        Ok(match self.mode {
335            Mode::Ordered => ordered(&applicable, owner, wanted),
336            Mode::Posix => {
337                let mask = self
338                    .entries
339                    .iter()
340                    .zip(&compiled)
341                    .find(|(entry, _)| {
342                        entry.principal == Principal::Mask && !entry.inherit.inherit_only
343                    })
344                    .map(|(_, compiled)| &compiled.rights);
345                posix(&applicable, mask, context, owner, wanted)
346            }
347            Mode::MostSpecific => match level(&applicable) {
348                Some(Level {
349                    cancel: Some(at), ..
350                }) => Decision::cancelled(context.schema, wanted, at),
351                Some(level) => Decision::from_sets(
352                    wanted,
353                    &level.rights | &owner,
354                    Rights::new(),
355                    level.deciding,
356                ),
357                None => Decision::from_sets(wanted, owner, Rights::new(), None),
358            },
359            Mode::DenyOverrides | Mode::Additive => deny_overrides(&applicable, owner, wanted),
360        })
361    }
362}
363
364impl ItemAcl {
365    /// [`Acl::check`] with the context's owner and owning group taken from this item.
366    ///
367    /// # Errors
368    ///
369    /// As [`Acl::check`].
370    pub fn check(&self, context: &Context<'_>, wanted: &Rights) -> Result<Decision, AclError> {
371        self.acl.check(&context.for_item(self), wanted)
372    }
373}
374
375type Applicable<'a> = [(usize, &'a Entry, &'a Compiled)];
376
377/// Each right decided by the first applicable entry naming it.
378fn ordered(applicable: &Applicable<'_>, owner: Rights, wanted: &Rights) -> Decision {
379    let mut granted = owner;
380    let mut denied = Rights::new();
381    let mut deciding = None;
382    for (at, entry, compiled) in applicable {
383        let fresh = &compiled.rights - &(&granted | &denied);
384        match entry.effect {
385            Effect::Allow => granted |= &fresh,
386            Effect::Deny => denied |= &fresh,
387        }
388        if deciding.is_none() && !fresh.is_disjoint(wanted) {
389            let refused = entry.effect == Effect::Deny;
390            if refused || wanted.is_subset(&granted) {
391                deciding = Some(*at);
392            }
393        }
394    }
395    Decision::from_sets(wanted, granted, denied, deciding)
396}
397
398/// Any applicable deny refuses its rights; the allows are unioned. The owner's standing
399/// rights are not refused by a deny.
400fn deny_overrides(applicable: &Applicable<'_>, owner: Rights, wanted: &Rights) -> Decision {
401    let mut denied = Rights::new();
402    for (_, entry, compiled) in applicable {
403        if entry.effect == Effect::Deny {
404            denied |= &compiled.rights;
405        }
406    }
407    let first_deny = applicable.iter().find(|(_, entry, compiled)| {
408        entry.effect == Effect::Deny && !compiled.rights.is_disjoint(wanted)
409    });
410    let mut granted = owner.clone();
411    let mut deciding = first_deny.map(|(at, ..)| *at);
412    for (at, entry, compiled) in applicable {
413        if entry.effect == Effect::Allow {
414            granted |= &(&compiled.rights - &denied);
415            if deciding.is_none() && wanted.is_subset(&granted) && !wanted.is_subset(&owner) {
416                deciding = Some(*at);
417            }
418        }
419    }
420    Decision::from_sets(wanted, granted, &denied - &owner, deciding)
421}
422
423/// The requester's class decides: owner, named user, groups (one entry must hold every
424/// wanted right, capped by the mask), everyone. The mask applies whoever asks, so it is
425/// found among all the entries, not the applicable ones.
426fn posix(
427    applicable: &Applicable<'_>,
428    mask: Option<&Rights>,
429    context: &Context<'_>,
430    owner: Rights,
431    wanted: &Rights,
432) -> Decision {
433    let capped = |rights: &Rights| match mask {
434        Some(mask) => rights & mask,
435        None => rights.clone(),
436    };
437    let of = |want: fn(&Principal) -> bool| {
438        applicable
439            .iter()
440            .filter(move |(_, entry, _)| want(&entry.principal))
441    };
442    if context.is(&Principal::Owner) {
443        let entry = of(|principal| *principal == Principal::Owner).next();
444        let rights = entry.map_or_else(Rights::new, |(_, _, compiled)| compiled.rights.clone());
445        return Decision::from_sets(wanted, &rights | &owner, Rights::new(), entry.map(|e| e.0));
446    }
447    let named_user = |principal: &Principal| {
448        matches!(
449            principal,
450            Principal::Subject(Subject::Account(_) | Subject::Person(_))
451        )
452    };
453    if let Some((at, _, compiled)) = of(named_user).next() {
454        return Decision::from_sets(wanted, capped(&compiled.rights), Rights::new(), Some(*at));
455    }
456    let group = |principal: &Principal| {
457        matches!(
458            principal,
459            Principal::OwnerGroup | Principal::Subject(Subject::Group(_))
460        )
461    };
462    let groups: Vec<_> = of(group).collect();
463    if !groups.is_empty() {
464        let granted = groups.iter().fold(Rights::new(), |all, (_, _, compiled)| {
465            &all | &capped(&compiled.rights)
466        });
467        let holding = groups
468            .iter()
469            .find(|(_, _, compiled)| wanted.is_subset(&capped(&compiled.rights)));
470        let mut decision = Decision::from_sets(
471            wanted,
472            granted,
473            Rights::new(),
474            holding.or(groups.first()).map(|(at, ..)| *at),
475        );
476        decision.allowed = holding.is_some();
477        return decision;
478    }
479    match of(|principal| *principal == Principal::Everyone).next() {
480        Some((at, _, compiled)) => {
481            Decision::from_sets(wanted, compiled.rights.clone(), Rights::new(), Some(*at))
482        }
483        None => Decision::nothing(wanted),
484    }
485}
486
487/// What one level of a most-specific walk says.
488pub(crate) struct Level {
489    pub(crate) rights: Rights,
490    pub(crate) cancel: Option<usize>,
491    pub(crate) deciding: Option<usize>,
492}
493
494/// The entries of the requester's highest tier at one level, unioned: the subjects naming
495/// the requester (and `Owner`) beat groups, `Everyone` and `Authenticated`. `None` when no
496/// entry applies, so the level leaves what came from above.
497pub(crate) fn level(applicable: &Applicable<'_>) -> Option<Level> {
498    let personal = |entry: &Entry| {
499        matches!(
500            entry.principal,
501            Principal::Owner | Principal::Subject(Subject::Account(_) | Subject::Person(_))
502        )
503    };
504    let tier: Vec<_> = if applicable.iter().any(|(_, entry, _)| personal(entry)) {
505        applicable
506            .iter()
507            .filter(|(_, entry, _)| personal(entry))
508            .collect()
509    } else {
510        applicable.iter().collect()
511    };
512    let first = tier.first()?;
513    Some(Level {
514        rights: tier.iter().fold(Rights::new(), |all, (_, _, compiled)| {
515            &all | &compiled.rights
516        }),
517        cancel: tier
518            .iter()
519            .find(|(_, _, compiled)| compiled.cancels)
520            .map(|(at, ..)| *at),
521        deciding: Some(first.0),
522    })
523}
524
525impl<'a> Context<'a> {
526    pub(crate) fn for_item<'b>(&self, item: &'b ItemAcl) -> Context<'b>
527    where
528        'a: 'b,
529    {
530        let context: Context<'b> = self.clone();
531        context
532            .owner(item.owner.as_ref())
533            .owner_group(item.owner_group.as_ref())
534    }
535}