Skip to main content

coqui_access_acl/
rights.rs

1//! Rights as a growable bit set, and the per-item-type schema that names them.
2
3use alloc::borrow::ToOwned;
4use alloc::collections::BTreeMap;
5use alloc::string::String;
6use alloc::vec::Vec;
7use core::fmt;
8use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Sub, SubAssign};
9
10use crate::error::AclError;
11use crate::options::Limits;
12
13/// A set of rights, one bit per right a [`RightsSchema`] defines. It grows as wide as the
14/// schema needs: Windows uses 32 bits, NFSv4 14, Proxmox about 60.
15///
16/// Bits mean nothing without their schema; store names ([`Entry::rights`]) and compile them
17/// with [`RightsSchema::rights`].
18///
19/// [`Entry::rights`]: crate::Entry::rights
20#[derive(Clone, Default, PartialEq, Eq, Hash)]
21pub struct Rights {
22    /// Never ends in a zero word, so equal sets compare equal.
23    words: Vec<u64>,
24}
25
26impl Rights {
27    /// The empty set.
28    pub const fn new() -> Self {
29        Self { words: Vec::new() }
30    }
31
32    /// Whether `bit` is in the set.
33    pub fn contains(&self, bit: usize) -> bool {
34        self.words
35            .get(bit / 64)
36            .is_some_and(|word| word & (1 << (bit % 64)) != 0)
37    }
38
39    /// Adds `bit`; `true` when it was not there.
40    pub fn insert(&mut self, bit: usize) -> bool {
41        let at = bit / 64;
42        if self.words.len() <= at {
43            self.words.resize(at + 1, 0);
44        }
45        let had = self.words[at] & (1 << (bit % 64)) != 0;
46        self.words[at] |= 1 << (bit % 64);
47        !had
48    }
49
50    /// Removes `bit`; `true` when it was there.
51    pub fn remove(&mut self, bit: usize) -> bool {
52        let had = self.contains(bit);
53        if had {
54            self.words[bit / 64] &= !(1 << (bit % 64));
55            self.trim();
56        }
57        had
58    }
59
60    /// Whether the set is empty.
61    pub fn is_empty(&self) -> bool {
62        self.words.is_empty()
63    }
64
65    /// How many rights the set holds.
66    pub fn len(&self) -> usize {
67        self.words
68            .iter()
69            .map(|word| word.count_ones() as usize)
70            .sum()
71    }
72
73    /// Whether every right here is also in `other`.
74    pub fn is_subset(&self, other: &Rights) -> bool {
75        self.words
76            .iter()
77            .enumerate()
78            .all(|(at, word)| word & !other.words.get(at).copied().unwrap_or(0) == 0)
79    }
80
81    /// Whether the two sets share no right.
82    pub fn is_disjoint(&self, other: &Rights) -> bool {
83        self.words
84            .iter()
85            .zip(&other.words)
86            .all(|(one, two)| one & two == 0)
87    }
88
89    /// The bits in the set, lowest first.
90    pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
91        self.words.iter().enumerate().flat_map(|(at, word)| {
92            (0..64)
93                .filter(move |bit| word & (1 << bit) != 0)
94                .map(move |bit| at * 64 + bit)
95        })
96    }
97
98    fn trim(&mut self) {
99        while self.words.last() == Some(&0) {
100            self.words.pop();
101        }
102    }
103
104    fn zip_with(&self, other: &Rights, combine: impl Fn(u64, u64) -> u64) -> Rights {
105        let width = self.words.len().max(other.words.len());
106        let word = |words: &[u64], at: usize| words.get(at).copied().unwrap_or(0);
107        let mut combined = Rights {
108            words: (0..width)
109                .map(|at| combine(word(&self.words, at), word(&other.words, at)))
110                .collect(),
111        };
112        combined.trim();
113        combined
114    }
115}
116
117impl fmt::Debug for Rights {
118    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119        formatter.debug_set().entries(self.iter()).finish()
120    }
121}
122
123impl FromIterator<usize> for Rights {
124    fn from_iter<I: IntoIterator<Item = usize>>(bits: I) -> Self {
125        let mut rights = Rights::new();
126        rights.extend(bits);
127        rights
128    }
129}
130
131impl Extend<usize> for Rights {
132    fn extend<I: IntoIterator<Item = usize>>(&mut self, bits: I) {
133        for bit in bits {
134            self.insert(bit);
135        }
136    }
137}
138
139impl BitOr for &Rights {
140    type Output = Rights;
141
142    fn bitor(self, other: &Rights) -> Rights {
143        self.zip_with(other, |one, two| one | two)
144    }
145}
146
147impl BitAnd for &Rights {
148    type Output = Rights;
149
150    fn bitand(self, other: &Rights) -> Rights {
151        self.zip_with(other, |one, two| one & two)
152    }
153}
154
155impl Sub for &Rights {
156    type Output = Rights;
157
158    fn sub(self, other: &Rights) -> Rights {
159        self.zip_with(other, |one, two| one & !two)
160    }
161}
162
163impl BitOrAssign<&Rights> for Rights {
164    fn bitor_assign(&mut self, other: &Rights) {
165        *self = &*self | other;
166    }
167}
168
169impl BitAndAssign<&Rights> for Rights {
170    fn bitand_assign(&mut self, other: &Rights) {
171        *self = &*self & other;
172    }
173}
174
175impl SubAssign<&Rights> for Rights {
176    fn sub_assign(&mut self, other: &Rights) {
177        *self = &*self - other;
178    }
179}
180
181/// What a name stands for.
182#[derive(Debug, Clone)]
183struct Named {
184    rights: Rights,
185    cancels: bool,
186}
187
188/// The rights one type of item has, by name, and the aliases that stand for several.
189///
190/// A right is one bit, numbered in the order it is defined. An alias names a set of rights
191/// and earlier aliases: Windows generic rights, NFSv4 basic permissions and Proxmox roles
192/// are all aliases. A cancelling name ([`RightsSchemaBuilder::cancel`]) grants nothing, and
193/// an entry naming it denies everything (Proxmox's `NoAccess`).
194///
195/// ```
196/// use coqui_access_acl::RightsSchema;
197///
198/// let schema = RightsSchema::builder()
199///     .right("read_data")
200///     .right("read_attributes")
201///     .right("write_data")
202///     .alias("read", ["read_data", "read_attributes"])
203///     .build()?;
204/// assert_eq!(schema.rights(["read"])?, schema.rights(["read_data", "read_attributes"])?);
205/// assert!(schema.rights(["delete"]).is_err());
206/// # Ok::<(), coqui_access_acl::AclError>(())
207/// ```
208#[derive(Debug, Clone, Default)]
209pub struct RightsSchema {
210    bits: Vec<String>,
211    names: BTreeMap<String, Named>,
212}
213
214impl RightsSchema {
215    /// Starts a schema; rights take bits in the order they are added.
216    pub fn builder() -> RightsSchemaBuilder {
217        RightsSchemaBuilder::default()
218    }
219
220    /// How many rights (bits) the schema defines; aliases are not counted.
221    pub fn len(&self) -> usize {
222        self.bits.len()
223    }
224
225    /// Whether the schema defines no right.
226    pub fn is_empty(&self) -> bool {
227        self.bits.is_empty()
228    }
229
230    /// The bit of the right `name`; `None` for an alias or an unknown name.
231    pub fn bit(&self, name: &str) -> Option<usize> {
232        self.bits.iter().position(|bit| bit == name)
233    }
234
235    /// Every right the schema defines.
236    pub fn all(&self) -> Rights {
237        (0..self.bits.len()).collect()
238    }
239
240    /// Whether `name` cancels everything.
241    pub fn cancels(&self, name: &str) -> bool {
242        self.names.get(name).is_some_and(|named| named.cancels)
243    }
244
245    /// The rights `names` stand for together: rights and aliases, unioned.
246    ///
247    /// # Errors
248    ///
249    /// [`AclError::UnknownRight`] with the position of the first name the schema lacks.
250    pub fn rights<I, S>(&self, names: I) -> Result<Rights, AclError>
251    where
252        I: IntoIterator<Item = S>,
253        S: AsRef<str>,
254    {
255        let mut rights = Rights::new();
256        for (at, name) in names.into_iter().enumerate() {
257            let named = self
258                .names
259                .get(name.as_ref())
260                .ok_or(AclError::UnknownRight { entry: None, at })?;
261            rights |= &named.rights;
262        }
263        Ok(rights)
264    }
265
266    /// The names of the rights in `rights`, lowest bit first; a bit the schema does not
267    /// define is left out.
268    pub fn names<'a>(&'a self, rights: &Rights) -> Vec<&'a str> {
269        rights
270            .iter()
271            .filter_map(|bit| self.bits.get(bit).map(String::as_str))
272            .collect()
273    }
274
275    /// The rights and whether any name cancels, or the position of the first unknown name.
276    pub(crate) fn compile(&self, names: &[String]) -> Result<(Rights, bool), usize> {
277        let mut rights = Rights::new();
278        let mut cancels = false;
279        for (at, name) in names.iter().enumerate() {
280            let named = self.names.get(name).ok_or(at)?;
281            rights |= &named.rights;
282            cancels |= named.cancels;
283        }
284        Ok((rights, cancels))
285    }
286}
287
288/// Builds a [`RightsSchema`].
289#[derive(Debug, Clone, Default)]
290#[must_use]
291pub struct RightsSchemaBuilder {
292    rights: Vec<String>,
293    aliases: Vec<(String, Vec<String>, bool)>,
294    limits: Limits,
295}
296
297impl RightsSchemaBuilder {
298    /// Defines a right, with the next bit.
299    pub fn right(mut self, name: impl Into<String>) -> Self {
300        self.rights.push(name.into());
301        self
302    }
303
304    /// Defines several rights, in order.
305    pub fn rights(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
306        self.rights.extend(names.into_iter().map(Into::into));
307        self
308    }
309
310    /// Defines an alias for rights and aliases defined before it.
311    pub fn alias(
312        mut self,
313        name: impl Into<String>,
314        members: impl IntoIterator<Item = impl Into<String>>,
315    ) -> Self {
316        self.aliases.push((
317            name.into(),
318            members.into_iter().map(Into::into).collect(),
319            false,
320        ));
321        self
322    }
323
324    /// Defines a name that grants nothing and cancels every grant where it is in force.
325    pub fn cancel(mut self, name: impl Into<String>) -> Self {
326        self.aliases.push((name.into(), Vec::new(), true));
327        self
328    }
329
330    /// The bounds the schema is built within; only [`Limits::rights`] applies here.
331    pub fn limits(mut self, limits: Limits) -> Self {
332        self.limits = limits;
333        self
334    }
335
336    /// Checks the names and builds the schema.
337    ///
338    /// # Errors
339    ///
340    /// [`AclError::InvalidName`] for an empty name or one holding a control character,
341    /// [`AclError::DuplicateName`], [`AclError::UnknownRight`] for an alias member not defined
342    /// before it, [`AclError::TooManyRights`] past [`Limits::rights`].
343    pub fn build(self) -> Result<RightsSchema, AclError> {
344        if self
345            .limits
346            .rights
347            .is_some_and(|max| self.rights.len() > max)
348        {
349            return Err(AclError::TooManyRights);
350        }
351        let mut schema = RightsSchema::default();
352        let add = |schema: &mut RightsSchema, name: &str, named: Named| {
353            if name.is_empty() || name.chars().any(char::is_control) {
354                return Err(AclError::InvalidName);
355            }
356            if schema.names.insert(name.to_owned(), named).is_some() {
357                return Err(AclError::DuplicateName);
358            }
359            Ok(())
360        };
361        for (bit, name) in self.rights.iter().enumerate() {
362            let rights = core::iter::once(bit).collect();
363            add(
364                &mut schema,
365                name,
366                Named {
367                    rights,
368                    cancels: false,
369                },
370            )?;
371            schema.bits.push(name.clone());
372        }
373        for (name, members, cancels) in &self.aliases {
374            let (rights, cancelling) = schema
375                .compile(members)
376                .map_err(|at| AclError::UnknownRight { entry: None, at })?;
377            let named = Named {
378                rights,
379                cancels: *cancels || cancelling,
380            };
381            add(&mut schema, name, named)?;
382        }
383        Ok(schema)
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn a_set_grows_past_one_word_and_compares_by_content() {
393        let mut wide: Rights = [1, 70, 130].into_iter().collect();
394        assert!(wide.contains(70) && !wide.contains(71));
395        assert_eq!(wide.len(), 3);
396        assert!(wide.remove(130));
397        assert!(!wide.remove(130));
398        assert_eq!(wide, [70, 1].into_iter().collect());
399        let narrow: Rights = [1].into_iter().collect();
400        assert!(narrow.is_subset(&wide) && !wide.is_subset(&narrow));
401        assert_eq!(&wide - &narrow, [70].into_iter().collect());
402        assert_eq!(&wide & &narrow, narrow);
403        assert!((&wide - &wide).is_empty());
404        assert_eq!(wide.iter().collect::<Vec<_>>(), [1, 70]);
405        assert!(narrow.is_disjoint(&[70].into_iter().collect()));
406    }
407
408    #[test]
409    fn names_compile_to_bits_and_unknown_or_repeated_names_are_refused() {
410        let schema = RightsSchema::builder()
411            .rights(["a", "b", "c"])
412            .alias("ab", ["a", "b"])
413            .alias("abc", ["ab", "c"])
414            .cancel("none")
415            .build()
416            .unwrap();
417        assert_eq!(schema.len(), 3);
418        assert_eq!(schema.rights(["abc"]).unwrap(), schema.all());
419        assert_eq!(schema.names(&schema.rights(["ab"]).unwrap()), ["a", "b"]);
420        assert!(schema.cancels("none") && !schema.cancels("a"));
421        assert!(schema.rights(["none"]).unwrap().is_empty());
422        assert!(matches!(
423            schema.rights(["a", "zz"]),
424            Err(AclError::UnknownRight { at: 1, .. })
425        ));
426        for bad in [
427            RightsSchema::builder().rights(["a", "a"]),
428            RightsSchema::builder().right("a").alias("a", ["a"]),
429            RightsSchema::builder().right(""),
430            RightsSchema::builder().alias("x", ["missing"]),
431            RightsSchema::builder()
432                .rights(["a", "b"])
433                .limits(Limits::default().rights(Some(1))),
434        ] {
435            assert!(bad.build().is_err());
436        }
437        let many = (0..2000).map(|bit| alloc::format!("r{bit}"));
438        assert!(
439            RightsSchema::builder()
440                .rights(many.clone())
441                .build()
442                .is_err()
443        );
444        let unbounded = Limits::default().rights(None);
445        let wide = RightsSchema::builder()
446            .rights(many)
447            .limits(unbounded)
448            .build()
449            .unwrap();
450        assert_eq!(wide.all().len(), 2000);
451    }
452}