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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
use serde_json::value::Value;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::SystemTime;

#[cfg(feature = "matching")]
use regex::Regex;
#[cfg(feature = "matching")]
use std::fmt;
#[cfg(feature = "matching")]
use std::hash::{Hash, Hasher};
#[cfg(feature = "matching")]
use std::ops::Deref;

use crate::crypto::algorithm::Algorithm;
use crate::error::{Error, ErrorDetails};
use crate::raw::*;
use crate::TokenData;

// Regex doesn't implement PartialEq, Eq or Hash so we nee a wrapper...
#[cfg(feature = "matching")]
#[derive(Debug, Clone)]
struct Pattern(Regex);

#[cfg(feature = "matching")]
impl Deref for Pattern {
    type Target = Regex;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
#[cfg(feature = "matching")]
impl fmt::Display for Pattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}
#[cfg(feature = "matching")]
impl PartialEq for Pattern {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}
#[cfg(feature = "matching")]
impl Eq for Pattern {}
#[cfg(feature = "matching")]
impl Hash for Pattern {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.as_str().hash(state);
    }
}

#[derive(Clone)]
struct VerifierClosure {
    func: Arc<dyn Send + Sync + Fn(&serde_json::value::Value) -> bool>,
}
impl Eq for VerifierClosure {}
impl PartialEq for VerifierClosure {
    fn eq(&self, other: &Self) -> bool {
        return Arc::ptr_eq(&self.func, &other.func);
    }
}

#[derive(Clone, PartialEq, Eq)]
enum VerifierKind {
    Closure(VerifierClosure),

    StringConstant(String),
    StringSet(HashSet<String>),

    #[cfg(feature = "matching")]
    StringPattern(Pattern),
    #[cfg(feature = "matching")]
    StringPatternSet(HashSet<Pattern>),

    StringOrArrayContains(String)
}

/// Immutable requirements for checking token claims
#[derive(Clone)]
pub struct Verifier {
    leeway: u32,
    ignore_exp: bool,
    ignore_nbf: bool,
    ignore_iat: bool,

    claim_verifiers: HashMap<String, VerifierKind>,
}

impl Verifier {
    /// Start constructing a Verifier and configuring what claims should be verified.
    pub fn create() -> VerifierBuilder {
        VerifierBuilder::new()
    }

    /// Verifies a token's claims but does not look at any header or verify any signature
    pub fn verify_claims_only(
        &self,
        claims: &serde_json::value::Value,
        time_now: u64,
    ) -> Result<(), Error> {
        let claims = match claims {
            serde_json::value::Value::Object(map) => map,
            _ => {
                return Err(Error::MalformedToken(ErrorDetails::new(
                    "Expected claims to be a JSON object",
                )))
            }
        };

        if !self.ignore_iat {
            match claims.get("iat") {
                Some(serde_json::value::Value::Number(number)) => {
                    if let Some(iat) = number.as_u64() {
                        if iat > time_now + (self.leeway as u64) {
                            return Err(Error::MalformedToken(ErrorDetails::new(
                                "Issued with a future 'iat' time",
                            )));
                        }
                    } else {
                        return Err(Error::MalformedToken(ErrorDetails::new(
                            "Failed to parse 'iat' as an integer",
                        )));
                    }
                }
                Some(_) => {
                    return Err(Error::MalformedToken(ErrorDetails::new(
                        "Given 'iat' not a number",
                    )));
                }
                None => {}
            }
        }

        if !self.ignore_nbf {
            match claims.get("nbf") {
                Some(serde_json::value::Value::Number(number)) => {
                    if let Some(nbf) = number.as_u64() {
                        if nbf > time_now + (self.leeway as u64) {
                            return Err(Error::MalformedToken(ErrorDetails::new(
                                "Time is before 'nbf'",
                            )));
                        }
                    } else {
                        return Err(Error::MalformedToken(ErrorDetails::new(
                            "Failed to parse 'nbf' as an integer",
                        )));
                    }
                }
                Some(_) => {
                    return Err(Error::MalformedToken(ErrorDetails::new(
                        "Given 'nbf' not a number",
                    )));
                }
                None => {}
            }
        }

        if !self.ignore_exp {
            match claims.get("exp") {
                Some(serde_json::value::Value::Number(number)) => {
                    if let Some(exp) = number.as_u64() {
                        if exp <= time_now - (self.leeway as u64) {
                            return Err(Error::TokenExpiredAt(exp));
                        }
                    } else {
                        return Err(Error::MalformedToken(ErrorDetails::new(
                            "Failed to parse 'exp' as an integer",
                        )));
                    }
                }
                Some(_) => {
                    return Err(Error::MalformedToken(ErrorDetails::new(
                        "Given 'exp' not a number",
                    )));
                }
                None => {}
            }
        }

        // At least verify the type for these standard claims
        // (Values can separately be validated via .claim_verifiers)
        for &string_claim in &["iss", "sub"] {
            match claims.get(string_claim) {
                Some(serde_json::value::Value::String(_)) => {}
                Some(_) => {
                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                        "Given '{}' not a string",
                        string_claim
                    ))));
                }
                None => {}
            }
        }

        for &string_or_array in &["aud"] {
            match claims.get(string_or_array) {
                Some(serde_json::value::Value::String(_)) => {},
                Some(serde_json::value::Value::Array(claim_array)) => {
                    for subclaim in claim_array {
                        if !subclaim.is_string() {
                            return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                "Claim {}: array elements are not all strings",
                                string_or_array
                            ))));
                        }
                    }
                },
                Some(_) => {
                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                        "Given '{}' not a string or an array of strings",
                        string_or_array
                    ))));
                }
                None => {}
            }
        }

        let verifiers = &self.claim_verifiers;

        for (claim_key, claim_verifier) in verifiers.iter() {
            match claims.get(claim_key) {
                Some(claim_value) => {
                    if let VerifierKind::Closure(closure_container) = claim_verifier {
                        let closure = closure_container.func.as_ref();
                        if !closure(claim_value) {
                            return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                "Claim {}: verifier callback returned false for '{}'",
                                claim_key, claim_value
                            ))));
                        }
                    } else if let Value::String(claim_string) = claim_value {
                        match claim_verifier {
                            VerifierKind::StringConstant(constant) => {
                                if claim_string != constant {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: {} != {}",
                                        claim_key, claim_string, constant
                                    ))));
                                }
                            }
                            VerifierKind::StringSet(constant_set) => {
                                if !constant_set.contains(claim_string) {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: {} not in set",
                                        claim_key, claim_string
                                    ))));
                                }
                            }
                            #[cfg(feature = "matching")]
                            VerifierKind::StringPattern(pattern) => {
                                if !pattern.is_match(claim_string) {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: {} doesn't match regex {}",
                                        claim_key, claim_string, pattern
                                    ))));
                                }
                            }
                            #[cfg(feature = "matching")]
                            VerifierKind::StringPatternSet(pattern_set) => {
                                let mut found_match = false;
                                for p in pattern_set {
                                    if p.is_match(claim_string) {
                                        found_match = true;
                                        break;
                                    }
                                }
                                if !found_match {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: {} doesn't match regex set",
                                        claim_key, claim_string
                                    ))));
                                }
                            }
                            VerifierKind::StringOrArrayContains(contains) => {
                                 if claim_string != contains {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: {} != {}",
                                        claim_key, claim_string, contains
                                    ))));
                                }
                            }
                            _ => {
                                return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                    "Claim {}: has unexpected type (String)",
                                    claim_key
                                ))));
                            }
                        }
                    } else if let Value::Array(claim_array) = claim_value {
                        match claim_verifier {
                            VerifierKind::StringOrArrayContains(contains) => {
                                let mut found = false;
                                for subclaim in claim_array {
                                    match subclaim {
                                        Value::String(subclaim_string) => {
                                            if subclaim_string == contains {
                                                found = true;
                                                // XXX: don't break from loop early since we want to
                                                // check _all_ array elements are strings
                                            }
                                        }
                                        _ => {
                                            return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                                "Claim {}: array elements are not all strings",
                                                claim_key
                                            ))));
                                        }
                                    }
                                }
                                if !found {
                                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                        "Claim {}: array did not contain '{}'",
                                        claim_key, contains
                                    ))));
                                }
                            },
                            _ => {
                                return Err(Error::MalformedToken(ErrorDetails::new(format!(
                                    "Claim {}: has unexpected type (Array)",
                                    claim_key
                                ))));
                            }
                        }
                    } else if let Value::Number(_claim_number) = claim_value {
                        // TODO: support verifying numeric claims
                        return Err(Error::MalformedToken(ErrorDetails::new(format!(
                            "Claim {}: has unexpected type (Number)",
                            claim_key
                        ))));
                    } else {
                        return Err(Error::MalformedToken(ErrorDetails::new(format!(
                            "Claim {}: has unexpected type",
                            claim_key
                        ))));
                    }
                }
                _ => {
                    // If we have a verifier for particular claim then that claim is required
                    return Err(Error::MalformedToken(ErrorDetails::new(format!(
                        "Claim {}: missing",
                        claim_key
                    ))));
                }
            }
        }
        Ok(())
    }

    /// Verify a token's signature and its claims, given a specific unix epoch timestamp
    pub fn verify_for_time(
        &self,
        token: impl AsRef<str>,
        algorithm: &Algorithm,
        time_now: u64,
    ) -> Result<TokenData, Error> {
        let TokenSlices {
            message,
            signature,
            header,
            claims,
        } = split_token(token.as_ref())?;

        let header = decode_json_token_slice(header)?;
        verify_signature_only(&header, message, signature, algorithm)?;
        let claims = decode_json_token_slice(claims)?;
        self.verify_claims_only(&claims, time_now)?;

        Ok(TokenData {
            header: header,
            claims: claims,
            _extensible: (),
        })
    }

    /// Verify a token's signature and its claims
    pub fn verify(
        &self,
        token: impl AsRef<str>,
        algorithm: &Algorithm,
    ) -> Result<serde_json::value::Value, Error> {
        let timestamp = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
            Ok(n) => n.as_secs(),
            Err(_) => {
                return Err(Error::InvalidInput(ErrorDetails::new(
                    "SystemTime before UNIX EPOCH!",
                )))
            }
        };

        match self.verify_for_time(token.as_ref(), algorithm, timestamp) {
            Ok(data) => Ok(data.claims),
            Err(error) => Err(error),
        }
    }
}

/// Configures the requirements for checking token claims with a builder-pattern API
pub struct VerifierBuilder {
    leeway: u32,
    ignore_exp: bool,
    ignore_nbf: bool,
    ignore_iat: bool,

    claim_verifiers: HashMap<String, VerifierKind>,
}

impl VerifierBuilder {
    pub fn new() -> VerifierBuilder {
        VerifierBuilder {
            leeway: 0,
            ignore_exp: false,
            ignore_nbf: false,
            ignore_iat: false,
            claim_verifiers: HashMap::new(),
        }
    }

    /// Convenience for string_equals("iss", "value")
    pub fn issuer(&mut self, issuer: impl Into<String>) -> &mut Self {
        self.string_equals("iss", issuer)
    }

    /// Convenience for string_or_array_contains("aud", "value")
    pub fn audience(&mut self, aud: impl Into<String>) -> &mut Self {
        self.string_or_array_contains("aud", aud)
    }

    /// Convenience for string_equals("sub", "value")
    pub fn subject(&mut self, sub: impl Into<String>) -> &mut Self {
        self.string_equals("sub", sub)
    }

    /// Convenience for string_equals("nonce", "value")
    pub fn nonce(&mut self, nonce: impl Into<String>) -> &mut Self {
        self.string_equals("nonce", nonce)
    }

    /// Check that a claim has a specific string value
    pub fn string_equals(
        &mut self,
        claim: impl Into<String>,
        value: impl Into<String>,
    ) -> &mut Self {
        self.claim_verifiers
            .insert(claim.into(), VerifierKind::StringConstant(value.into()));
        self
    }

    /// Check that a claim equals one of the given string values
    pub fn string_equals_one_of(&mut self, claim: impl Into<String>, values: &[&str]) -> &mut Self {
        let hash_set: HashSet<String> = values.into_iter().cloned().map(|s| s.to_owned()).collect();
        self.claim_verifiers
            .insert(claim.into(), VerifierKind::StringSet(hash_set));
        self
    }

    /// Check that the claim matches the given regular expression
    #[cfg(feature = "matching")]
    pub fn string_matches(
        &mut self,
        claim: impl Into<String>,
        value: impl Into<Regex>,
    ) -> &mut Self {
        self.claim_verifiers.insert(
            claim.into(),
            VerifierKind::StringPattern(Pattern(value.into())),
        );
        self
    }

    // Maybe this could be more ergonomic if it took &[&str] strings but then we'd have to
    // defer compiling the regular expressions until .build() which would be a bit of a pain

    /// Check that the claim matches one of the given regular expressions
    #[cfg(feature = "matching")]
    pub fn string_matches_one_of(
        &mut self,
        claim: impl Into<String>,
        values: &[Regex],
    ) -> &mut Self {
        let hash_set: HashSet<Pattern> = values.into_iter().cloned().map(|r| Pattern(r)).collect();
        self.claim_verifiers
            .insert(claim.into(), VerifierKind::StringPatternSet(hash_set));
        self
    }

    pub fn string_or_array_contains(
        &mut self,
        claim: impl Into<String>,
        value: impl Into<String>
    ) -> &mut Self {
        self.claim_verifiers.insert(
            claim.into(),
            VerifierKind::StringOrArrayContains(value.into())
        );
        self
    }

    /// Sets a leeway (in seconds) should be allowed when checking exp, nbf and iat claims
    pub fn leeway(&mut self, leeway: u32) -> &mut Self {
        self.leeway = leeway;
        self
    }

    /// Don't check the 'exp' expiry claim
    pub fn ignore_exp(&mut self) -> &mut Self {
        self.ignore_exp = true;
        self
    }

    /// Don't check the 'nbf' not before claim
    pub fn ignore_nbf(&mut self) -> &mut Self {
        self.ignore_nbf = true;
        self
    }

    /// Don't check the 'iat' issued at claim
    pub fn ignore_iat(&mut self) -> &mut Self {
        self.ignore_iat = true;
        self
    }

    /// Check a claim `Value` manually, returning `true` if ok, else `false`
    pub fn claim_callback(
        &mut self,
        claim: impl Into<String>,
        func: impl Send + Sync + Fn(&serde_json::value::Value) -> bool + 'static,
    ) -> &mut Self {
        let closure_verifier = VerifierClosure {
            func: Arc::new(func),
        };
        self.claim_verifiers
            .insert(claim.into(), VerifierKind::Closure(closure_verifier));
        self
    }

    /// Build the final Verifier
    pub fn build(&self) -> Result<Verifier, Error> {
        Ok(Verifier {
            leeway: self.leeway,
            ignore_exp: self.ignore_exp,
            ignore_nbf: self.ignore_nbf,
            ignore_iat: self.ignore_iat,
            claim_verifiers: self.claim_verifiers.clone(),
        })
    }
}