-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
verification.rs
2121 lines (1957 loc) · 89 KB
/
verification.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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::HashSet;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;
use chrono::{DateTime, Utc};
use oauth2::{ClientId, ClientSecret};
use serde::de::DeserializeOwned;
use serde::Serialize;
use thiserror::Error;
use crate::jwt::{JsonWebToken, JsonWebTokenJsonPayloadSerde};
use crate::user_info::UserInfoClaimsImpl;
use crate::{
AdditionalClaims, Audience, AuthenticationContextClass, GenderClaim, IdTokenClaims, IssuerUrl,
JsonWebKey, JsonWebKeySet, JsonWebKeyType, JsonWebKeyUse, JsonWebTokenAccess,
JsonWebTokenAlgorithm, JsonWebTokenHeader, JweContentEncryptionAlgorithm, JwsSigningAlgorithm,
Nonce, SubjectIdentifier,
};
pub(crate) trait AudiencesClaim {
fn audiences(&self) -> Option<&Vec<Audience>>;
}
pub(crate) trait IssuerClaim {
fn issuer(&self) -> Option<&IssuerUrl>;
}
///
/// Error verifying claims.
///
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClaimsVerificationError {
/// Claims have expired.
#[error("Expired: {0}")]
Expired(String),
/// Audience claim is invalid.
#[error("Invalid audiences: {0}")]
InvalidAudience(String),
/// Authorization context class reference (`acr`) claim is invalid.
#[error("Invalid authorization context class reference: {0}")]
InvalidAuthContext(String),
/// User authenticated too long ago.
#[error("Invalid authentication time: {0}")]
InvalidAuthTime(String),
/// Issuer claim is invalid.
#[error("Invalid issuer: {0}")]
InvalidIssuer(String),
/// Nonce is invalid.
#[error("Invalid nonce: {0}")]
InvalidNonce(String),
/// Subject claim is invalid.
#[error("Invalid subject: {0}")]
InvalidSubject(String),
/// No signature present but claims must be signed.
#[error("Claims must be signed")]
NoSignature,
/// An unexpected error occurred.
#[error("{0}")]
Other(String),
/// Failed to verify the claims signature.
#[error("Signature verification failed")]
SignatureVerification(#[source] SignatureVerificationError),
/// Unsupported argument or value.
#[error("Unsupported: {0}")]
Unsupported(String),
}
///
/// Error verifying claims signature.
///
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignatureVerificationError {
/// More than one key matches the supplied key constraints (e.g., key ID).
#[error("Ambiguous key identification: {0}")]
AmbiguousKeyId(String),
/// Invalid signature for the supplied claims and signing key.
#[error("Crypto error: {0}")]
CryptoError(String),
/// The supplied signature algorithm is disallowed by the verifier.
#[error("Disallowed signature algorithm: {0}")]
DisallowedAlg(String),
/// The supplied key cannot be used in this context. This may occur if the key type does not
/// match the signature type (e.g., an RSA key used to validate an HMAC) or the JWK usage
/// disallows signatures.
#[error("Invalid cryptographic key: {0}")]
InvalidKey(String),
/// The signing key needed for verifying the
/// [JSON Web Token](https://tools.ietf.org/html/rfc7519)'s signature/MAC could not be found.
/// This error can occur if the key ID (`kid`) specified in the JWT's
/// [JOSE header](https://tools.ietf.org/html/rfc7519#section-5) does not match the ID of any
/// key in the OpenID Connect provider's JSON Web Key Set (JWKS), typically retrieved from
/// the provider's [JWKS document](
/// http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata). To support
/// [rotation of asymmetric signing keys](
/// http://openid.net/specs/openid-connect-core-1_0.html#RotateSigKeys), client applications
/// should consider refreshing the JWKS document (via
/// [`JsonWebKeySet::fetch`][crate::JsonWebKeySet::fetch]).
///
/// This error can also occur if the identified
/// [JSON Web Key](https://tools.ietf.org/html/rfc7517) is of the wrong type (e.g., an RSA key
/// when the JOSE header specifies an ECDSA algorithm) or does not support signing.
#[error("No matching key found")]
NoMatchingKey,
/// Unsupported signature algorithm.
#[error("Unsupported signature algorithm: {0}")]
UnsupportedAlg(String),
/// An unexpected error occurred.
#[error("Other error: {0}")]
Other(String),
}
// This struct is intentionally private.
#[derive(Clone)]
struct JwtClaimsVerifier<'a, JS, JT, JU, K>
where
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
allowed_algs: Option<HashSet<JS>>,
aud_match_required: bool,
client_id: ClientId,
client_secret: Option<ClientSecret>,
iss_required: bool,
issuer: IssuerUrl,
is_signature_check_enabled: bool,
other_aud_verifier_fn: Arc<dyn Fn(&Audience) -> bool + 'a + Send + Sync>,
signature_keys: JsonWebKeySet<JS, JT, JU, K>,
}
impl<'a, JS, JT, JU, K> JwtClaimsVerifier<'a, JS, JT, JU, K>
where
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
pub fn new(
client_id: ClientId,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<JS, JT, JU, K>,
) -> Self {
JwtClaimsVerifier {
allowed_algs: Some([JS::rsa_sha_256()].iter().cloned().collect()),
aud_match_required: true,
client_id,
client_secret: None,
iss_required: true,
issuer,
is_signature_check_enabled: true,
// Secure default: reject all other audiences as untrusted, since any other audience
// can potentially impersonate the user when by sending its copy of these claims
// to this relying party.
other_aud_verifier_fn: Arc::new(|_| false),
signature_keys,
}
}
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.aud_match_required = aud_required;
self
}
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.iss_required = iss_required;
self
}
pub fn require_signature_check(mut self, sig_required: bool) -> Self {
self.is_signature_check_enabled = sig_required;
self
}
pub fn set_allowed_algs<I>(mut self, algs: I) -> Self
where
I: IntoIterator<Item = JS>,
{
self.allowed_algs = Some(algs.into_iter().collect());
self
}
pub fn allow_any_alg(mut self) -> Self {
self.allowed_algs = None;
self
}
pub fn set_client_secret(mut self, client_secret: ClientSecret) -> Self {
self.client_secret = Some(client_secret);
self
}
pub fn set_other_audience_verifier_fn<T>(mut self, other_aud_verifier_fn: T) -> Self
where
T: Fn(&Audience) -> bool + 'a + Send + Sync,
{
self.other_aud_verifier_fn = Arc::new(other_aud_verifier_fn);
self
}
fn validate_jose_header<JE>(
jose_header: &JsonWebTokenHeader<JE, JS, JT>,
) -> Result<(), ClaimsVerificationError>
where
JE: JweContentEncryptionAlgorithm<JT>,
{
// The 'typ' header field must either be omitted or have the canonicalized value JWT.
if let Some(ref jwt_type) = jose_header.typ {
if jwt_type.to_uppercase() != "JWT" {
return Err(ClaimsVerificationError::Unsupported(format!(
"unexpected or unsupported JWT type `{}`",
**jwt_type
)));
}
}
// The 'cty' header field must be omitted, since it's only used for JWTs that contain
// content types other than JSON-encoded claims. This may include nested JWTs, such as if
// JWE encryption is used. This is currently unsupported.
if let Some(ref content_type) = jose_header.cty {
if content_type.to_uppercase() == "JWT" {
return Err(ClaimsVerificationError::Unsupported(
"nested JWT's are not currently supported".to_string(),
));
} else {
return Err(ClaimsVerificationError::Unsupported(format!(
"unexpected or unsupported JWT content type `{}`",
**content_type
)));
}
}
// If 'crit' fields are specified, we must reject any we do not understand. Since this
// implementation doesn't understand any of them, unconditionally reject the JWT. Note that
// the spec prohibits this field from containing any of the standard headers or being empty.
if jose_header.crit.is_some() {
// https://tools.ietf.org/html/rfc7515#appendix-E
return Err(ClaimsVerificationError::Unsupported(
"critical JWT header fields are unsupported".to_string(),
));
}
Ok(())
}
pub fn verified_claims<A, C, JE, T>(&self, jwt: A) -> Result<T, ClaimsVerificationError>
where
A: JsonWebTokenAccess<JE, JS, JT, C, ReturnType = T>,
C: AudiencesClaim + Debug + DeserializeOwned + IssuerClaim + Serialize,
JE: JweContentEncryptionAlgorithm<JT>,
T: AudiencesClaim + IssuerClaim,
{
{
let jose_header = jwt.unverified_header();
Self::validate_jose_header(jose_header)?;
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// 1. If the ID Token is encrypted, decrypt it using the keys and algorithms that the Client
// specified during Registration that the OP was to use to encrypt the ID Token. If
// encryption was negotiated with the OP at Registration time and the ID Token is not
// encrypted, the RP SHOULD reject it.
if let JsonWebTokenAlgorithm::Encryption(ref encryption_alg) = jose_header.alg {
return Err(ClaimsVerificationError::Unsupported(format!(
"JWE encryption is not currently supported (found algorithm `{}`)",
serde_plain::to_string(encryption_alg).unwrap_or_else(|err| panic!(
"encryption alg {:?} failed to serialize to a string: {}",
encryption_alg, err
)),
)));
}
}
// TODO: Add encryption (JWE) support
{
// 2. The Issuer Identifier for the OpenID Provider (which is typically obtained during
// Discovery) MUST exactly match the value of the iss (issuer) Claim.
let unverified_claims = jwt.unverified_payload_ref();
if self.iss_required {
if let Some(issuer) = unverified_claims.issuer() {
if *issuer != self.issuer {
return Err(ClaimsVerificationError::InvalidIssuer(format!(
"expected `{}` (found `{}`)",
*self.issuer, **issuer
)));
}
} else {
return Err(ClaimsVerificationError::InvalidIssuer(
"missing issuer claim".to_string(),
));
}
}
// 3. The Client MUST validate that the aud (audience) Claim contains its client_id value
// registered at the Issuer identified by the iss (issuer) Claim as an audience. The aud
// (audience) Claim MAY contain an array with more than one element. The ID Token MUST be
// rejected if the ID Token does not list the Client as a valid audience, or if it
// contains additional audiences not trusted by the Client.
if self.aud_match_required {
if let Some(audiences) = unverified_claims.audiences() {
if !audiences
.iter()
.any(|aud| (**aud).deref() == self.client_id.deref())
{
return Err(ClaimsVerificationError::InvalidAudience(format!(
"must contain `{}` (found audiences: {})",
*self.client_id,
audiences
.iter()
.map(|aud| format!("`{}`", Deref::deref(aud)))
.collect::<Vec<_>>()
.join(", ")
)));
} else if audiences.len() > 1 {
audiences
.iter()
.filter(|aud| (**aud).deref() != self.client_id.deref())
.find(|aud| !(self.other_aud_verifier_fn)(aud))
.map(|aud| {
Err(ClaimsVerificationError::InvalidAudience(format!(
"`{}` is not a trusted audience",
**aud,
)))
})
.unwrap_or(Ok(()))?;
}
} else {
return Err(ClaimsVerificationError::InvalidAudience(
"missing audiences claim".to_string(),
));
}
}
}
// Steps 4--5 (azp claim validation) are specific to the ID token.
// 6. If the ID Token is received via direct communication between the Client and the Token
// Endpoint (which it is in this flow), the TLS server validation MAY be used to validate
// the issuer in place of checking the token signature. The Client MUST validate the
// signature of all other ID Tokens according to JWS [JWS] using the algorithm specified
// in the JWT alg Header Parameter. The Client MUST use the keys provided by the Issuer.
if !self.is_signature_check_enabled {
return Ok(jwt.unverified_payload());
}
// Borrow the header again. We had to drop the reference above to allow for the
// early exit calling jwt.unverified_claims(), which takes ownership of the JWT.
let signature_alg = match jwt.unverified_header().alg {
// Encryption is handled above.
JsonWebTokenAlgorithm::Encryption(_) => unreachable!(),
JsonWebTokenAlgorithm::Signature(ref signature_alg, _) => signature_alg,
// Section 2 of OpenID Connect Core 1.0 specifies that "ID Tokens MUST NOT use
// none as the alg value unless the Response Type used returns no ID Token from
// the Authorization Endpoint (such as when using the Authorization Code Flow)
// and the Client explicitly requested the use of none at Registration time."
//
// While there's technically a use case where this is ok, we choose not to
// support it for now to protect against accidental misuse. If demand arises,
// we can figure out a API that mitigates the risk.
JsonWebTokenAlgorithm::None => return Err(ClaimsVerificationError::NoSignature),
}
.clone();
// 7. The alg value SHOULD be the default of RS256 or the algorithm sent by the Client
// in the id_token_signed_response_alg parameter during Registration.
if let Some(ref allowed_algs) = self.allowed_algs {
if !allowed_algs.contains(&signature_alg) {
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::DisallowedAlg(format!(
"algorithm `{}` is not one of: {}",
serde_plain::to_string(&signature_alg).unwrap_or_else(|err| panic!(
"signature alg {:?} failed to serialize to a string: {}",
signature_alg, err,
)),
allowed_algs
.iter()
.map(
|alg| serde_plain::to_string(alg).unwrap_or_else(|err| panic!(
"signature alg {:?} failed to serialize to a string: {}",
alg, err,
))
)
.collect::<Vec<_>>()
.join(", "),
)),
));
}
}
// NB: We must *not* trust the 'kid' (key ID) or 'alg' (algorithm) fields present in the
// JOSE header, as an attacker could manipulate these while forging the JWT. The code
// below must be secure regardless of how these fields are manipulated.
if signature_alg.uses_shared_secret() {
// 8. If the JWT alg Header Parameter uses a MAC based algorithm such as HS256,
// HS384, or HS512, the octets of the UTF-8 representation of the client_secret
// corresponding to the client_id contained in the aud (audience) Claim are used
// as the key to validate the signature. For MAC based algorithms, the behavior
// is unspecified if the aud is multi-valued or if an azp value is present that
// is different than the aud value.
if let Some(ref client_secret) = self.client_secret {
let key = K::new_symmetric(client_secret.secret().clone().into_bytes());
return jwt
.payload(&signature_alg, &key)
.map_err(ClaimsVerificationError::SignatureVerification);
} else {
// The client secret isn't confidential for public clients, so anyone can forge a
// JWT with a valid signature.
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::DisallowedAlg(
"symmetric signatures are disallowed for public clients".to_string(),
),
));
}
}
// Section 10.1 of OpenID Connect Core 1.0 states that the JWT must include a key ID
// if the JWK set contains more than one public key.
// See if any key has a matching key ID (if supplied) and compatible type.
let public_keys = {
let jose_header = jwt.unverified_header();
self.signature_keys
.keys()
.iter()
.filter(|key|
// The key must be of the type expected for this signature algorithm.
Some(key.key_type()) == signature_alg.key_type().as_ref() &&
// Either the key hasn't specified it's allowed usage (in which case
// any usage is acceptable), or the key supports signing.
(key.key_use().is_none() ||
key.key_use().iter().any(
|key_use| key_use.allows_signature()
)) &&
// Either the JWT doesn't include a 'kid' (in which case any 'kid'
// is acceptable), or the 'kid' matches the key's ID.
(jose_header.kid.is_none() ||
jose_header.kid.as_ref() == key.key_id()))
.collect::<Vec<&K>>()
};
if public_keys.is_empty() {
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::NoMatchingKey,
));
} else if public_keys.len() != 1 {
return Err(ClaimsVerificationError::SignatureVerification(
SignatureVerificationError::AmbiguousKeyId(format!(
"JWK set must only contain one eligible public key \
({} eligible keys: {})",
public_keys.len(),
public_keys
.iter()
.map(|key| format!(
"{} ({})",
key.key_id()
.map(|kid| format!("`{}`", **kid))
.unwrap_or_else(|| "null ID".to_string()),
serde_plain::to_string(key.key_type()).unwrap_or_else(|err| panic!(
"key type {:?} failed to serialize to a string: {}",
key.key_type(),
err,
))
))
.collect::<Vec<_>>()
.join(", ")
)),
));
}
jwt.payload(
&signature_alg.clone(),
*public_keys.first().expect("unreachable"),
)
.map_err(ClaimsVerificationError::SignatureVerification)
// Steps 9--13 are specific to the ID token.
}
}
///
/// Trait for verifying ID token nonces.
///
pub trait NonceVerifier {
///
/// Verifies the nonce.
///
/// Returns `Ok(())` if the nonce is valid, or a string describing the error otherwise.
///
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String>;
}
impl NonceVerifier for &Nonce {
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String> {
if let Some(claims_nonce) = nonce {
// Nonce::eq is already implemented with a constant time comparison
if claims_nonce != self {
return Err("nonce mismatch".to_string());
}
} else {
return Err("missing nonce claim".to_string());
}
Ok(())
}
}
impl<F> NonceVerifier for F
where
F: FnOnce(Option<&Nonce>) -> Result<(), String>,
{
fn verify(self, nonce: Option<&Nonce>) -> Result<(), String> {
self(nonce)
}
}
///
/// ID token verifier.
///
#[derive(Clone)]
pub struct IdTokenVerifier<'a, JS, JT, JU, K>
where
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
acr_verifier_fn:
Arc<dyn Fn(Option<&AuthenticationContextClass>) -> Result<(), String> + 'a + Send + Sync>,
#[allow(clippy::type_complexity)]
auth_time_verifier_fn:
Arc<dyn Fn(Option<DateTime<Utc>>) -> Result<(), String> + 'a + Send + Sync>,
iat_verifier_fn: Arc<dyn Fn(DateTime<Utc>) -> Result<(), String> + 'a + Send + Sync>,
jwt_verifier: JwtClaimsVerifier<'a, JS, JT, JU, K>,
time_fn: Arc<dyn Fn() -> DateTime<Utc> + 'a + Send + Sync>,
}
impl<'a, JS, JT, JU, K> IdTokenVerifier<'a, JS, JT, JU, K>
where
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
fn new(jwt_verifier: JwtClaimsVerifier<'a, JS, JT, JU, K>) -> Self {
IdTokenVerifier {
// By default, accept authorization context reference (acr claim).
acr_verifier_fn: Arc::new(|_| Ok(())),
auth_time_verifier_fn: Arc::new(|_| Ok(())),
// By default, accept any issued time (iat claim).
iat_verifier_fn: Arc::new(|_| Ok(())),
jwt_verifier,
// By default, use the current system time.
time_fn: Arc::new(Utc::now),
}
}
///
/// Initializes a new verifier for a public client (i.e., one without a client secret).
///
pub fn new_public_client(
client_id: ClientId,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<JS, JT, JU, K>,
) -> Self {
Self::new(JwtClaimsVerifier::new(client_id, issuer, signature_keys))
}
///
/// Initializes a no-op verifier that performs no signature, audience, or issuer verification.
/// The token's expiration time is still checked, and the token is otherwise required to conform to the expected format.
///
pub fn new_insecure_without_verification() -> Self {
let empty_issuer = IssuerUrl::new("https://0.0.0.0".to_owned())
.expect("Creating empty issuer url mustn't fail");
Self::new_public_client(
ClientId::new(String::new()),
empty_issuer,
JsonWebKeySet::new(vec![]),
)
.insecure_disable_signature_check()
.require_audience_match(false)
.require_issuer_match(false)
}
///
/// Initializes a new verifier for a confidential client (i.e., one with a client secret).
///
/// A confidential client verifier is required in order to verify ID tokens signed using a
/// shared secret algorithm such as `HS256`, `HS384`, or `HS512`. For these algorithms, the
/// client secret is the shared secret.
///
pub fn new_confidential_client(
client_id: ClientId,
client_secret: ClientSecret,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<JS, JT, JU, K>,
) -> Self {
Self::new(
JwtClaimsVerifier::new(client_id, issuer, signature_keys)
.set_client_secret(client_secret),
)
}
///
/// Specifies which JSON Web Signature algorithms are supported.
///
pub fn set_allowed_algs<I>(mut self, algs: I) -> Self
where
I: IntoIterator<Item = JS>,
{
self.jwt_verifier = self.jwt_verifier.set_allowed_algs(algs);
self
}
///
/// Specifies that any signature algorithm is supported.
///
pub fn allow_any_alg(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.allow_any_alg();
self
}
///
/// Specifies a function for verifying the `acr` claim.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
///
pub fn set_auth_context_verifier_fn<T>(mut self, acr_verifier_fn: T) -> Self
where
T: Fn(Option<&AuthenticationContextClass>) -> Result<(), String> + 'a + Send + Sync,
{
self.acr_verifier_fn = Arc::new(acr_verifier_fn);
self
}
///
/// Specifies a function for verifying the `auth_time` claim.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
///
pub fn set_auth_time_verifier_fn<T>(mut self, auth_time_verifier_fn: T) -> Self
where
T: Fn(Option<DateTime<Utc>>) -> Result<(), String> + 'a + Send + Sync,
{
self.auth_time_verifier_fn = Arc::new(auth_time_verifier_fn);
self
}
///
/// Enables signature verification.
///
/// Signature verification is enabled by default, so this function is only useful if
/// [`IdTokenVerifier::insecure_disable_signature_check`] was previously invoked.
///
pub fn enable_signature_check(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.require_signature_check(true);
self
}
///
/// Disables signature verification.
///
/// # Security Warning
///
/// Unverified ID tokens may be subject to forgery. See [Section 16.3](
/// https://openid.net/specs/openid-connect-core-1_0.html#TokenManufacture) for more
/// information.
///
pub fn insecure_disable_signature_check(mut self) -> Self {
self.jwt_verifier = self.jwt_verifier.require_signature_check(false);
self
}
///
/// Specifies whether the issuer claim must match the expected issuer URL for the provider.
///
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_issuer_match(iss_required);
self
}
///
/// Specifies whether the audience claim must match this client's client ID.
///
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_audience_match(aud_required);
self
}
///
/// Specifies a function for returning the current time.
///
/// This function is used for verifying the ID token expiration time.
///
pub fn set_time_fn<T>(mut self, time_fn: T) -> Self
where
T: Fn() -> DateTime<Utc> + 'a + Send + Sync,
{
self.time_fn = Arc::new(time_fn);
self
}
///
/// Specifies a function for verifying the ID token issue time.
///
/// The function should return `Ok(())` if the claim is valid, or a string describing the error
/// otherwise.
///
pub fn set_issue_time_verifier_fn<T>(mut self, iat_verifier_fn: T) -> Self
where
T: Fn(DateTime<Utc>) -> Result<(), String> + 'a + Send + Sync,
{
self.iat_verifier_fn = Arc::new(iat_verifier_fn);
self
}
///
/// Specifies a function for verifying audiences included in the `aud` claim that differ from
/// this client's client ID.
///
/// The function should return `true` if the audience is trusted, or `false` otherwise.
///
/// [Section 3.1.3.7](https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
/// states that *"The ID Token MUST be rejected if the ID Token does not list the Client as a
/// valid audience, or if it contains additional audiences not trusted by the Client."*
///
pub fn set_other_audience_verifier_fn<T>(mut self, other_aud_verifier_fn: T) -> Self
where
T: Fn(&Audience) -> bool + 'a + Send + Sync,
{
self.jwt_verifier = self
.jwt_verifier
.set_other_audience_verifier_fn(other_aud_verifier_fn);
self
}
pub(super) fn verified_claims<'b, AC, GC, JE, N>(
&self,
jwt: &'b JsonWebToken<JE, JS, JT, IdTokenClaims<AC, GC>, JsonWebTokenJsonPayloadSerde>,
nonce_verifier: N,
) -> Result<&'b IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<JT>,
N: NonceVerifier,
{
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// Steps 1--3 are handled by the generic JwtClaimsVerifier.
let partially_verified_claims = self.jwt_verifier.verified_claims(jwt)?;
self.verify_claims(partially_verified_claims, nonce_verifier)?;
Ok(partially_verified_claims)
}
pub(super) fn verified_claims_owned<AC, GC, JE, N>(
&self,
jwt: JsonWebToken<JE, JS, JT, IdTokenClaims<AC, GC>, JsonWebTokenJsonPayloadSerde>,
nonce_verifier: N,
) -> Result<IdTokenClaims<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
JE: JweContentEncryptionAlgorithm<JT>,
N: NonceVerifier,
{
// The code below roughly follows the validation steps described in
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
// Steps 1--3 are handled by the generic JwtClaimsVerifier.
let partially_verified_claims = self.jwt_verifier.verified_claims(jwt)?;
self.verify_claims(&partially_verified_claims, nonce_verifier)?;
Ok(partially_verified_claims)
}
fn verify_claims<AC, GC, N>(
&self,
partially_verified_claims: &'_ IdTokenClaims<AC, GC>,
nonce_verifier: N,
) -> Result<(), ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
N: NonceVerifier,
{
// 4. If the ID Token contains multiple audiences, the Client SHOULD verify that an azp
// Claim is present.
// There is significant confusion and contradiction in the OpenID Connect Core spec around
// the azp claim. See https://bitbucket.org/openid/connect/issues/973/ for a detailed
// discussion. Given the lack of clarity around how this claim should be used, we defer
// any verification of it here until a use case becomes apparent. If such a use case does
// arise, we most likely want to allow clients to pass in a function for validating the
// azp claim rather than introducing logic that affects all clients of this library.
// This naive implementation of the spec would almost certainly not be useful in practice:
/*
let azp_required = partially_verified_claims.audiences().len() > 1;
// 5. If an azp (authorized party) Claim is present, the Client SHOULD verify that its
// client_id is the Claim Value.
if let Some(authorized_party) = partially_verified_claims.authorized_party() {
if *authorized_party != self.client_id {
return Err(ClaimsVerificationError::InvalidAudience(format!(
"authorized party must match client ID `{}` (found `{}`",
*self.client_id, **authorized_party
)));
}
} else if azp_required {
return Err(ClaimsVerificationError::InvalidAudience(format!(
"missing authorized party claim but multiple audiences found"
)));
}
*/
// Steps 6--8 are handled by the generic JwtClaimsVerifier.
// 9. The current time MUST be before the time represented by the exp Claim.
let cur_time = (*self.time_fn)();
if cur_time >= partially_verified_claims.expiration() {
return Err(ClaimsVerificationError::Expired(format!(
"ID token expired at {} (current time is {})",
partially_verified_claims.expiration(),
cur_time
)));
}
// 10. The iat Claim can be used to reject tokens that were issued too far away from the
// current time, limiting the amount of time that nonces need to be stored to prevent
// attacks. The acceptable range is Client specific.
(*self.iat_verifier_fn)(partially_verified_claims.issue_time())
.map_err(ClaimsVerificationError::Expired)?;
// 11. If a nonce value was sent in the Authentication Request, a nonce Claim MUST be
// present and its value checked to verify that it is the same value as the one that was
// sent in the Authentication Request. The Client SHOULD check the nonce value for
// replay attacks. The precise method for detecting replay attacks is Client specific.
nonce_verifier
.verify(partially_verified_claims.nonce())
.map_err(ClaimsVerificationError::InvalidNonce)?;
// 12. If the acr Claim was requested, the Client SHOULD check that the asserted Claim Value
// is appropriate. The meaning and processing of acr Claim Values is out of scope for
// this specification.
(*self.acr_verifier_fn)(partially_verified_claims.auth_context_ref())
.map_err(ClaimsVerificationError::InvalidAuthContext)?;
// 13. If the auth_time Claim was requested, either through a specific request for this
// Claim or by using the max_age parameter, the Client SHOULD check the auth_time Claim
// value and request re-authentication if it determines too much time has elapsed since
// the last End-User authentication.
(*self.auth_time_verifier_fn)(partially_verified_claims.auth_time())
.map_err(ClaimsVerificationError::InvalidAuthTime)?;
Ok(())
}
}
///
/// User info verifier.
///
#[derive(Clone)]
pub struct UserInfoVerifier<'a, JE, JS, JT, JU, K>
where
JE: JweContentEncryptionAlgorithm<JT>,
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
jwt_verifier: JwtClaimsVerifier<'a, JS, JT, JU, K>,
expected_subject: Option<SubjectIdentifier>,
_phantom: PhantomData<JE>,
}
impl<'a, JE, JS, JT, JU, K> UserInfoVerifier<'a, JE, JS, JT, JU, K>
where
JE: JweContentEncryptionAlgorithm<JT>,
JS: JwsSigningAlgorithm<JT>,
JT: JsonWebKeyType,
JU: JsonWebKeyUse,
K: JsonWebKey<JS, JT, JU>,
{
///
/// Instantiates a user info verifier.
///
pub fn new(
client_id: ClientId,
issuer: IssuerUrl,
signature_keys: JsonWebKeySet<JS, JT, JU, K>,
expected_subject: Option<SubjectIdentifier>,
) -> Self {
UserInfoVerifier {
jwt_verifier: JwtClaimsVerifier::new(client_id, issuer, signature_keys),
expected_subject,
_phantom: PhantomData,
}
}
pub(crate) fn expected_subject(&self) -> Option<&SubjectIdentifier> {
self.expected_subject.as_ref()
}
///
/// Specifies whether the issuer claim must match the expected issuer URL for the provider.
///
pub fn require_issuer_match(mut self, iss_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_issuer_match(iss_required);
self
}
///
/// Specifies whether the audience claim must match this client's client ID.
///
pub fn require_audience_match(mut self, aud_required: bool) -> Self {
self.jwt_verifier = self.jwt_verifier.require_audience_match(aud_required);
self
}
pub(crate) fn verified_claims<AC, GC>(
&self,
user_info_jwt: JsonWebToken<
JE,
JS,
JT,
UserInfoClaimsImpl<AC, GC>,
JsonWebTokenJsonPayloadSerde,
>,
) -> Result<UserInfoClaimsImpl<AC, GC>, ClaimsVerificationError>
where
AC: AdditionalClaims,
GC: GenderClaim,
{
let user_info = self.jwt_verifier.verified_claims(user_info_jwt)?;
if self
.expected_subject
.iter()
.all(|expected_subject| user_info.standard_claims.sub == *expected_subject)
{
Ok(user_info)
} else {
Err(ClaimsVerificationError::InvalidSubject(format!(
"expected `{}` (found `{}`)",
// This can only happen when self.expected_subject is not None.
self.expected_subject.as_ref().unwrap().as_str(),
user_info.standard_claims.sub.as_str()
)))
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use chrono::{TimeZone, Utc};
use oauth2::{ClientId, ClientSecret};
use super::{
AudiencesClaim, ClaimsVerificationError, IssuerClaim, JsonWebTokenHeader,
JwtClaimsVerifier, SignatureVerificationError, SubjectIdentifier,
};
use crate::core::{
CoreIdToken, CoreIdTokenClaims, CoreIdTokenVerifier, CoreJsonWebKey, CoreJsonWebKeySet,
CoreJsonWebKeyType, CoreJsonWebKeyUse, CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm, CoreRsaPrivateSigningKey, CoreUserInfoClaims,
CoreUserInfoJsonWebToken, CoreUserInfoVerifier,
};
use crate::jwt::tests::{TEST_RSA_PRIV_KEY, TEST_RSA_PUB_KEY};
use crate::jwt::{JsonWebToken, JsonWebTokenJsonPayloadSerde};
use crate::types::helpers::timestamp_to_utc;
use crate::types::Base64UrlEncodedBytes;
use crate::types::Timestamp;
use crate::{
AccessToken, Audience, AuthenticationContextClass, AuthorizationCode, EndUserName,
IssuerUrl, JsonWebKeyId, Nonce, StandardClaims, UserInfoError,
};
type CoreJsonWebTokenHeader = JsonWebTokenHeader<
CoreJweContentEncryptionAlgorithm,
CoreJwsSigningAlgorithm,
CoreJsonWebKeyType,
>;
type CoreJwtClaimsVerifier<'a> = JwtClaimsVerifier<
'a,
CoreJwsSigningAlgorithm,
CoreJsonWebKeyType,
CoreJsonWebKeyUse,
CoreJsonWebKey,
>;
fn assert_unsupported<T>(result: Result<T, ClaimsVerificationError>, expected_substr: &str) {
match result {
Err(ClaimsVerificationError::Unsupported(msg)) => {
assert!(msg.contains(expected_substr))
}