dailp/
auth.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use async_graphql::{Guard, MaybeUndefined};
use serde::{Deserialize, Serialize};
use serde_with::{rust::StringWithSeparator, CommaSeparator};
use uuid::Uuid;

/// Auth metadata on the user making the current request.
#[derive(PartialEq, Debug, async_graphql::SimpleObject)]
pub struct UserInfo {
    /// Unique ID for the User. Should be an AWS Cognito Sub.
    pub id: Uuid,
    email: String,
    groups: Vec<UserGroup>,
}

/// serde deserialization struct for UserInfo.
///
/// AWS Cognito JWTs will encode groups as an array of strings.
/// Compare to ApiGatewayUserInfoDef
#[derive(Deserialize, Debug)]
#[serde(remote = "UserInfo")]
pub struct JWTUserInfoDef {
    #[serde(default, rename = "sub")]
    id: Uuid,
    email: String,
    #[serde(default, rename = "cognito:groups")]
    groups: Vec<UserGroup>,
}

/// A helper type for deserializing UserInfo from a Cognito JWT
#[derive(Deserialize)]
pub struct JWTUserInfo(#[serde(with = "JWTUserInfoDef")] pub UserInfo);

/// serde deserialization struct for UserInfo.
///
/// AWS ApiGateway will always encode the groups as a comma-separated
/// string, even if the client sends a JWT with an array.
#[derive(PartialEq, Deserialize, Debug)]
#[serde(remote = "UserInfo")]
pub struct ApiGatewayUserInfoDef {
    #[serde(default, rename = "sub")]
    id: Uuid,
    email: String,
    #[serde(
        default,
        rename = "cognito:groups",
        with = "StringWithSeparator::<CommaSeparator>"
    )]
    groups: Vec<UserGroup>,
}

/// A helper type for deserializing UserInfo from AWS ApiGateway
#[derive(Deserialize)]
pub struct ApiGatewayUserInfo(#[serde(with = "ApiGatewayUserInfoDef")] pub UserInfo);

/// A user belongs to any number of user groups, which give them various permissions.
#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize, Debug, async_graphql::Enum)]
pub enum UserGroup {
    /// A user that can add audio, comments, and some language data.
    Contributors,
    /// A user that can add and publicly display language data, audio, and comments.
    Editors,
    Readers,
    Administrators,
}

impl From<String> for UserGroup {
    fn from(s: String) -> Self {
        match s.as_str() {
            "Contributors" => UserGroup::Contributors,
            "Editors" => UserGroup::Editors,
            "Readers" => UserGroup::Readers,
            "Administrators" => UserGroup::Administrators,
            "CONTRIBUTOR" => UserGroup::Contributors,
            "EDITOR" => UserGroup::Editors,
            "READER" => UserGroup::Readers,
            "ADMINISTRATOR" => UserGroup::Administrators,
            _ => panic!("Unknown user group: {}", s),
        }
    }
}

impl From<Option<String>> for UserGroup {
    fn from(opt_s: Option<String>) -> Self {
        match opt_s {
            Some(s) => UserGroup::from(s),
            None => UserGroup::Readers,
        }
    }
}

impl UserGroup {
    pub fn to_string(&self) -> String {
        match self {
            UserGroup::Contributors => "Contributors".to_string(),
            UserGroup::Editors => "Editors".to_string(),
            UserGroup::Readers => "Readers".to_string(),
            UserGroup::Administrators => "Administrators".to_string(),
        }
    }
}

// // Impl FromStr and Display automatically for UserGroup, using serde.
// // This allows us to (de)serialize lists of groups via a comma-separated string
// // like this: "Editor,Contributor,Translator"
serde_plain::forward_from_str_to_serde!(UserGroup);
serde_plain::forward_display_to_serde!(UserGroup);

/// Requires that the user is authenticated and a member of the given user group.
pub struct GroupGuard {
    group: UserGroup,
}

impl GroupGuard {
    /// Creates a new group guard from existing user groups.
    ///     See dailp::auth::UserGoup.
    pub fn new(group: UserGroup) -> Self {
        Self { group }
    }
}

#[async_trait::async_trait]
impl Guard for GroupGuard {
    async fn check(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<()> {
        let user = ctx.data_opt::<UserInfo>();
        let has_group = user.map(|user| user.groups.iter().any(|group| group == &self.group));

        match user {
            Some(user) => log::info!("Debug user info groups={:?}", user),
            None => log::info!("No user"),
        };

        if has_group == Some(true) {
            Ok(())
        } else {
            Err(format!("Forbidden, user not in group '{:?}'", self.group).into())
        }
    }
}

/// Blocks access if the user is in the specified group.
pub struct NotGroupGuard {
    group: UserGroup,
}

impl NotGroupGuard {
    pub fn new(group: UserGroup) -> Self {
        Self { group }
    }
}

#[async_trait::async_trait]
impl Guard for NotGroupGuard {
    async fn check(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<()> {
        let user = ctx.data_opt::<UserInfo>();
        let is_in_forbidden_group =
            user.map(|user| user.groups.iter().any(|group| group == &self.group));

        // Deny access if the user is in the forbidden group
        if is_in_forbidden_group == Some(true) {
            Err(format!("Forbidden: User is in blocked group '{:?}'", self.group).into())
        } else {
            Ok(())
        }
    }
}

/// Requires that the user is authenticated.
pub struct AuthGuard;

#[async_trait::async_trait]
impl Guard for AuthGuard {
    async fn check(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<()> {
        let user = ctx.data_opt::<UserInfo>();
        if user.is_some() {
            Ok(())
        } else {
            Err("Forbidden, user not authenticated".into())
        }
    }
}

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

    #[test]
    fn decoding_single_group_works() {
        let res: Result<ApiGatewayUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:groups": "Editors",
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|ApiGatewayUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![UserGroup::Editors]
            }
        )
    }

    #[test]
    fn decoding_many_groups_works() {
        let res: Result<ApiGatewayUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:groups": "Editors,Contributors",
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|ApiGatewayUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![UserGroup::Editors, UserGroup::Contributors]
            }
        )
    }

    #[test]
    fn decoding_no_groups_works() {
        let res: Result<ApiGatewayUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|ApiGatewayUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![]
            }
        )
    }
}

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

    #[test]
    fn decoding_single_group_works() {
        let res: Result<JWTUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:groups": ["Editors"],
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|JWTUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![UserGroup::Editors]
            }
        )
    }

    #[test]
    fn decoding_many_groups_works() {
        let res: Result<JWTUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:groups": ["Editors", "Contributors"],
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|JWTUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![UserGroup::Editors, UserGroup::Contributors]
            }
        )
    }

    #[test]
    fn decoding_no_groups_works() {
        let res: Result<JWTUserInfo, _> = serde_json::from_str(
            r#"
            {
                "cognito:username": "7c455493-8e7e-47b9-abed-5f1492eb7a9b",
                "email": "charliemcvicker@protonmail.com",
                "sub": "7c455493-8e7e-47b9-abed-5f1492eb7a9b"
              }
            "#,
        );

        assert_eq!(
            res.map(|JWTUserInfo(user)| user).unwrap(),
            UserInfo {
                id: Uuid::parse_str("7c455493-8e7e-47b9-abed-5f1492eb7a9b").unwrap(),
                email: String::from("charliemcvicker@protonmail.com"),
                groups: vec![]
            }
        )
    }
}