iap-jwt 0.4.0

Validate and decode Google Cloud Identity-Aware Proxy (IAP) JWTs
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
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
use std::{collections::HashMap, time::SystemTime};

use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

const IAP_ISSUER: &str = "https://cloud.google.com/iap";

#[cfg(all(not(feature = "aws_lc_rs"), not(feature = "rust_crypto")))]
compile_error!("Either aws_lc_rs or rust_crypto feature must be enabled");

/// The claims in a JWT issued by Google IAP.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Claims {
    pub exp: u64,
    pub iat: u64,
    pub aud: String,
    pub iss: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hd: Option<String>,
    pub sub: String,
    pub email: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub google: Option<Value>,
}

/// The error returned by the `decode_and_validate` method.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    #[error("Invalid kid: {0}")]
    InvalidKid(String),
    #[error("Invalid alg: {0}, must be ES256")]
    InvalidAlgorithm(String),
    #[error("Invalid aud: {actual}, expected {expected}")]
    InvalidAudience { actual: String, expected: String },
    #[error("Invalid issuer: {0}, expected {IAP_ISSUER}")]
    InvalidIssuer(String),
    #[error("Invalid key format")]
    InvalidKeyFormat,
    #[error(transparent)]
    JsonWebToken(#[from] jsonwebtoken::errors::Error),
    #[error("Request failed: {0}")]
    RequestFailed(Box<dyn std::error::Error + Send + 'static>),
    #[error("Kid not available in header")]
    KidNotAvailable,
    #[error("Invalid iat: {actual} > {expected}")]
    FutureIat { actual: u64, expected: u64 },
    #[error("Invalid hosted domain: {actual}, expected {expected:?}")]
    InvalidHostedDomain {
        actual: String,
        expected: Vec<String>,
    },
    #[error("hd claim is missing, expected {expected:?}")]
    HdClaimMissing { expected: Vec<String> },
    #[error("Insufficient access level, expected {0}")]
    InsufficientAccessLevel(String),
    #[error("Access levels claim is missing")]
    AccessLevelsMissing,
    #[error("Invalid google claims")]
    InvalidGoogleClaims,
    #[error("Token lifetime too long: iat: {iat}, exp: {exp}, max_lifetime: {max_lifetime}")]
    TokenLifetimeTooLong {
        iat: u64,
        exp: u64,
        max_lifetime: u64,
    },
}

/// Configures validation options for JWT issued by Google IAP.
///
/// # Validation Options
///
/// - By default, validates the audience claim against the provided list.
/// - `with_google_hosted_domain`: Additionally validates the `hd` (hosted domain) claim.
/// - `with_access_levels`: Additionally validates the access levels claim in the Google-specific payload.
pub struct ValidationConfig {
    audience: Vec<String>,
    /// "If an account belongs to a hosted domain, the hd claim is provided to differentiate the domain the account is associated with." - https://cloud.google.com/iap/docs/signed-headers-howto
    google_hosted_domain: Option<Vec<String>>,
    access_levels: Option<Vec<String>>,
    /// Time skew tolerance in seconds
    skew: u64,
    /// Maximum token lifetime in seconds
    max_token_lifetime: u64,
}

impl ValidationConfig {
    /// Creates a new validation config with the given audience.
    ///
    /// By default, validates the audience claim against the provided list.
    pub fn new<A, I>(audience: I) -> Self
    where
        A: Into<String>,
        I: IntoIterator<Item = A>,
    {
        Self {
            audience: audience.into_iter().map(Into::into).collect(),
            google_hosted_domain: None,
            access_levels: None,
            skew: 30,                         // Default value: 30 seconds
            max_token_lifetime: 600 + 2 * 30, // Default value: 10 minutes + 2 * skew
        }
    }

    /// Validates that the hd claim is in the list of google hosted domains.
    ///
    /// "If an account belongs to a hosted domain, the hd claim is provided to differentiate the domain the account is associated with." - https://cloud.google.com/iap/docs/signed-headers-howto
    pub fn with_google_hosted_domain<H, I>(mut self, google_hosted_domain: I) -> Self
    where
        H: Into<String>,
        I: IntoIterator<Item = H>,
    {
        self.google_hosted_domain =
            Some(google_hosted_domain.into_iter().map(Into::into).collect());
        self
    }

    /// Validates that the access levels claim contains all the access levels in the config.
    pub fn with_access_levels<T: Into<String>>(
        mut self,
        access_levels: impl IntoIterator<Item = T>,
    ) -> Self {
        self.access_levels = Some(access_levels.into_iter().map(Into::into).collect());
        self
    }

    /// Decode and validate a jwt with respect to the IAP documentation: https://cloud.google.com/iap/docs/signed-headers-howto
    pub async fn decode_and_validate<E: std::error::Error + Send + 'static>(
        &self,
        token: &str,
        client: &impl PublicKeySource<Error = E>,
    ) -> Result<Claims, Error> {
        let header = decode_header(token)?;
        let kid = header.kid.ok_or(Error::KidNotAvailable)?;
        let public_key = client
            .get_public_key(&kid)
            .await
            .map_err(|e| Error::RequestFailed(Box::new(e)))?
            .ok_or_else(|| Error::InvalidKid(kid))?;
        let mut validation = Validation::new(Algorithm::ES256);
        validation.set_audience(&self.audience);
        validation.set_issuer(&[IAP_ISSUER]);
        validation.leeway = self.skew;

        let token = decode::<Claims>(
            token,
            &DecodingKey::from_ec_pem(public_key.as_bytes())
                .map_err(|_| Error::InvalidKeyFormat)?,
            &validation,
        )?;

        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Validate iat (considering skew)
        if token.claims.iat > now + self.skew {
            return Err(Error::FutureIat {
                actual: token.claims.iat,
                expected: now,
            });
        }

        // Validate maximum token lifetime
        if token.claims.exp > token.claims.iat + self.max_token_lifetime {
            return Err(Error::TokenLifetimeTooLong {
                iat: token.claims.iat,
                exp: token.claims.exp,
                max_lifetime: self.max_token_lifetime,
            });
        }

        if let Some(expected_hd) = &self.google_hosted_domain {
            let Some(hd) = &token.claims.hd else {
                return Err(Error::HdClaimMissing {
                    expected: expected_hd.clone(),
                });
            };
            if !expected_hd.contains(hd) {
                return Err(Error::InvalidHostedDomain {
                    actual: hd.clone(),
                    expected: expected_hd.clone(),
                });
            }
        }

        if let Some(expected_access_levels) = &self.access_levels {
            #[derive(Deserialize)]
            struct GoogleClaims {
                access_levels: Vec<String>,
            }
            let google: GoogleClaims = serde_json::from_value(
                token
                    .claims
                    .google
                    .as_ref()
                    .ok_or(Error::AccessLevelsMissing)?
                    .clone(),
            )
            .map_err(|_| Error::InvalidGoogleClaims)?;
            for access_level in expected_access_levels {
                if !google.access_levels.contains(access_level) {
                    return Err(Error::InsufficientAccessLevel(access_level.clone()));
                }
            }
        }

        Ok(token.claims)
    }
}

pub trait PublicKeySource {
    type Error: std::error::Error + Send + 'static;

    fn get_public_key(
        &self,
        key: &str,
    ) -> impl std::future::Future<Output = Result<Option<String>, Self::Error>> + Send;
}

#[cfg(feature = "reqwest")]
impl PublicKeySource for reqwest::Client {
    type Error = reqwest::Error;

    async fn get_public_key(&self, key: &str) -> Result<Option<String>, Self::Error> {
        Ok(self
            .get("https://www.gstatic.com/iap/verify/public_key")
            .send()
            .await?
            .error_for_status()?
            .json::<HashMap<String, String>>()
            .await?
            .remove(key))
    }
}

#[cfg(test)]
mod tests {
    use jsonwebtoken::{EncodingKey, Header};
    use serde_json::json;

    use super::*;

    const VALID_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgrpu756TO0uDuesyS
1S1jL/6u/X5TUTfnSscBq6sVLTihRANCAATnZzElTUxsOkFb6AhJ2vRUy3uSuRy/
JX8+CfoH13EhLv+gIqtL8ooDGQKktq9fd/yo89wv3Ut8CVDxET2h34jE
-----END PRIVATE KEY-----
";
    const VALID_PUBLIC_KEY: &str = "-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE52cxJU1MbDpBW+gISdr0VMt7krkc
vyV/Pgn6B9dxIS7/oCKrS/KKAxkCpLavX3f8qPPcL91LfAlQ8RE9od+IxA==
-----END PUBLIC KEY-----
";

    const TEST_AUD: &str = "/projects/1234567890/global/backendServices/test-service-id";
    const TEST_KID: &str = "test-kid";

    fn test_header() -> Header {
        let mut header = Header::new(Algorithm::ES256);
        header.kid = Some(TEST_KID.to_string());
        header
    }

    fn test_claims() -> Claims {
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        Claims {
            exp: now + 600, // 10 minutes after iat (maximum is 10 minutes + 2*skew)
            iat: now,
            aud: TEST_AUD.to_string(),
            iss: "https://cloud.google.com/iap".into(),
            hd: Some("example.com".to_string()),
            google: Some(json!({
                "access_levels": ["OWNER", "EDITOR"],
            })),
            sub: "1234567890".into(),
            email: "test@example.com".into(),
        }
    }

    #[derive(Debug, Error)]
    #[error("Mock error: {0}")]
    struct MockError(String);

    fn mock_client(
        f: impl Fn(&str) -> Result<Option<String>, MockError> + Send + Sync + 'static,
    ) -> impl PublicKeySource {
        type MockFn = Box<dyn Fn(&str) -> Result<Option<String>, MockError> + Send + Sync>;
        struct MockClient(MockFn);
        impl PublicKeySource for MockClient {
            type Error = MockError;

            async fn get_public_key(&self, key: &str) -> Result<Option<String>, Self::Error> {
                self.0(key)
            }
        }
        MockClient(Box::new(f))
    }

    #[tokio::test]
    async fn test_decode_with_public_key() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let decoded = ValidationConfig::new([TEST_AUD])
            .with_google_hosted_domain(["example.com"])
            .with_access_levels(["OWNER", "EDITOR"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap();
        assert_eq!(decoded.exp, claims.exp);
        assert_eq!(decoded.iat, claims.iat);
        assert_eq!(decoded.aud, claims.aud);
        assert_eq!(decoded.iss, claims.iss);
        assert_eq!(decoded.hd, claims.hd);
        assert_eq!(decoded.sub, claims.sub);
        assert_eq!(decoded.email, claims.email);
    }

    #[tokio::test]
    async fn test_decode_with_public_key_not_found() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(None)
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "Invalid kid: test-kid");
    }

    #[tokio::test]
    async fn test_decode_with_private_key_is_invalid() {
        const TEST_INVALID_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgx1I+Ljp/UOxUumfg
kp1T9PFpY8RklbMF1SHmFaB1OXihRANCAAQnLQRg6fL2pgJYUPKdl6DFVsKtda3i
sDlX34kd5D0tFCdaZ5LH7MRtf5ptFCWouh7JDyOcAucHHwz0Z20PKFmu
-----END PRIVATE KEY-----
";
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(TEST_INVALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "InvalidSignature");
    }

    #[tokio::test]
    async fn test_decode_invalid_audience() {
        let mut claims = test_claims();
        claims.aud = "invalid-aud".to_string();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "InvalidAudience");
    }

    #[tokio::test]
    async fn test_decode_aud_not_found() {
        let claims = test_claims();
        let mut json = serde_json::to_value(&claims).unwrap();
        json.as_object_mut().unwrap().remove("aud");
        let token = jsonwebtoken::encode(
            &test_header(),
            &json,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(
            error.to_string().contains("missing field `aud`"),
            "{} does not contain `aud`",
            error
        );
    }

    #[tokio::test]
    async fn test_decode_invalid_algorithm() {
        const TEST_RSA_PRIVATE_KEY: &str = "-----BEGIN PRIVATE KEY-----
MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQDbWZjcOnBP8XB1
OJIitW3Nc7/YpI+rNni1JBCSngMN/PVnOWrmkEj3ObsvYPwVpZ+FF+tKYNdcCU3S
Z6ntUkd6404tB/QeutCtRFF1m9jtLa1bayP3dnsnhrrD/qsV/BWxw1BynJ8a1HLe
303E0jBKNa+kVxf0OMccHyyoAAnaOtCvJmY+xFV/Z9ai584Rs8aKWoiL+vg28tEt
LGu/YgWIbEibVbQCpy8w8kuYFraU92uuXlCDJ6SMIfWmaj4yob/YiGDqwYTT+jyF
EZIXsHJzuUXCsgshfG4cAOKjYpqR+bbRwPVznINxQLWgs4SCisX8xMXuAumyVLta
K330dWXbAgMBAAECgf994+gVzockCXpcI/Yrqor2frBkeorbChDfdTEUB6imaxFa
hHpyMPMA2BTt15yX7yVgKuOObvNplETXao6ZKWeq+mZgnZoghcZ2pNgbuoIjeEWv
H2rJu1vHnp5/hvs/+k7QmByaDtlz3b87iFfuRvKC3RTes8AFfXF39w684B0SZlpp
rayQY2eXNQnVZXxORLls2NEkqFByZmIuNd0yIuvnYaYICtvzL8Er7xPkgLREvmzH
rivbjhL2IpFrlH7Hye9kKSrQ0nwmuKAZutOYP1PPq1YrK/dEkJhy6NdqAcMlBhib
PH4WQ2wCFtADb74mI3vfEKDHFMdaEf0XxBc0BEECgYEA8CkZbejMFcuIrWuXJ61V
EtFEKZQVr8LKvGhlE41vEqfqBt7Gj6VHz9fJEVo/nrqz9lZz6lKFZMF0TLkEHRFc
jtXaLoJQ9OVcqiA4cwUFoHE99rjql8oDZ2/ccOaHnmxlXfByGUTDuI+CxbuEh8AR
GfFk7HR8h6rR2jlMDQrox4cCgYEA6dEhN5LNIHY0lpLx9rhDEb/ecsn64bo4vOTk
KiSwcw/VDiYQeua6JnVpY1c4Ir9us5+NNCs/As00LJeNdWkFDLO5dnxud0mqquKd
SSG1tS4L7CIi7IqQYeOSDB3idFxj8u/8M6FgMVXuDui+inxkd+0Yb1ZVmtC9vTCD
oEPLnA0CgYBLpXZ4E0Ltfo3PqjsTaVqJsdbZjeaC1UWMsQldbkhVRQTHIzbCGlqT
UjHoQFgXxFFZP4QFg/a2dOUQIZr1GPnhl+TAj5W2feSBReLh/+v0zJaq9zYVl7EY
zLhP650+PoBzZYBbCzjnEnUrmVQ2ej4owMt8W3i6Nwkgxrl4xj3qUwKBgQCipt5q
oG6dxFz02igEL05IzKZcR/GEkVzi2n92aattf3gAra4NMPARzN+RQZ1FXtINllJO
Fj9xHXrMAmlfYb0nhubfa9QUm2RkF9y+gPq8nNmiXGTbE9E4p2xzjV54/8RvvU4+
RGZ8K4C9Ul8qSzpAyuiSmwZV+hvjvhnypPbBCQKBgFNo/R0p0O9GLAPe6aF5dJVx
mXTqfrk1BmXxkSS16EgoZC8D8N6EnAQC8tI6FFYWYsgD7kaUnKG1lNIXQjw63PDx
NksAFp0qJeVLilaFwTXrR1RNIoWzWrZkWzsZ3IHpE1WHgrH3hzVZ0O3X94ns4vT6
W8BYg+xGjeeybwjKuiVc
-----END PRIVATE KEY-----
";
        const TEST_RSA_PUBLIC_KEY: &str = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA21mY3DpwT/FwdTiSIrVt
zXO/2KSPqzZ4tSQQkp4DDfz1Zzlq5pBI9zm7L2D8FaWfhRfrSmDXXAlN0mep7VJH
euNOLQf0HrrQrURRdZvY7S2tW2sj93Z7J4a6w/6rFfwVscNQcpyfGtRy3t9NxNIw
SjWvpFcX9DjHHB8sqAAJ2jrQryZmPsRVf2fWoufOEbPGilqIi/r4NvLRLSxrv2IF
iGxIm1W0AqcvMPJLmBa2lPdrrl5QgyekjCH1pmo+MqG/2Ihg6sGE0/o8hRGSF7By
c7lFwrILIXxuHADio2Kakfm20cD1c5yDcUC1oLOEgorF/MTF7gLpslS7Wit99HVl
2wIDAQAB
-----END PUBLIC KEY-----
";
        let mut header = test_header();
        header.alg = Algorithm::RS256;
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &header,
            &claims,
            &EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(TEST_RSA_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Invalid key format"));
    }

    #[tokio::test]
    async fn test_decode_request_failure_handling() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Err(MockError("test-error".to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "Request failed: Mock error: test-error");
    }

    #[tokio::test]
    async fn test_docode_kid_not_available() {
        let mut header = test_header();
        header.kid = None;
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &header,
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Err(MockError("test-error".to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "Kid not available in header");
    }

    #[tokio::test]
    async fn test_decode_future_iat() {
        let mut claims = test_claims();
        claims.iat += 120;
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Invalid iat"));
    }

    #[tokio::test]
    async fn test_decode_without_iat() {
        let claims = test_claims();
        let mut json = serde_json::to_value(&claims).unwrap();
        json.as_object_mut().unwrap().remove("iat");
        let token = jsonwebtoken::encode(
            &test_header(),
            &json,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("missing field `iat`"));
    }

    #[tokio::test]
    async fn test_decode_expired() {
        let mut claims = test_claims();
        claims.exp -= 4000;
        claims.iat -= 4000;
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Expired"));
    }

    /// Test that tokens with exp at the skew boundary are accepted.
    /// According to IAP documentation: "exp - Must be in the future. Allow 30 seconds for skew."
    #[tokio::test]
    async fn test_decode_exp_within_skew_tolerance() {
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut claims = test_claims();
        // Set exp to 30 seconds in the past - at the 30 second skew boundary
        claims.iat = now - 600; // issued 10 minutes ago
        claims.exp = now - 30; // expired 30 seconds ago, at 30s skew boundary

        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });

        // This should succeed because exp is at the 30 second skew boundary
        let decoded = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .expect("Token with exp at skew boundary should be valid");

        assert_eq!(decoded.exp, claims.exp);
    }

    /// Test that tokens with exp beyond the skew tolerance are rejected.
    /// According to IAP documentation: "exp - Must be in the future. Allow 30 seconds for skew."
    /// A token that expired 31 seconds ago should be rejected (beyond 30s skew).
    #[tokio::test]
    async fn test_decode_exp_beyond_skew_tolerance() {
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut claims = test_claims();
        // Set exp to 31 seconds in the past - beyond the 30 second skew tolerance
        claims.iat = now - 600; // issued 10 minutes ago
        claims.exp = now - 31; // expired 31 seconds ago, beyond 30s skew

        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });

        // This should fail because exp is beyond the 30 second skew tolerance
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();

        assert!(
            error.to_string().contains("Expired"),
            "Token expired 31 seconds ago should be rejected, but got: {}",
            error
        );
    }

    #[tokio::test]
    async fn test_decode_without_exp() {
        let claims = test_claims();
        let mut json = serde_json::to_value(&claims).unwrap();
        json.as_object_mut().unwrap().remove("exp");
        let token = jsonwebtoken::encode(
            &test_header(),
            &json,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("missing field `exp`"));
    }

    #[tokio::test]
    async fn test_decode_without_iss() {
        let claims = test_claims();
        let mut json = serde_json::to_value(&claims).unwrap();
        json.as_object_mut().unwrap().remove("iss");
        let token = jsonwebtoken::encode(
            &test_header(),
            &json,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert!(error.to_string().contains("missing field `iss`"));
    }

    #[tokio::test]
    async fn test_decode_invalid_iss() {
        let mut claims = test_claims();
        claims.iss = "invalid-iss".to_string();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "InvalidIssuer");
    }

    #[tokio::test]
    async fn test_decode_validate_hd() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .with_google_hosted_domain(["another.example.com"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(
            error.to_string(),
            "Invalid hosted domain: example.com, expected [\"another.example.com\"]"
        );
    }

    #[tokio::test]
    async fn test_decode_hd_not_found() {
        let mut claims = test_claims();
        claims.hd = None;
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .with_google_hosted_domain(["example.com"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(
            error.to_string(),
            "hd claim is missing, expected [\"example.com\"]"
        );
    }

    #[tokio::test]
    async fn test_decode_validate_access_levels() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .with_access_levels(["EDITOR", "ADMIN"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(
            error.to_string(),
            "Insufficient access level, expected ADMIN"
        );
    }

    #[tokio::test]
    async fn test_decode_validate_access_levels_missing() {
        let claims = test_claims();
        let mut json = serde_json::to_value(&claims).unwrap();
        json.as_object_mut().unwrap().remove("google");
        let token = jsonwebtoken::encode(
            &test_header(),
            &json,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let error = ValidationConfig::new([TEST_AUD])
            .with_access_levels(["EDITOR"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();
        assert_eq!(error.to_string(), "Access levels claim is missing");
    }

    #[tokio::test]
    async fn test_decode_super_set_access_levels() {
        let claims = test_claims();
        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();
        let client = mock_client(|key| {
            assert_eq!(key, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });
        let decoded = ValidationConfig::new([TEST_AUD])
            .with_google_hosted_domain(["example.com"])
            .with_access_levels(["EDITOR"])
            .decode_and_validate(&token, &client)
            .await
            .unwrap();
        assert_eq!(decoded.sub, claims.sub);
    }

    #[tokio::test]
    async fn test_decode_token_lifetime_too_long() {
        let now = SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let mut claims = test_claims();
        claims.iat = now - 60;
        claims.exp = claims.iat + 661;

        let token = jsonwebtoken::encode(
            &test_header(),
            &claims,
            &EncodingKey::from_ec_pem(VALID_PRIVATE_KEY.as_bytes()).unwrap(),
        )
        .unwrap();

        let client = mock_client(|kid| {
            assert_eq!(kid, TEST_KID);
            Ok(Some(VALID_PUBLIC_KEY.to_string()))
        });

        let error = ValidationConfig::new([TEST_AUD])
            .decode_and_validate(&token, &client)
            .await
            .unwrap_err();

        match error {
            Error::TokenLifetimeTooLong {
                iat,
                exp,
                max_lifetime,
            } => {
                assert_eq!(iat, claims.iat);
                assert_eq!(exp, claims.exp);
                assert_eq!(max_lifetime, 600 + 2 * 30); // 10 minutes + 2 * skew(30 seconds)
            }
            _ => panic!("Expected TokenLifetimeTooLong error, got: {:?}", error),
        }
    }
}