tokkit 0.17.0

A simple(simplistic) OAUTH toolkit.
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Various parsers for the responses of a token info service.
use std::env;
use std::str;

use failure::*;

use crate::{Scope, TokenInfo, UserId};

/// A parser that can parse a slice of bytes to a `TokenInfo`
pub trait TokenInfoParser: Send + 'static {
    fn parse(&self, bytes: &[u8]) -> Result<TokenInfo, Error>;
}

/// A configurable `TokenInfoParser` that parses a `TokenInfo` from JSON
/// returned by a token introspection service.
#[derive(Clone)]
pub struct CustomTokenInfoParser {
    /// The field name in the JSON that identifies the `active` field
    /// for the `TokenInfo`. If None the field will not be looked up
    /// and set to `true` in the `TokenInfo` right away.
    /// The reason is that this is a mandatory field in the `TokenInfo`
    /// and that we assume that if a token introspection service does
    /// not provide this field it would return an error in the introspection
    /// request in case the token is not active at the time the request was
    /// made.
    pub active_field: Option<String>,
    /// The field name in the JSON that identifies the `user_id` field
    /// for the `TokenInfo`. If None the field will not be looked up
    /// and set to `None` in the `TokenInfo` right away.
    pub user_id_field: Option<String>,
    /// The field name in the JSON that identifies the `scope` field
    /// for the `TokenInfo`. If None the field will not be looked up
    /// and set to `None` in the `TokenInfo` right away.
    pub scope_field: Option<String>,
    /// The field name in the JSON that identifies the `expires_in` field
    /// for the `TokenInfo`. If None the field will not be looked up
    /// and set to `None` in the `TokenInfo` right away.
    pub expires_in_field: Option<String>,
}

impl CustomTokenInfoParser {
    pub fn new<U, S, E, A>(
        active_field: Option<A>,
        user_id_field: Option<U>,
        scope_field: Option<S>,
        expires_in_field: Option<E>,
    ) -> Self
    where
        U: Into<String>,
        S: Into<String>,
        E: Into<String>,
        A: Into<String>,
    {
        Self {
            active_field: active_field.map(Into::into),
            user_id_field: user_id_field.map(Into::into),
            scope_field: scope_field.map(Into::into),
            expires_in_field: expires_in_field.map(Into::into),
        }
    }

    /// Create a new parser from environment variables.
    ///
    /// The following variables used to identify the field in a token info
    /// response:
    ///
    /// * `TOKKIT_TOKEN_INFO_PARSER_USER_ID_FIELD`(optional): The field name
    /// for the user id * `TOKKIT_TOKEN_INFO_PARSER_SCOPE_FIELD`(optional):
    /// The field name for scopes
    /// * `TOKKIT_TOKEN_INFO_PARSER_EXPIRES_IN_FIELD`(optional): The field name
    /// for the * `TOKKIT_TOKEN_INFO_PARSER_ACTIVE_FIELD`(optional): The
    /// field name for the active field
    pub fn from_env() -> Result<CustomTokenInfoParser, Error> {
        let user_id_field: Option<String> = match env::var("TOKKIT_TOKEN_INFO_PARSER_USER_ID_FIELD")
        {
            Ok(v) => Some(v),
            Err(env::VarError::NotPresent) => None,
            Err(err) => bail!("'TOKKIT_TOKEN_INFO_PARSER_USER_ID_FIELD': {}", err),
        };
        let scope_field: Option<String> = match env::var("TOKKIT_TOKEN_INFO_PARSER_SCOPE_FIELD") {
            Ok(v) => Some(v),
            Err(env::VarError::NotPresent) => None,
            Err(err) => bail!("'TOKKIT_TOKEN_INFO_PARSER_SCOPE_FIELD': {}", err),
        };
        let expires_in_field: Option<String> =
            match env::var("TOKKIT_TOKEN_INFO_PARSER_EXPIRES_IN_FIELD") {
                Ok(v) => Some(v),
                Err(env::VarError::NotPresent) => None,
                Err(err) => bail!("'TOKKIT_TOKEN_INFO_PARSER_EXPIRES_IN_FIELD': {}", err),
            };
        let active_field: Option<String> = match env::var("TOKKIT_TOKEN_INFO_PARSER_ACTIVE_FIELD") {
            Ok(v) => Some(v),
            Err(env::VarError::NotPresent) => None,
            Err(err) => bail!("'TOKKIT_TOKEN_INFO_PARSER_ACTIVE_FIELD': {}", err),
        };
        Ok(Self::new(
            active_field,
            user_id_field,
            scope_field,
            expires_in_field,
        ))
    }
}

impl TokenInfoParser for CustomTokenInfoParser {
    fn parse(&self, json: &[u8]) -> Result<TokenInfo, Error> {
        parse(
            json,
            self.active_field.as_ref().map(|s| &**s),
            self.user_id_field.as_ref().map(|s| &**s),
            self.scope_field.as_ref().map(|s| &**s),
            self.expires_in_field.as_ref().map(|s| &**s),
        )
    }
}

/// Parses a `TokenInfo` from JSON
///
/// [Description](http://planb.readthedocs.io/en/latest/intro.html#token-info)
///
/// ##Example
///
/// ```rust
/// use tokkit::parsers::{PlanBTokenInfoParser, TokenInfoParser};
/// use tokkit::*;
///
/// let sample = br#"
/// {
/// "access_token": "token",
/// "cn": true,
/// "expires_in": 28292,
/// "grant_type": "password",
/// "open_id": "token",
/// "realm": "/services",
/// "scope": ["cn"],
/// "token_type": "Bearer",
/// "uid": "test2"
/// }
/// "#;
///
/// let expected = TokenInfo {
///     active: true,
///     user_id: Some(UserId::new("test2")),
///     scope: vec![Scope::new("cn")],
///     expires_in_seconds: Some(28292),
/// };
///
/// let token_info = PlanBTokenInfoParser.parse(sample).unwrap();
///
/// assert_eq!(expected, token_info);
/// ```
#[derive(Clone)]
pub struct PlanBTokenInfoParser;

impl TokenInfoParser for PlanBTokenInfoParser {
    fn parse(&self, json: &[u8]) -> ::std::result::Result<TokenInfo, Error> {
        parse(json, None, Some("uid"), Some("scope"), Some("expires_in"))
    }
}

/// Parses a `TokenInfo` from JSON
///
/// [Description](https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken)
///
/// ##Example
///
/// ```rust
/// use tokkit::parsers::{GoogleV3TokenInfoParser, TokenInfoParser};
/// use tokkit::*;
///
/// let sample = br#"
/// {
/// "aud":"8819981768.apps.googleusercontent.com",
/// "user_id":"123456789",
/// "scope":"https://www.googleapis.com/auth/drive.metadata.readonly",
/// "expires_in":436
/// }
/// "#;
///
///     let expected = TokenInfo {
///         active: true,
///         user_id: Some(UserId::new("123456789")),
///         scope: vec![Scope::new(
///             "https://www.googleapis.com/auth/drive.metadata.readonly",
///     )],
///     expires_in_seconds: Some(436),
/// };
///
/// let token_info = GoogleV3TokenInfoParser.parse(sample).unwrap();
///
/// assert_eq!(expected, token_info);
/// ```
///
///
#[derive(Clone)]
pub struct GoogleV3TokenInfoParser;

impl TokenInfoParser for GoogleV3TokenInfoParser {
    fn parse(&self, json: &[u8]) -> ::std::result::Result<TokenInfo, Error> {
        parse(
            json,
            None,
            Some("user_id"),
            Some("scope"),
            Some("expires_in"),
        )
    }
}

/// Parses a `TokenInfo` from JSON
///
/// [Description](https://images-na.ssl-images-amazon.
/// com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf)
///
/// ##Example
///
/// ```rust
/// use tokkit::parsers::{AmazonTokenInfoParser, TokenInfoParser};
/// use tokkit::*;
///
/// let sample = br#"
/// {
/// "iss":"https://www.amazon.com",
/// "user_id": "amznl.account.K2LI23KL2LK2",
/// "aud": "amznl.oa2-client.ASFWDFBRN",
/// "app_id": "amznl.application.436457DFHDH",
/// "exp": 3597,
/// "iat": 1311280970
/// }
/// "#;
///
///     let expected = TokenInfo {
///         active: true,
///         user_id: Some(UserId::new("amznl.account.K2LI23KL2LK2")),
///         scope: Vec::new(),
///         expires_in_seconds: Some(3597),
///     };
///
///     let token_info = AmazonTokenInfoParser.parse(sample).unwrap();
///
///     assert_eq!(expected, token_info);
/// ```
#[derive(Clone)]
pub struct AmazonTokenInfoParser;

impl TokenInfoParser for AmazonTokenInfoParser {
    fn parse(&self, json: &[u8]) -> Result<TokenInfo, Error> {
        parse(json, None, Some("user_id"), Some("scope"), Some("exp"))
    }
}

pub fn parse(
    json: &[u8],
    active_field: Option<&str>,
    user_id_field: Option<&str>,
    scope_field: Option<&str>,
    expires_field: Option<&str>,
) -> ::std::result::Result<TokenInfo, Error> {
    use json::*;
    let json = str::from_utf8(json).context("String was not UTF-8")?;
    let json = ::json::parse(json)?;
    match json {
        JsonValue::Object(data) => {
            let active = if let Some(active_field) = active_field {
                match data.get(active_field) {
                    Some(&JsonValue::Boolean(active)) => active,
                    Some(&JsonValue::Short(s)) => s.parse()?,
                    invalid => bail!(
                        "Expected a boolean as the 'active' field in '{}' but found a {:?}",
                        active_field,
                        invalid
                    ),
                }
            } else {
                true
            };
            let user_id = if let Some(user_id_field) = user_id_field {
                match data.get(user_id_field) {
                    Some(&JsonValue::Short(ref user_id)) => Some(UserId::new(user_id.as_str())),
                    Some(&JsonValue::String(ref user_id)) => Some(UserId::new(user_id.as_str())),
                    invalid => bail!(
                        "Expected a string as the user id in field '{}' but found a {:?}",
                        user_id_field,
                        invalid
                    ),
                }
            } else {
                None
            };
            let scope = if let Some(scope_field) = scope_field {
                match data.get(scope_field) {
                    Some(&JsonValue::Array(ref values)) => {
                        let mut scopes = Vec::with_capacity(values.len());
                        for elem in values {
                            match elem {
                                &JsonValue::String(ref v) => scopes.push(Scope(v.clone())),
                                &JsonValue::Short(ref v) => scopes.push(Scope::new(v.as_str())),
                                invalid => bail!(
                                    "Expected a string as a scope in ['{}'] but found '{}'",
                                    scope_field,
                                    invalid
                                ),
                            }
                        }
                        scopes
                    }
                    Some(&JsonValue::String(ref scope)) => split_scopes(scope.as_ref()),
                    Some(&JsonValue::Short(ref scope)) => split_scopes(scope.as_ref()),
                    None => Vec::new(),
                    invalid => bail!(
                        "Expected an array or string for the \
                         scope(s) in field '{}' but found a {:?}",
                        scope_field,
                        invalid
                    ),
                }
            } else {
                Vec::new()
            };
            let expires_in = if let Some(expires_field) = expires_field {
                match data.get(expires_field) {
                    Some(&JsonValue::Number(number)) => {
                        let expires: f64 = number.into();
                        let expires = expires.round() as i64;
                        if expires >= 0 {
                            Some(expires as u64)
                        } else {
                            bail!(
                                "Field '{}' for expires_in_seconds \
                                 must be greater than 0(is {}).",
                                expires_field,
                                expires
                            )
                        }
                    }
                    None => bail!(
                        "Field '{}' for expires_in_seconds not found.",
                        expires_field
                    ),
                    invalid => bail!(
                        "Expected a number for field '{}' but found a {:?}",
                        expires_field,
                        invalid
                    ),
                }
            } else {
                None
            };
            Ok(TokenInfo {
                active,
                user_id,
                scope,
                expires_in_seconds: expires_in,
            })
        }
        _ => bail!(
            "Expected an object but found something else which i won't show\
             since it might contain a token."
        ),
    }
}

fn split_scopes(input: &str) -> Vec<Scope> {
    input
        .split(' ')
        .filter(|s| !s.is_empty())
        .map(Scope::new)
        .collect()
}

#[test]
fn google_v3_token_info_multiple_scopes() {
    let sample = br#"
    {
        "aud":"8819981768.apps.googleusercontent.com",
        "user_id":"123456789",
        "scope":"a b https://www.googleapis.com/auth/drive.metadata.readonly d",
        "expires_in":436
    }
    "#;

    let expected = TokenInfo {
        active: true,
        user_id: Some(UserId::new("123456789")),
        scope: vec![
            Scope::new("a"),
            Scope::new("b"),
            Scope::new("https://www.googleapis.com/auth/drive.metadata.readonly"),
            Scope::new("d"),
        ],
        expires_in_seconds: Some(436),
    };

    let token_info = GoogleV3TokenInfoParser.parse(sample).unwrap();

    assert_eq!(expected, token_info);
}

#[test]
fn google_v3_token_info_multiple_scopes_whitespaces() {
    let sample = br#"
    {
        "aud":"8819981768.apps.googleusercontent.com",
        "user_id":"123456789",
        "scope":" a     b  https://www.googleapis.com/auth/drive.metadata.readonly d   ",
        "expires_in":436
    }
    "#;

    let expected = TokenInfo {
        active: true,
        user_id: Some(UserId::new("123456789")),
        scope: vec![
            Scope::new("a"),
            Scope::new("b"),
            Scope::new("https://www.googleapis.com/auth/drive.metadata.readonly"),
            Scope::new("d"),
        ],
        expires_in_seconds: Some(436),
    };

    let token_info = GoogleV3TokenInfoParser.parse(sample).unwrap();

    assert_eq!(expected, token_info);
}
#[test]
fn amazon_token_info() {}