1use core::fmt;
4use core::str::FromStr;
5
6use crate::model::Person;
7
8#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
29#[non_exhaustive]
30pub enum Subject {
31 Account(String),
33 Person(String),
35 Group(String),
39 AnySignedIn,
42}
43
44impl Subject {
45 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 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 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
79fn 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#[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 assert!(written.matches(&in_groups(&["staff", "domain users"])));
194 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 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 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 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}