1pub fn parse_scopes(input: &str) -> Vec<String> {
5 let mut scopes: Vec<String> = input
6 .split(|c: char| c.is_whitespace() || c == ',')
7 .filter(|s| !s.is_empty())
8 .map(|s| s.trim().to_lowercase())
9 .collect();
10 scopes.sort();
11 scopes.dedup();
12 scopes
13}
14
15pub fn validate_scopes(requested: &[String], allowed: &[&str]) -> Result<Vec<String>, ScopeError> {
19 for scope in requested {
20 if !allowed.contains(&scope.as_str()) {
21 return Err(ScopeError::UnknownScope(scope.clone()));
22 }
23 }
24 Ok(requested.to_vec())
25}
26
27pub fn scopes_subset(requested: &[String], allowed: &[String]) -> bool {
29 requested.iter().all(|r| allowed.contains(r))
30}
31
32#[derive(Debug, thiserror::Error)]
34pub enum ScopeError {
35 #[error("unknown scope: {0}")]
37 UnknownScope(String),
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn parse_scopes_whitespace() {
46 assert_eq!(parse_scopes("read write admin"), vec!["admin", "read", "write"]);
47 }
48
49 #[test]
50 fn parse_scopes_comma() {
51 assert_eq!(parse_scopes("read,write,admin"), vec!["admin", "read", "write"]);
52 }
53
54 #[test]
55 fn parse_scopes_dedup() {
56 assert_eq!(parse_scopes("read read"), vec!["read"]);
57 }
58
59 #[test]
60 fn validate_scopes_ok() {
61 let requested = vec!["read".into(), "write".into()];
62 let allowed = &["read", "write", "admin"];
63 assert!(validate_scopes(&requested, allowed).is_ok());
64 }
65
66 #[test]
67 fn validate_scopes_unknown() {
68 let requested = vec!["read".into(), "dangerous".into()];
69 let allowed = &["read", "write"];
70 assert!(validate_scopes(&requested, allowed).is_err());
71 }
72
73 #[test]
74 fn scopes_subset_true() {
75 assert!(scopes_subset(&["a".into()], &["a".into(), "b".into()]));
76 }
77
78 #[test]
79 fn scopes_subset_false() {
80 assert!(!scopes_subset(&["a".into(), "c".into()], &["a".into(), "b".into()]));
81 }
82}