summaryrefslogtreecommitdiff
path: root/src/types/oauth.rs
blob: 222c567e85cf51d8c9f7412765105db374a908b6 (plain)
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
use std::{borrow::Cow, fmt::Display};

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub(crate) struct Scope<'a>(pub Cow<'a, str>);

impl<'a> Scope<'a> {
    pub const fn borrowed(s: &'a str) -> Self {
        Self(Cow::Borrowed(s))
    }

    pub fn into_owned(self) -> Scope<'static> {
        Scope(Cow::Owned(self.0.into_owned()))
    }

    pub fn implies(&self, other: &Scope) -> bool {
        let (a, b) = (&*self.0, &*other.0);
        match (a.strip_prefix("https://"), b.strip_prefix("https://")) {
            (Some(a), Some(b)) => {
                let (a_origin, a_path) = a.split_once('/').unwrap_or((a, ""));
                let (b_origin, b_path) = b.split_once('/').unwrap_or((b, ""));
                if a_origin != b_origin {
                    false
                } else {
                    let (a_path, a_frag) = match a_path.split_once('#') {
                        Some((p, f)) => (p, Some(f)),
                        None => (a_path, None),
                    };
                    let (b_path, b_frag) = match b_path.split_once('#') {
                        Some((p, f)) => (p, Some(f)),
                        None => (b_path, None),
                    };
                    if b_path
                        .strip_prefix(a_path)
                        .map_or(false, |br| br.is_empty() || br.starts_with('/'))
                    {
                        match (a_frag, b_frag) {
                            (Some(af), Some(bf)) => af == bf,
                            (Some(_), None) => false,
                            _ => true,
                        }
                    } else {
                        false
                    }
                }
            },
            (None, None) => {
                let (a, a_write) =
                    a.strip_suffix(":write").map(|s| (s, true)).unwrap_or((a, false));
                let (b, b_write) =
                    b.strip_suffix(":write").map(|s| (s, true)).unwrap_or((b, false));
                if b_write && !a_write {
                    false
                } else {
                    b.strip_prefix(a).map_or(false, |br| br.is_empty() || br.starts_with(':'))
                }
            },
            _ => false,
        }
    }
}

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

#[derive(Clone, Debug, Serialize, Deserialize, sqlx::Type)]
#[serde(transparent)]
#[sqlx(transparent)]
pub(crate) struct ScopeSet(String);

impl ScopeSet {
    pub fn split(&self) -> impl Iterator<Item = Scope> {
        // not using split_whitespace because the oauth spec explicitly says to split on SP
        self.0.split(' ').filter(|s| !s.is_empty()).map(Scope::borrowed)
    }

    pub fn implies(&self, scope: &Scope) -> bool {
        self.split().any(|a| a.implies(scope))
    }

    pub fn implies_all(&self, scopes: &ScopeSet) -> bool {
        scopes.split().all(|b| self.implies(&b))
    }

    pub fn is_allowed_by(&self, allowed: &[Scope]) -> bool {
        self.split().all(|scope| allowed.iter().any(|perm| perm.implies(&scope)))
    }

    pub fn remove(&self, remove: &Scope) -> ScopeSet {
        let remaining = self.split().filter(|s| !remove.implies(s));
        ScopeSet(remaining.map(|s| s.0).collect::<Vec<_>>().join(" "))
    }
}

impl PartialEq for ScopeSet {
    fn eq(&self, other: &Self) -> bool {
        let (mut a, mut b) = (self.split().collect::<Vec<_>>(), other.split().collect::<Vec<_>>());
        a.sort_by(|a, b| a.0.cmp(&b.0));
        b.sort_by(|a, b| a.0.cmp(&b.0));
        a.eq(&b)
    }
}

impl Eq for ScopeSet {}

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

#[cfg(test)]
mod test {
    use super::{Scope, ScopeSet};

    #[test]
    fn test_scope_implies() {
        assert!(ScopeSet("profile:write".to_string()).implies(&Scope::borrowed("profile")));
        assert!(ScopeSet("profile".to_string()).implies(&Scope::borrowed("profile:email")));
        assert!(ScopeSet("profile:write".to_string()).implies(&Scope::borrowed("profile:email")));
        assert!(
            ScopeSet("profile:write".to_string()).implies(&Scope::borrowed("profile:email:write"))
        );
        assert!(
            ScopeSet("profile:email:write".to_string()).implies(&Scope::borrowed("profile:email"))
        );
        assert!(ScopeSet("profile profile:email:write".to_string())
            .implies(&Scope::borrowed("profile:email")));
        assert!(ScopeSet("profile profile:email:write".to_string())
            .implies(&Scope::borrowed("profile:display_name")));
        assert!(ScopeSet("profile https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("profile")));
        assert!(ScopeSet("profile https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync#read")));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks")));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks#read")));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync#read".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks#read")));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync#read profile".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks#read")));

        assert!(!ScopeSet("profile:email:write".to_string()).implies(&Scope::borrowed("profile")));
        assert!(
            !ScopeSet("profile:email:write".to_string()).implies(&Scope::borrowed("profile:write"))
        );
        assert!(!ScopeSet("profile:email".to_string())
            .implies(&Scope::borrowed("profile:display_name")));
        assert!(!ScopeSet("profilebogey".to_string()).implies(&Scope::borrowed("profile")));
        assert!(!ScopeSet("profile:write".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
        assert!(!ScopeSet("profile profile:email:write".to_string())
            .implies(&Scope::borrowed("profile:write")));
        assert!(!ScopeSet("https".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("profile")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync#read".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync#write".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/bookmarks#read")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync/bookmarks".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync/bookmarks".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync/passwords")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsyncer".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsyncer")));
        assert!(!ScopeSet("https://identity.mozilla.org/apps/oldsync".to_string())
            .implies(&Scope::borrowed("https://identity.mozilla.com/apps/oldsync")));
    }

    #[test]
    fn test_scopes_allowed_by() {
        const ALLOWED: [Scope; 2] = [
            Scope::borrowed("profile:write"),
            Scope::borrowed("https://identity.mozilla.com/apps/oldsync"),
        ];

        assert!(ScopeSet("profile".to_string()).is_allowed_by(&ALLOWED));
        assert!(ScopeSet("profile:write".to_string()).is_allowed_by(&ALLOWED));
        assert!(ScopeSet("profile:email".to_string()).is_allowed_by(&ALLOWED));
        assert!(ScopeSet("profile:email:write".to_string()).is_allowed_by(&ALLOWED));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync#read".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync/bookmarks".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(ScopeSet("https://identity.mozilla.com/apps/oldsync/bookmarks#read".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(ScopeSet("profile https://identity.mozilla.com/apps/oldsync".to_string())
            .is_allowed_by(&ALLOWED));

        assert!(!ScopeSet("storage".to_string()).is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("storage:write".to_string()).is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("storage:email".to_string()).is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("storage:email:write".to_string()).is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/newsync".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/newsync#read".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/newsync/bookmarks".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("https://identity.mozilla.com/apps/newsync/bookmarks#read".to_string())
            .is_allowed_by(&ALLOWED));
        assert!(!ScopeSet("storage https://identity.mozilla.com/apps/newsync".to_string())
            .is_allowed_by(&ALLOWED));
    }

    #[test]
    fn test_scopes_remove() {
        assert_eq!(
            ScopeSet("profile foo".to_string()).remove(&Scope::borrowed("profile")),
            ScopeSet("foo".to_string())
        );
        assert_ne!(
            ScopeSet("profile:write foo".to_string()).remove(&Scope::borrowed("profile")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("profile:write foo".to_string()).remove(&Scope::borrowed("profile:write")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("profile:x foo".to_string()).remove(&Scope::borrowed("profile")),
            ScopeSet("foo".to_string())
        );
        assert_ne!(
            ScopeSet("profile:x:write foo".to_string()).remove(&Scope::borrowed("profile")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("profile:x:write foo".to_string()).remove(&Scope::borrowed("profile:write")),
            ScopeSet("foo".to_string())
        );

        assert_eq!(
            ScopeSet("https://foo/bar foo".to_string()).remove(&Scope::borrowed("https://foo/bar")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("https://foo/bar/baz foo".to_string())
                .remove(&Scope::borrowed("https://foo/bar")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("https://foo/bar#read foo".to_string())
                .remove(&Scope::borrowed("https://foo/bar")),
            ScopeSet("foo".to_string())
        );
        assert_eq!(
            ScopeSet("https://foo/bar/baz#read foo".to_string())
                .remove(&Scope::borrowed("https://foo/bar")),
            ScopeSet("foo".to_string())
        );
    }
}