oauth2_types/
scope.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Copyright 2024 New Vector Ltd.
// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
//
// SPDX-License-Identifier: AGPL-3.0-only
// Please see LICENSE in the repository root for full details.

//! Types to define an [access token's scope].
//!
//! [access token's scope]: https://www.rfc-editor.org/rfc/rfc6749#section-3.3

#![allow(clippy::module_name_repetitions)]

use std::{borrow::Cow, collections::BTreeSet, iter::FromIterator, ops::Deref, str::FromStr};

use serde::{Deserialize, Serialize};
use thiserror::Error;

/// The error type returned when a scope is invalid.
#[derive(Debug, Error, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[error("Invalid scope format")]
pub struct InvalidScope;

/// A scope token or scope value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ScopeToken(Cow<'static, str>);

impl ScopeToken {
    /// Create a `ScopeToken` from a static string. The validity of it is not
    /// checked since it has to be valid in const contexts
    #[must_use]
    pub const fn from_static(token: &'static str) -> Self {
        Self(Cow::Borrowed(token))
    }

    /// Get the scope token as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

/// `openid`.
///
/// Must be included in OpenID Connect requests.
pub const OPENID: ScopeToken = ScopeToken::from_static("openid");

/// `profile`.
///
/// Requests access to the End-User's default profile Claims.
pub const PROFILE: ScopeToken = ScopeToken::from_static("profile");

/// `email`.
///
/// Requests access to the `email` and `email_verified` Claims.
pub const EMAIL: ScopeToken = ScopeToken::from_static("email");

/// `address`.
///
/// Requests access to the `address` Claim.
pub const ADDRESS: ScopeToken = ScopeToken::from_static("address");

/// `phone`.
///
/// Requests access to the `phone_number` and `phone_number_verified` Claims.
pub const PHONE: ScopeToken = ScopeToken::from_static("phone");

/// `offline_access`.
///
/// Requests that an OAuth 2.0 Refresh Token be issued that can be used to
/// obtain an Access Token that grants access to the End-User's Userinfo
/// Endpoint even when the End-User is not present (not logged in).
pub const OFFLINE_ACCESS: ScopeToken = ScopeToken::from_static("offline_access");

// As per RFC6749 appendix A:
// https://datatracker.ietf.org/doc/html/rfc6749#appendix-A
//
//    NQCHAR     = %x21 / %x23-5B / %x5D-7E
fn nqchar(c: char) -> bool {
    '\x21' == c || ('\x23'..'\x5B').contains(&c) || ('\x5D'..'\x7E').contains(&c)
}

impl FromStr for ScopeToken {
    type Err = InvalidScope;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // As per RFC6749 appendix A.4:
        // https://datatracker.ietf.org/doc/html/rfc6749#appendix-A.4
        //
        //    scope-token = 1*NQCHAR
        if !s.is_empty() && s.chars().all(nqchar) {
            Ok(ScopeToken(Cow::Owned(s.into())))
        } else {
            Err(InvalidScope)
        }
    }
}

impl Deref for ScopeToken {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::fmt::Display for ScopeToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// A scope.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scope(BTreeSet<ScopeToken>);

impl Deref for Scope {
    type Target = BTreeSet<ScopeToken>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl FromStr for Scope {
    type Err = InvalidScope;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // As per RFC6749 appendix A.4:
        // https://datatracker.ietf.org/doc/html/rfc6749#appendix-A.4
        //
        //    scope       = scope-token *( SP scope-token )
        let scopes: Result<BTreeSet<ScopeToken>, InvalidScope> =
            s.split(' ').map(ScopeToken::from_str).collect();

        Ok(Self(scopes?))
    }
}

impl Scope {
    /// Whether this `Scope` is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        // This should never be the case?
        self.0.is_empty()
    }

    /// The number of tokens in the `Scope`.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether this `Scope` contains the given value.
    #[must_use]
    pub fn contains(&self, token: &str) -> bool {
        ScopeToken::from_str(token)
            .map(|token| self.0.contains(&token))
            .unwrap_or(false)
    }

    /// Inserts the given token in this `Scope`.
    ///
    /// Returns whether the token was newly inserted.
    pub fn insert(&mut self, value: ScopeToken) -> bool {
        self.0.insert(value)
    }
}

impl std::fmt::Display for Scope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (index, token) in self.0.iter().enumerate() {
            if index == 0 {
                write!(f, "{token}")?;
            } else {
                write!(f, " {token}")?;
            }
        }

        Ok(())
    }
}

impl Serialize for Scope {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.to_string().serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Scope {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        // FIXME: seems like there is an unnecessary clone here?
        let scope: String = Deserialize::deserialize(deserializer)?;
        Scope::from_str(&scope).map_err(serde::de::Error::custom)
    }
}

impl FromIterator<ScopeToken> for Scope {
    fn from_iter<T: IntoIterator<Item = ScopeToken>>(iter: T) -> Self {
        Self(BTreeSet::from_iter(iter))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_scope_token() {
        assert_eq!(ScopeToken::from_str("openid"), Ok(OPENID));

        assert_eq!(ScopeToken::from_str("invalid\\scope"), Err(InvalidScope));
    }

    #[test]
    fn parse_scope() {
        let scope = Scope::from_str("openid profile address").unwrap();
        assert_eq!(scope.len(), 3);
        assert!(scope.contains("openid"));
        assert!(scope.contains("profile"));
        assert!(scope.contains("address"));
        assert!(!scope.contains("unknown"));

        assert!(
            Scope::from_str("").is_err(),
            "there should always be at least one token in the scope"
        );

        assert!(Scope::from_str("invalid\\scope").is_err());
        assert!(Scope::from_str("no  double space").is_err());
        assert!(Scope::from_str(" no leading space").is_err());
        assert!(Scope::from_str("no trailing space ").is_err());

        let scope = Scope::from_str("openid").unwrap();
        assert_eq!(scope.len(), 1);
        assert!(scope.contains("openid"));
        assert!(!scope.contains("profile"));
        assert!(!scope.contains("address"));

        assert_eq!(
            Scope::from_str("order does not matter"),
            Scope::from_str("matter not order does"),
        );

        assert!(Scope::from_str("http://example.com").is_ok());
        assert!(Scope::from_str("urn:matrix:org.matrix.msc2967.client:*").is_ok());
    }
}