Skip to main content

oauth_toolkit/
scope.rs

1//! OAuth2 scope parsing and validation.
2
3/// Parse a space- or comma-separated scope string into a sorted, deduplicated vec.
4pub 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
15/// Validate that every requested scope is in the allowed set.
16///
17/// Returns the normalized scope list on success, or the first unknown scope as an error.
18pub 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
27/// Check that `requested` scopes are a subset of `allowed` scopes.
28pub fn scopes_subset(requested: &[String], allowed: &[String]) -> bool {
29    requested.iter().all(|r| allowed.contains(r))
30}
31
32/// Errors for scope operations.
33#[derive(Debug, thiserror::Error)]
34pub enum ScopeError {
35    /// An unknown scope was requested.
36    #[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!(
47            parse_scopes("read write admin"),
48            vec!["admin", "read", "write"]
49        );
50    }
51
52    #[test]
53    fn parse_scopes_comma() {
54        assert_eq!(
55            parse_scopes("read,write,admin"),
56            vec!["admin", "read", "write"]
57        );
58    }
59
60    #[test]
61    fn parse_scopes_dedup() {
62        assert_eq!(parse_scopes("read read"), vec!["read"]);
63    }
64
65    #[test]
66    fn validate_scopes_ok() {
67        let requested = vec!["read".into(), "write".into()];
68        let allowed = &["read", "write", "admin"];
69        assert!(validate_scopes(&requested, allowed).is_ok());
70    }
71
72    #[test]
73    fn validate_scopes_unknown() {
74        let requested = vec!["read".into(), "dangerous".into()];
75        let allowed = &["read", "write"];
76        assert!(validate_scopes(&requested, allowed).is_err());
77    }
78
79    #[test]
80    fn scopes_subset_true() {
81        assert!(scopes_subset(&["a".into()], &["a".into(), "b".into()]));
82    }
83
84    #[test]
85    fn scopes_subset_false() {
86        assert!(!scopes_subset(
87            &["a".into(), "c".into()],
88            &["a".into(), "b".into()]
89        ));
90    }
91}