Skip to main content

coqui_access_acl/
path.rs

1//! Walked inheritance: items in a tree, decided from the root down, as Proxmox does.
2
3use alloc::collections::BTreeSet;
4use alloc::string::{String, ToString};
5use alloc::vec::Vec;
6
7use coqui_access::guatiao::library::ProviderError;
8
9use crate::check::{Context, Decision, Level, level};
10use crate::entry::{Entry, ItemAcl, Mode};
11use crate::error::AclError;
12use crate::options::OnMissing;
13use crate::rights::Rights;
14
15/// Where items' ACLs and their places in a tree are kept: the consumer's storage.
16///
17/// An item with its own ACL in a mode other than `MostSpecific` is decided by that ACL
18/// alone (inheritance was copied when it was made). Otherwise the item's ancestors are
19/// walked: every ACL met must be `MostSpecific`, and an item with no ACL and no ACL above
20/// it gets [`Options::on_missing`](crate::Options::on_missing).
21pub trait AclStore {
22    /// The ACL of `item`; `None` when it has none of its own.
23    ///
24    /// # Errors
25    ///
26    /// The store could not answer.
27    fn acl(&self, item: &str) -> Result<Option<ItemAcl>, ProviderError>;
28
29    /// The item `item` is inside; `None` at the root.
30    ///
31    /// # Errors
32    ///
33    /// The store could not answer.
34    fn parent(&self, item: &str) -> Result<Option<String>, ProviderError>;
35
36    /// Whether the requester in `context` holds `wanted` on `item`, its ACL or its
37    /// ancestors' deciding. `context`'s owner is taken from each ACL met, and its item is
38    /// set to `item`.
39    ///
40    /// The walk (Proxmox's): from the root down, a level's entries apply when they are at
41    /// the item itself (not `inherit_only`) or pass to `containers`; the requester's own
42    /// entries (`account:`, `person:`, `Owner`) beat the rest at that level, whose rights
43    /// are unioned; a level where something applies replaces what came from above. A
44    /// cancelling name refuses everything if its level is the one in force.
45    ///
46    /// # Errors
47    ///
48    /// [`AclError::Store`] when the store cannot answer, never a denial;
49    /// [`AclError::Cycle`] when an item is its own ancestor, whatever the limits;
50    /// [`AclError::TooDeep`] past [`Limits::depth`](crate::Limits::depth) levels;
51    /// [`AclError::ModeMismatch`] for an ACL in another mode met on a walk; what
52    /// [`Acl::check`](crate::Acl::check) refuses.
53    fn check(
54        &self,
55        item: &str,
56        context: &Context<'_>,
57        wanted: &Rights,
58    ) -> Result<Decision, AclError> {
59        check_item(self, item, context, wanted)
60    }
61}
62
63fn check_item<S: AclStore + ?Sized>(
64    store: &S,
65    item: &str,
66    context: &Context<'_>,
67    wanted: &Rights,
68) -> Result<Decision, AclError> {
69    let context = context.clone().item(item);
70    let own = store.acl(item)?;
71    if let Some(own) = &own
72        && own.acl.mode != Mode::MostSpecific
73    {
74        return own.check(&context, wanted);
75    }
76    let limit = context.options.limits.depth;
77    let mut chain = Vec::from([(item.to_string(), own)]);
78    let mut seen = BTreeSet::from([item.to_string()]);
79    while let Some(parent) = store.parent(&chain[chain.len() - 1].0)? {
80        if !seen.insert(parent.clone()) {
81            return Err(AclError::Cycle);
82        }
83        if limit.is_some_and(|max| chain.len() >= max) {
84            return Err(AclError::TooDeep);
85        }
86        let acl = store.acl(&parent)?;
87        chain.push((parent, acl));
88    }
89    if chain.iter().all(|(_, acl)| acl.is_none()) {
90        return Ok(match context.options.on_missing {
91            OnMissing::Deny => Decision::nothing(wanted),
92            OnMissing::AllowAll => {
93                Decision::from_sets(wanted, &context.schema.all() | wanted, Rights::new(), None)
94            }
95        });
96    }
97    let mut in_force: Option<Level> = None;
98    for (depth, (_, acl)) in chain.iter().enumerate().rev() {
99        let Some(acl) = acl else { continue };
100        if acl.acl.mode != Mode::MostSpecific {
101            return Err(AclError::ModeMismatch);
102        }
103        let compiled = acl.acl.compile(context.schema, &context.options)?;
104        let here = context.for_item(acl);
105        let at_item = depth == 0;
106        let applicable: Vec<_> = acl
107            .acl
108            .entries
109            .iter()
110            .zip(&compiled)
111            .enumerate()
112            .filter(|(_, (entry, _))| applies_at(entry, at_item) && here.applies(entry))
113            .map(|(at, (entry, compiled))| (at, entry, compiled))
114            .collect();
115        if let Some(found) = level(&applicable) {
116            in_force = Some(found);
117        }
118    }
119    let item_acl = chain[0].1.as_ref();
120    let owner = item_acl.map_or_else(Rights::new, |acl| {
121        context.for_item(acl).owner_grant(&acl.acl)
122    });
123    Ok(match in_force {
124        Some(Level {
125            cancel: Some(at), ..
126        }) => Decision::cancelled(context.schema, wanted, at),
127        Some(found) => Decision::from_sets(
128            wanted,
129            &found.rights | &owner,
130            Rights::new(),
131            found.deciding,
132        ),
133        None => Decision::from_sets(wanted, owner, Rights::new(), None),
134    })
135}
136
137/// Whether an entry counts at its own item (`at_item`) or below it.
138fn applies_at(entry: &Entry, at_item: bool) -> bool {
139    if at_item {
140        !entry.inherit.inherit_only
141    } else {
142        entry.inherit.containers
143    }
144}