Skip to main content

coqui_access/
subject.rs

1//! Who a policy names: one account, one person, one group or every signed-in person.
2
3use core::fmt;
4use core::str::FromStr;
5
6use crate::model::Person;
7
8/// One account, person or group, written `account:<name>`, `person:<id>` or `group:<name>`, or
9/// every signed-in person, written `any:signed-in`.
10///
11/// It is the text form policies store; [`matches`](Subject::matches) says whether a
12/// directory's [`Person`] is the one it names. `Debug` shows the kind only, since the value
13/// is an identity; `any:signed-in` names nobody, so it shows whole.
14///
15/// ```
16/// use coqui_access::{Person, Subject};
17///
18/// let staff: Subject = "group:staff".parse()?;
19/// let person = Person { groups: vec!["staff".into()], ..Person::default() };
20/// assert!(staff.matches(&person));
21/// assert_eq!(staff.to_string(), "group:staff");
22///
23/// let signed_in: Subject = "any:signed-in".parse()?;
24/// assert!(signed_in.matches(&Person { id: "p-1".into(), ..Person::default() }));
25/// assert!(!signed_in.matches(&Person::default()));
26/// # Ok::<(), coqui_access::SubjectError>(())
27/// ```
28#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
29#[non_exhaustive]
30pub enum Subject {
31    /// The person whose [`Person::name`] is this.
32    Account(String),
33    /// The person whose [`Person::id`] is this.
34    Person(String),
35    /// Every person whose [`Person::groups`] holds this, compared without regard to case: a
36    /// directory may report a group in either case, and two groups that differ only in case are
37    /// one.
38    Group(String),
39    /// Every person who carries an identity: a non-empty [`Person::id`]. An anonymous caller
40    /// has none, so it never matches. It is the only reserved `any:` name.
41    AnySignedIn,
42}
43
44impl Subject {
45    /// The kind as written before the colon: `account`, `person`, `group` or `any`.
46    pub fn kind(&self) -> &'static str {
47        match self {
48            Self::Account(_) => "account",
49            Self::Person(_) => "person",
50            Self::Group(_) => "group",
51            Self::AnySignedIn => "any",
52        }
53    }
54
55    /// The name, id or group after the colon (`signed-in` for `any:signed-in`).
56    pub fn value(&self) -> &str {
57        match self {
58            Self::Account(value) | Self::Person(value) | Self::Group(value) => value,
59            Self::AnySignedIn => "signed-in",
60        }
61    }
62
63    /// Whether `person` is the one this names, is in the group it names, or, for
64    /// `any:signed-in`, has an id.
65    ///
66    /// An account name and a person id compare exactly. A group compares by Unicode lowercase,
67    /// so `group:Domain Users` names `domain users`; two POSIX groups that differ only in case
68    /// are therefore one here. `==` on a `Subject` stays exact, since it compares the text.
69    pub fn matches(&self, person: &Person) -> bool {
70        match self {
71            Self::Account(name) => name == &person.name,
72            Self::Person(id) => id == &person.id,
73            Self::Group(group) => person.groups.iter().any(|member| same_group(member, group)),
74            Self::AnySignedIn => !person.id.is_empty(),
75        }
76    }
77}
78
79/// Whether two group names are the same without regard to case: equal after Unicode lowercase
80/// (`char::to_lowercase`, not full case folding, so `ß` and `SS` differ), compared a character
81/// at a time so nothing is allocated.
82fn same_group(left: &str, right: &str) -> bool {
83    left.chars()
84        .flat_map(char::to_lowercase)
85        .eq(right.chars().flat_map(char::to_lowercase))
86}
87
88impl fmt::Debug for Subject {
89    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::AnySignedIn => formatter.write_str("Subject(any:signed-in)"),
92            _ => write!(formatter, "Subject({}:…)", self.kind()),
93        }
94    }
95}
96
97impl fmt::Display for Subject {
98    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99        write!(formatter, "{}:{}", self.kind(), self.value())
100    }
101}
102
103/// Text that is not `account:<name>`, `person:<id>` or `group:<name>` with a value that is
104/// not empty, holds no control character and neither starts nor ends with whitespace (inner
105/// spaces are fine: `group:Domain Users`), or `any:signed-in`. Any other `any:` name is
106/// refused.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108#[non_exhaustive]
109pub struct SubjectError;
110
111impl fmt::Display for SubjectError {
112    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
113        formatter
114            .write_str("a subject is account:<name>, person:<id>, group:<name> or any:signed-in")
115    }
116}
117
118impl core::error::Error for SubjectError {}
119
120impl FromStr for Subject {
121    type Err = SubjectError;
122
123    fn from_str(text: &str) -> Result<Self, SubjectError> {
124        if text == "any:signed-in" {
125            return Ok(Self::AnySignedIn);
126        }
127        let (kind, value) = text.split_once(':').ok_or(SubjectError)?;
128        if value.is_empty()
129            || value.chars().any(char::is_control)
130            || value.starts_with(char::is_whitespace)
131            || value.ends_with(char::is_whitespace)
132        {
133            return Err(SubjectError);
134        }
135        let value = value.to_owned();
136        match kind {
137            "account" => Ok(Self::Account(value)),
138            "person" => Ok(Self::Person(value)),
139            "group" => Ok(Self::Group(value)),
140            _ => Err(SubjectError),
141        }
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    fn person() -> Person {
150        Person {
151            id: "p-1".into(),
152            name: "alice".into(),
153            groups: vec!["staff".into()],
154            ..Person::default()
155        }
156    }
157
158    #[test]
159    fn each_kind_reads_writes_and_matches_its_own_field() {
160        for (text, matched) in [
161            ("account:alice", true),
162            ("person:p-1", true),
163            ("group:staff", true),
164            ("account:p-1", false),
165            ("person:alice", false),
166            ("group:alice", false),
167        ] {
168            let subject: Subject = text.parse().unwrap();
169            assert_eq!(subject.to_string(), text);
170            assert_eq!(subject.matches(&person()), matched, "{text}");
171        }
172        assert_eq!(
173            "group:a:b".parse::<Subject>(),
174            Ok(Subject::Group("a:b".into()))
175        );
176    }
177
178    fn in_groups(groups: &[&str]) -> Person {
179        Person {
180            groups: groups.iter().map(|group| (*group).to_owned()).collect(),
181            ..Person::default()
182        }
183    }
184
185    #[test]
186    fn a_group_matches_without_regard_to_case_in_either_direction() {
187        let written: Subject = "group:Domain Users".parse().unwrap();
188        assert!(written.matches(&in_groups(&["domain users"])));
189        assert!(written.matches(&in_groups(&["DOMAIN USERS"])));
190        let lowercase: Subject = "group:domain users".parse().unwrap();
191        assert!(lowercase.matches(&in_groups(&["Domain Users"])));
192        // Any one of the groups may be the one.
193        assert!(written.matches(&in_groups(&["staff", "domain users"])));
194        // Non-ASCII names fold too.
195        let accented: Subject = "group:Ñandú Équipe".parse().unwrap();
196        assert!(accented.matches(&in_groups(&["ñandú équipe"])));
197        let greek: Subject = "group:ΣΟΦΙΑ".parse().unwrap();
198        assert!(greek.matches(&in_groups(&["σοφια"])));
199    }
200
201    #[test]
202    fn a_group_differing_in_more_than_case_does_not_match() {
203        let written: Subject = "group:Domain Users".parse().unwrap();
204        for other in [
205            "domain  users",
206            "domain users ",
207            "domain user",
208            "domainusers",
209            "domain admins",
210        ] {
211            assert!(!written.matches(&in_groups(&[other])), "{other:?}");
212        }
213        assert!(!written.matches(&in_groups(&[])));
214        // Only groups fold: an account or a person id is still compared exactly.
215        let by_name = Person {
216            name: "Alice".into(),
217            id: "P-1".into(),
218            ..Person::default()
219        };
220        assert!(
221            !"account:alice"
222                .parse::<Subject>()
223                .unwrap()
224                .matches(&by_name)
225        );
226        assert!(!"person:p-1".parse::<Subject>().unwrap().matches(&by_name));
227        assert!(
228            "account:Alice"
229                .parse::<Subject>()
230                .unwrap()
231                .matches(&by_name)
232        );
233        // The subject itself stays what was written.
234        assert_ne!(written, "group:domain users".parse::<Subject>().unwrap());
235        assert_eq!(written.to_string(), "group:Domain Users");
236    }
237
238    #[test]
239    fn any_signed_in_reads_writes_and_matches_a_person_with_an_id() {
240        let subject: Subject = "any:signed-in".parse().unwrap();
241        assert_eq!(subject, Subject::AnySignedIn);
242        assert_eq!(subject.to_string(), "any:signed-in");
243        assert_eq!((subject.kind(), subject.value()), ("any", "signed-in"));
244        assert_eq!(format!("{subject:?}"), "Subject(any:signed-in)");
245        assert!(subject.matches(&person()));
246        let anonymous = Person {
247            groups: vec!["staff".into()],
248            name: "alice".into(),
249            ..Person::default()
250        };
251        assert!(!subject.matches(&anonymous), "an empty id is not signed in");
252    }
253
254    #[test]
255    fn every_other_any_name_is_refused() {
256        for text in [
257            "any:",
258            "any:other",
259            "any:person",
260            "any:signed-in:x",
261            "any:Signed-in",
262            "any:signed-in ",
263            "ANY:signed-in",
264            "any",
265        ] {
266            assert_eq!(text.parse::<Subject>(), Err(SubjectError), "{text:?}");
267        }
268        // The kind comes first, so a name that spells it is still a name.
269        assert_eq!(
270            "group:any:signed-in".parse::<Subject>(),
271            Ok(Subject::Group("any:signed-in".into()))
272        );
273    }
274
275    #[test]
276    fn a_value_may_hold_inner_spaces_but_not_start_or_end_with_whitespace() {
277        let group: Subject = "group:Domain Users".parse().unwrap();
278        assert_eq!(group, Subject::Group("Domain Users".into()));
279        assert_eq!(group.to_string(), "group:Domain Users");
280        assert!("account:Ana María".parse::<Subject>().is_ok());
281        for text in [
282            "group: Domain Users",
283            "group:Domain Users ",
284            "account:alice\u{a0}",
285            "person: p-1",
286            "group:  ",
287            "group:Domain\tUsers",
288        ] {
289            assert_eq!(text.parse::<Subject>(), Err(SubjectError), "{text:?}");
290        }
291    }
292
293    #[test]
294    fn malformed_text_is_refused_and_debug_hides_the_value() {
295        for text in ["", "alice", "user:alice", "group:", "group:a\nb", ":x"] {
296            assert_eq!(text.parse::<Subject>(), Err(SubjectError), "{text:?}");
297        }
298        let debug = format!("{:?}", Subject::Account("alice".into()));
299        assert!(!debug.contains("alice") && debug.contains("account"));
300    }
301}