rust-mcp-extra 0.3.2

A companion crate to rust-mcp-sdk offering extra implementations of core traits like SessionStore and EventStore, enabling integration with various database backends and third-party platforms such as AWS Lambda for serverless and cloud-native MCP applications.
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
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
use crate::token_verifier::jwt_cache::JwtCache;
use async_lock::RwLock;
use async_trait::async_trait;
use reqwest::{header::AUTHORIZATION, StatusCode};
use rust_mcp_sdk::{
    auth::{
        decode_token_header, default_jwks_algorithms, shared_http_client, Algorithm, Audience,
        AuthInfo, AuthenticationError, IntrospectionResponse, JsonWebKeySet, OauthTokenVerifier,
    },
    mcp_http::error_message_from_response,
};
use serde_json::Value;
use std::{
    collections::HashMap,
    time::{Duration, SystemTime},
};
use url::Url;

const JWKS_REFRESH_TIME: Duration = Duration::from_secs(24 * 60 * 60); // re-fetch jwks every 24 hours
const REMOTE_VERIFICATION_INTERVAL: Duration = Duration::from_secs(15 * 60); // 15 minutes
const JWT_CACHE_CAPACITY: usize = 1000;

struct JwksCache {
    last_updated: Option<SystemTime>,
    jwks: JsonWebKeySet,
}

/// Supported OAuth token verification strategies.
///
/// Each variant represents a different method for validating access tokens,
/// depending on what the authorization server exposes or what your application
/// requires.
pub enum VerificationStrategies {
    /// Verifies tokens by calling the authorization server's introspection
    /// endpoint, as defined in RFC 7662.
    ///
    /// This method allows the resource server to validate opaque or JWT tokens
    /// by sending them to the introspection URI along with its client credentials.
    Introspection {
        /// The OAuth introspection endpoint.
        introspection_uri: String,
        /// Client identifier used to authenticate the introspection request.
        client_id: String,
        /// Client secret used to authenticate the introspection request.
        client_secret: String,
        /// Indicates whether the OAuth2 client should use HTTP Basic Authentication when
        ///calling the token introspection endpoint.
        /// if false: client_id and client_secret will be sent in the POST body instead of using Basic Authentication
        use_basic_auth: bool,
        /// Optional key-value pairs to include as additional parameters in the
        /// body of the token introspection request.
        /// Example : ("token_type_hint", "access_token")
        extra_params: Option<Vec<(&'static str, &'static str)>>,
    },
    /// Verifies JWT access tokens using the authorization server’s JSON Web Key
    /// Set (JWKS) endpoint.
    ///
    /// This strategy allows fully offline signature validation after retrieving
    /// the key set, making it efficient for high-throughput services.
    JWKs {
        /// The JWKS endpoint URL used to retrieve signing keys.
        jwks_uri: String,
    },
    /// Verifies tokens by querying the OpenID Connect UserInfo endpoint.
    ///
    /// This strategy is typically used when token validity is tied to the user's
    /// profile information or when the resource server relies on OIDC user data
    /// for validation.
    UserInfo { userinfo_uri: String },
}

/// Options for configuring a token verifier.
///
/// `TokenVerifierOptions` allows specifying one or more strategies for verifying
/// OAuth access tokens. Multiple strategies can be provided; the verifier will
/// attempt them in order until one succeeds or all fail.
pub struct TokenVerifierOptions {
    /// The list of token verification strategies to use.
    /// Each strategy defines a different method for validating tokens, such as
    /// introspection, JWKS signature validation, or querying the UserInfo endpoint.
    /// For optimal performance, it is recommended to include JWKS alongside either introspection or UserInfo.
    pub strategies: Vec<VerificationStrategies>,
    /// Optional audience value to validate against the token's `aud` claim.
    pub validate_audience: Option<Audience>,
    /// Optional issuer value to validate against the token's `iss` claim.
    pub validate_issuer: Option<String>,
    /// Optional capacity for the internal cache, used to reduce unnecessary requests during verification.
    pub cache_capacity: Option<usize>,
}

#[derive(Default, Debug)]
struct StrategiesOptions {
    pub introspection_uri: Option<Url>,
    pub introspection_basic_auth: bool,
    pub introspect_extra_params: Option<Vec<(&'static str, &'static str)>>,
    pub client_id: Option<String>,
    pub client_secret: Option<String>,
    pub jwks_uri: Option<Url>,
    pub userinfo_uri: Option<Url>,
}

impl TokenVerifierOptions {
    fn unpack(&mut self) -> Result<(StrategiesOptions, bool), AuthenticationError> {
        let mut result = StrategiesOptions::default();

        let mut has_jwks = false;
        let mut has_other = false;

        for strategy in self.strategies.drain(0..) {
            match strategy {
                VerificationStrategies::Introspection {
                    introspection_uri,
                    client_id,
                    client_secret,
                    use_basic_auth,
                    extra_params,
                } => {
                    result.introspection_uri =
                        Some(Url::parse(&introspection_uri).map_err(|err| {
                            AuthenticationError::ParsingError(format!(
                                "Invalid introspection uri: {err}",
                            ))
                        })?);
                    result.client_id = Some(client_id);
                    result.client_secret = Some(client_secret);
                    result.introspection_basic_auth = use_basic_auth;
                    result.introspect_extra_params = extra_params;
                    has_other = true;
                }
                VerificationStrategies::JWKs { jwks_uri } => {
                    result.jwks_uri = Some(Url::parse(&jwks_uri).map_err(|err| {
                        AuthenticationError::ParsingError(format!("Invalid jwks uri: {err}"))
                    })?);
                    has_jwks = true;
                }
                VerificationStrategies::UserInfo { userinfo_uri } => {
                    result.userinfo_uri = Some(Url::parse(&userinfo_uri).map_err(|err| {
                        AuthenticationError::ParsingError(format!("Invalid userinfo uri: {err}"))
                    })?);
                    has_other = true;
                }
            }
        }

        Ok((result, has_jwks && has_other))
    }
}

pub struct GenericOauthTokenVerifier {
    /// Optional audience value to validate against the token's `aud` claim.
    validate_audience: Option<Audience>,
    /// Optional issuer value to validate against the token's `iss` claim.
    validate_issuer: Option<String>,
    /// Signature algorithms accepted during JWKS verification.
    allowed_algorithms: Vec<Algorithm>,
    jwt_cache: Option<RwLock<JwtCache>>,
    json_web_key_set: RwLock<Option<JwksCache>>,
    introspection_uri: Option<Url>,
    introspection_basic_auth: bool,
    introspect_extra_params: Option<Vec<(&'static str, &'static str)>>,
    client_id: Option<String>,
    client_secret: Option<String>,
    jwks_uri: Option<Url>,
    userinfo_uri: Option<Url>,
}

impl GenericOauthTokenVerifier {
    pub fn new(mut options: TokenVerifierOptions) -> Result<Self, AuthenticationError> {
        let (strategy_options, chachable) = options.unpack()?;

        let validate_audience = options.validate_audience.take();

        let validate_issuer = options
            .validate_issuer
            .map(|iss| iss.trim_end_matches('/').to_string());

        // we only need to cache if both jwks and introspection are supported
        let jwt_cache = if chachable {
            Some(RwLock::new(JwtCache::new(
                REMOTE_VERIFICATION_INTERVAL,
                options.cache_capacity.unwrap_or(JWT_CACHE_CAPACITY),
            )))
        } else {
            None
        };

        Ok(Self {
            validate_issuer,
            validate_audience,
            allowed_algorithms: default_jwks_algorithms(),
            jwt_cache,
            json_web_key_set: RwLock::new(None),
            introspection_uri: strategy_options.introspection_uri,
            introspection_basic_auth: strategy_options.introspection_basic_auth,
            introspect_extra_params: strategy_options.introspect_extra_params,
            client_id: strategy_options.client_id,
            client_secret: strategy_options.client_secret,
            jwks_uri: strategy_options.jwks_uri,
            userinfo_uri: strategy_options.userinfo_uri,
        })
    }

    /// Override the set of algorithms allowed during JWKS verification.
    ///
    /// By default only asymmetric algorithms (RS/PS/ES/EdDSA) are accepted.
    /// Use this builder method if you need a custom allowlist.
    pub fn with_allowed_algorithms(mut self, algorithms: Vec<Algorithm>) -> Self {
        self.allowed_algorithms = algorithms;
        self
    }

    async fn verify_user_info(
        &self,
        token: &str,
        token_unique_id: Option<&str>,
        user_info_endpoint: &Url,
    ) -> Result<AuthInfo, AuthenticationError> {
        // use token_unique_id or get from token header
        let token_unique_id = match token_unique_id {
            Some(id) => id.to_owned(),
            None => {
                let header = decode_token_header(token)?;
                header.kid.unwrap_or(token.to_string()).to_owned()
            }
        };

        let client = shared_http_client();

        let response = client
            .get(user_info_endpoint.to_owned())
            .header(AUTHORIZATION, format!("Bearer {token}"))
            .send()
            .await
            .map_err(|err| AuthenticationError::Jwks(err.to_string()))?;

        let status_code = response.status();

        if !response.status().is_success() {
            return Err(AuthenticationError::TokenVerificationFailed {
                description: error_message_from_response(response, "Unauthorized!").await,
                status_code: Some(status_code.as_u16()),
            });
        }

        let json: Value = response.json().await.unwrap();

        let extra = match json {
            Value::Object(map) => Some(map),
            _ => None,
        };

        let auth_info: AuthInfo = AuthInfo {
            token_unique_id,
            client_id: None,
            user_id: None,
            scopes: None,
            expires_at: None,
            audience: None,
            extra,
        };

        Ok(auth_info)
    }

    async fn verify_introspection(
        &self,
        token: &str,
        introspection_endpoint: &Url,
    ) -> Result<AuthInfo, AuthenticationError> {
        let client = shared_http_client();

        // Form data body
        let mut form = HashMap::new();
        form.insert("token", token);

        if !self.introspection_basic_auth {
            if let Some(client_id) = self.client_id.as_ref() {
                form.insert("client_id", client_id);
            };
            if let Some(client_secret) = self.client_secret.as_ref() {
                form.insert("client_secret", client_secret);
            };
        }

        if let Some(extra_params) = self.introspect_extra_params.as_ref() {
            extra_params.iter().for_each(|(key, value)| {
                form.insert(key, value);
            });
        }

        let mut request = client.post(introspection_endpoint.to_owned()).form(&form);
        if self.introspection_basic_auth {
            request = request.basic_auth(
                self.client_id.clone().unwrap_or_default(),
                self.client_secret.clone(),
            );
        }

        let response = request
            .send()
            .await
            .map_err(|err| AuthenticationError::Jwks(err.to_string()))?;

        let status_code = response.status();
        if !response.status().is_success() {
            let description = response.text().await.unwrap_or("Unauthorized!".to_string());
            return Err(AuthenticationError::TokenVerificationFailed {
                description,
                status_code: Some(status_code.as_u16()),
            });
        }

        let introspect_response: IntrospectionResponse = response
            .json()
            .await
            .map_err(|err| AuthenticationError::Jwks(err.to_string()))?;

        if !introspect_response.active {
            return Err(AuthenticationError::InactiveToken);
        }

        if let Some(validate_audience) = self.validate_audience.as_ref() {
            let Some(token_audience) = introspect_response.audience.as_ref() else {
                return Err(AuthenticationError::InvalidToken {
                    description: "Audience attribute (aud) is missing.",
                });
            };

            if token_audience != validate_audience {
                return Err(AuthenticationError::TokenVerificationFailed { description:
                    format!("None of the provided audiences are allowed. Expected ${validate_audience}, got: ${token_audience}")
                    , status_code: Some(StatusCode::UNAUTHORIZED.as_u16())
                });
            }
        }

        if let Some(validate_issuer) = self.validate_issuer.as_ref() {
            let Some(token_issuer) = introspect_response.issuer.as_ref() else {
                return Err(AuthenticationError::InvalidToken {
                    description: "Issuer (iss) is missing.",
                });
            };

            if token_issuer != validate_issuer {
                return Err(AuthenticationError::TokenVerificationFailed {
                    description: format!(
                        "Issuer is not allowed. Expected ${validate_issuer}, got: ${token_issuer}"
                    ),
                    status_code: Some(StatusCode::UNAUTHORIZED.as_u16()),
                });
            }
        }

        AuthInfo::from_introspection_response(token.to_owned(), introspect_response, None)
    }

    async fn populate_jwks(&self, jwks_uri: &Url) -> Result<(), AuthenticationError> {
        let response = shared_http_client()
            .get(jwks_uri.to_owned())
            .send()
            .await
            .map_err(|err| AuthenticationError::Jwks(err.to_string()))?;
        let jwks: JsonWebKeySet = response
            .json()
            .await
            .map_err(|err| AuthenticationError::Jwks(err.to_string()))?;
        let mut guard = self.json_web_key_set.write().await;
        *guard = Some(JwksCache {
            last_updated: Some(SystemTime::now()),
            jwks,
        });
        Ok(())
    }

    async fn verify_jwks(&self, token: &str, jwks: &Url) -> Result<AuthInfo, AuthenticationError> {
        // read-modify-write pattern
        {
            let guard = self.json_web_key_set.read().await;
            if let Some(cache) = guard.as_ref() {
                if let Some(last_updated) = cache.last_updated {
                    if SystemTime::now()
                        .duration_since(last_updated)
                        .unwrap_or(Duration::from_secs(0))
                        < JWKS_REFRESH_TIME
                    {
                        let token_info = cache.jwks.verify(
                            token.to_string(),
                            &self.allowed_algorithms,
                            self.validate_audience.as_ref(),
                            self.validate_issuer.as_ref(),
                        )?;

                        return AuthInfo::from_token_data(token.to_owned(), token_info, None);
                    }
                }
            }
        }

        // Refresh JWKS if cache is invalid or missing
        self.populate_jwks(jwks).await?;

        // Proceed with verification
        let guard = self.json_web_key_set.read().await;
        if let Some(cache) = guard.as_ref() {
            let token_info = cache.jwks.verify(
                token.to_string(),
                &self.allowed_algorithms,
                self.validate_audience.as_ref(),
                self.validate_issuer.as_ref(),
            )?;

            AuthInfo::from_token_data(token.to_owned(), token_info, None)
        } else {
            Err(AuthenticationError::Jwks(
                "Failed to retrieve or parse JWKS".to_string(),
            ))
        }
    }
}

#[async_trait]
impl OauthTokenVerifier for GenericOauthTokenVerifier {
    async fn verify_token(&self, access_token: String) -> Result<AuthInfo, AuthenticationError> {
        // perform local jwks verification if supported
        if let Some(jwks_endpoint) = self.jwks_uri.as_ref() {
            let mut auth_info = self.verify_jwks(&access_token, jwks_endpoint).await?;

            // perform remote verification only if it is supported and jwt is stale
            if let Some(jwt_cache) = self.jwt_cache.as_ref() {
                // return auth_info if it is recent
                if jwt_cache.read().await.is_recent(&auth_info.token_unique_id) {
                    return Ok(auth_info);
                }

                // introspection validation if introspection_uri is provided
                if let Some(introspection_endpoint) = self.introspection_uri.as_ref() {
                    let fresh_auth_info = self
                        .verify_introspection(&access_token, introspection_endpoint)
                        .await?;
                    jwt_cache
                        .write()
                        .await
                        .record(fresh_auth_info.token_unique_id.to_owned());
                    return Ok(fresh_auth_info);
                }

                // call userInfo endpoint only if introspect strategy is not used
                if let Some(user_info_endpoint) = self.userinfo_uri.as_ref() {
                    let fresh_auth_info = self
                        .verify_user_info(
                            &access_token,
                            Some(&auth_info.token_unique_id),
                            user_info_endpoint,
                        )
                        .await?;

                    auth_info.extra = fresh_auth_info.extra;
                    jwt_cache
                        .write()
                        .await
                        .record(auth_info.token_unique_id.to_owned());
                    return Ok(auth_info);
                }
            }

            return Ok(auth_info);
        }

        // use introspection if jwks is not supported, no caching
        if let Some(introspection_endpoint) = self.introspection_uri.as_ref() {
            let auth_info = self
                .verify_introspection(&access_token, introspection_endpoint)
                .await?;
            return Ok(auth_info);
        }

        // use userInfo endpoint if introspect strategy is not used
        if let Some(user_info_endpoint) = self.userinfo_uri.as_ref() {
            let auth_info = self
                .verify_user_info(&access_token, None, user_info_endpoint)
                .await?;
            return Ok(auth_info);
        }

        Err(AuthenticationError::InvalidToken {
            description: "Invalid token verification strategy!",
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oauth2_test_server::{OAuthTestServer, OauthEndpoints};
    use rust_mcp_sdk::auth::*;
    use serde_json::json;

    async fn token_verifier(
        strategies: Vec<VerificationStrategies>,
        endpoints: &OauthEndpoints,
        audience: Option<Audience>,
    ) -> GenericOauthTokenVerifier {
        let auth_metadata = AuthMetadataBuilder::new("http://127.0.0.1:3000/mcp")
            .issuer(&endpoints.oauth_server)
            .authorization_servers(vec![&endpoints.oauth_server])
            .authorization_endpoint(&endpoints.authorize)
            .token_endpoint(&endpoints.token)
            .scopes_supported(vec!["openid".to_string()])
            .introspection_endpoint(&endpoints.introspect)
            .jwks_uri(&endpoints.jwks)
            .resource_name("MCP Demo Server".to_string())
            .build()
            .unwrap();
        let meta = &auth_metadata.0;

        let token_verifier = GenericOauthTokenVerifier::new(TokenVerifierOptions {
            validate_audience: audience,
            validate_issuer: Some(meta.issuer.to_string()),
            strategies,
            cache_capacity: None,
        })
        .unwrap();
        token_verifier
    }

    #[tokio::test]
    async fn test_jwks_strategy() {
        let server = OAuthTestServer::start().await;

        let client = server
            .register_client(
                json!({ "scope": "openid", "redirect_uris":["http://localhost:8080/callback"]}),
            )
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::JWKs {
                jwks_uri: server.endpoints.jwks.clone(),
            }],
            &server.endpoints,
            Some(Audience::Single(client.client_id.clone())),
        )
        .await;

        let token = server.generate_jwt(&client, server.jwt_options().user_id("rustmcp").build());

        let auth_info = verifier.verify_token(token).await.unwrap();
        assert_eq!(
            auth_info.audience.as_ref().unwrap().to_string(),
            client.client_id
        );
        assert_eq!(
            auth_info.client_id.as_ref().unwrap().to_string(),
            client.client_id
        );
        assert_eq!(auth_info.user_id.as_ref().unwrap(), "rustmcp");
        let scopes = auth_info.scopes.as_ref().unwrap();
        assert_eq!(scopes.as_slice(), ["openid"]);
    }

    #[tokio::test]
    async fn test_userinfo_strategy() {
        let server = OAuthTestServer::start().await;

        let client = server
            .register_client(
                json!({ "scope": "openid", "redirect_uris":["http://localhost:8080/callback"]}),
            )
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::UserInfo {
                userinfo_uri: server.endpoints.userinfo.clone(),
            }],
            &server.endpoints,
            None,
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("rustmcp").build())
            .await;

        let auth_info = verifier.verify_token(token.access_token).await.unwrap();

        assert!(auth_info.audience.is_none());
        assert_eq!(
            auth_info
                .extra
                .unwrap()
                .get("sub")
                .unwrap()
                .as_str()
                .unwrap(),
            "rustmcp"
        );
    }

    #[tokio::test]
    async fn test_introspect_strategy() {
        let server = OAuthTestServer::start().await;

        let client = server
            .register_client(
                json!({ "scope": "openid", "redirect_uris":["http://localhost:8080/callback"]}),
            )
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::Introspection {
                introspection_uri: server.endpoints.introspect.clone(),
                client_id: client.client_id.clone(),
                client_secret: client.client_secret.as_ref().unwrap().clone(),
                use_basic_auth: true,
                extra_params: None,
            }],
            &server.endpoints,
            None,
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("rustmcp").build())
            .await;
        let auth_info = verifier.verify_token(token.access_token).await.unwrap();

        assert_eq!(
            auth_info.audience.as_ref().unwrap().to_string(),
            client.client_id
        );
        assert_eq!(
            auth_info.client_id.as_ref().unwrap().to_string(),
            client.client_id
        );
        assert_eq!(auth_info.user_id.as_ref().unwrap(), "rustmcp");
        let scopes = auth_info.scopes.as_ref().unwrap();
        assert_eq!(scopes.as_slice(), ["openid"]);
    }

    #[tokio::test]
    async fn test_introspect_strategy_with_client_secret_post() {
        let server = OAuthTestServer::start().await;

        let client = server
            .register_client(
                json!({ "scope": "openid profile", "redirect_uris":["http://localhost:8080/cb"]}),
            )
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::Introspection {
                introspection_uri: server.endpoints.introspect.clone(),
                client_id: client.client_id.clone(),
                client_secret: client.client_secret.as_ref().unwrap().clone(),
                use_basic_auth: false, // <--- POST body instead of Basic Auth
                extra_params: None,
            }],
            &server.endpoints,
            Some(Audience::Single(client.client_id.clone())),
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("alice").build())
            .await;

        let auth_info = verifier.verify_token(token.access_token).await.unwrap();

        assert_eq!(auth_info.user_id.as_ref().unwrap(), "alice");
        assert!(auth_info.scopes.unwrap().contains(&"profile".to_string()));
        assert_eq!(
            auth_info.audience.as_ref().unwrap().to_string(),
            client.client_id
        );
    }

    #[tokio::test]
    async fn test_introspect_rejects_inactive_token() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(json!({ "scope": "openid", "redirect_uris": ["http://localhost"] }))
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::Introspection {
                introspection_uri: server.endpoints.introspect.clone(),
                client_id: client.client_id.clone(),
                client_secret: client.client_secret.as_ref().unwrap().clone(),
                use_basic_auth: true,
                extra_params: None,
            }],
            &server.endpoints,
            None,
        )
        .await;

        let token_response = server
            .generate_token(&client, server.jwt_options().user_id("bob").build())
            .await;
        server
            .revoke_token(&client, &token_response.access_token)
            .await;

        let result = verifier.verify_token(token_response.access_token).await;
        assert!(matches!(result, Err(AuthenticationError::InactiveToken)));
    }

    #[tokio::test]
    async fn test_expired_token_rejected_by_jwks_and_introspection() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(
                json!({ "scope": "openid email", "redirect_uris": ["http://localhost"] }),
            )
            .await;

        // Use both strategies → expect rejection on expiration alone
        let verifier = token_verifier(
            vec![
                VerificationStrategies::JWKs {
                    jwks_uri: server.endpoints.jwks.clone(),
                },
                VerificationStrategies::Introspection {
                    introspection_uri: server.endpoints.introspect.clone(),
                    client_id: client.client_id.clone(),
                    client_secret: client.client_secret.as_ref().unwrap().clone(),
                    use_basic_auth: true,
                    extra_params: None,
                },
            ],
            &server.endpoints,
            Some(Audience::Single(client.client_id.clone())),
        )
        .await;

        // Generate short-lived token
        let short_lived = server
            .jwt_options()
            .user_id("charlie")
            .expires_in(1)
            .build();
        let token = server.generate_token(&client, short_lived).await;

        // Wait for expiry
        tokio::time::sleep(tokio::time::Duration::from_millis(2500)).await;

        // JWKS should reject immediately (exp validation)
        // But since fallback is enabled, it hits introspection → active: false → error
        let err1 = verifier
            .verify_token(token.access_token.clone())
            .await
            .unwrap_err();
        assert!(matches!(err1, AuthenticationError::InactiveToken));

        // Now revoke it (expired + revoked) → still InactiveToken (no special handling needed)
        server.revoke_token(&client, &token.access_token).await;
        let err2 = verifier.verify_token(token.access_token).await.unwrap_err();
        assert!(matches!(err2, AuthenticationError::InactiveToken));
    }

    #[tokio::test]
    async fn test_jwks_and_introspection_cache_works() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(json!({ "scope": "openid", "redirect_uris": ["http://localhost"] }))
            .await;

        let verifier = token_verifier(
            vec![
                VerificationStrategies::JWKs {
                    jwks_uri: server.endpoints.jwks.clone(),
                },
                VerificationStrategies::Introspection {
                    introspection_uri: server.endpoints.introspect.clone(),
                    client_id: client.client_id.clone(),
                    client_secret: client.client_secret.as_ref().unwrap().clone(),
                    use_basic_auth: true,
                    extra_params: None,
                },
            ],
            &server.endpoints,
            None,
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("dave").build())
            .await;

        // First call → goes through full flow
        let info1 = verifier
            .verify_token(token.access_token.clone())
            .await
            .unwrap();

        // Second call → should hit cache (no network)
        let info2 = verifier
            .verify_token(token.access_token.clone())
            .await
            .unwrap();

        assert_eq!(info1.user_id, info2.user_id);
        assert_eq!(info1.token_unique_id, info2.token_unique_id);
    }

    #[tokio::test]
    async fn test_audience_validation_rejects_wrong_aud() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(json!({ "scope": "openid", "redirect_uris": ["http://localhost"] }))
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::Introspection {
                introspection_uri: server.endpoints.introspect.clone(),
                client_id: client.client_id.clone(),
                client_secret: client.client_secret.as_ref().unwrap().clone(),
                use_basic_auth: true,
                extra_params: None,
            }],
            &server.endpoints,
            Some(Audience::Single("wrong-client-id-999".to_string())),
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("eve").build())
            .await;

        let err = verifier.verify_token(token.access_token).await.unwrap_err();
        assert!(matches!(
            err,
            AuthenticationError::TokenVerificationFailed { .. }
        ));
    }

    #[tokio::test]
    async fn test_issuer_validation_rejects_wrong_iss() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(json!({ "scope": "openid", "redirect_uris": ["http://localhost"] }))
            .await;

        let _verifier = token_verifier(
            vec![VerificationStrategies::JWKs {
                jwks_uri: server.endpoints.jwks.clone(),
            }],
            &server.endpoints,
            None,
        )
        .await;

        // Force wrong expected issuer
        let wrong_verifier = GenericOauthTokenVerifier::new(TokenVerifierOptions {
            strategies: vec![VerificationStrategies::JWKs {
                jwks_uri: server.endpoints.jwks.clone(),
            }],
            validate_audience: None,
            validate_issuer: Some("https://wrong-issuer.example.com".to_string()),
            cache_capacity: None,
        })
        .unwrap();

        let token = server
            .generate_token(&client, server.jwt_options().user_id("frank").build())
            .await;

        let err = wrong_verifier
            .verify_token(token.access_token)
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            AuthenticationError::TokenVerificationFailed { .. }
        ));
    }

    #[tokio::test]
    async fn test_userinfo_enriches_jwt_claims() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(
                json!({ "scope": "openid profile email", "redirect_uris": ["http://localhost"] }),
            )
            .await;

        let verifier = token_verifier(
            vec![
                VerificationStrategies::JWKs {
                    jwks_uri: server.endpoints.jwks.clone(),
                },
                VerificationStrategies::UserInfo {
                    userinfo_uri: server.endpoints.userinfo.clone(),
                },
            ],
            &server.endpoints,
            None,
        )
        .await;

        let token = server
            .generate_token(&client, server.jwt_options().user_id("grace").build())
            .await;

        let auth_info = verifier.verify_token(token.access_token).await.unwrap();

        let extra = auth_info.extra.unwrap();
        assert_eq!(
            extra.get("email").unwrap().as_str().unwrap(),
            "test@example.com"
        );
        assert_eq!(extra.get("name").unwrap().as_str().unwrap(), "Test User");
        assert!(extra.get("picture").is_some());
    }

    #[tokio::test]
    async fn test_with_allowed_algorithms_rejects_restricted_allowlist() {
        let server = OAuthTestServer::start().await;
        let client = server
            .register_client(json!({ "scope": "openid", "redirect_uris": ["http://localhost"] }))
            .await;

        let verifier = token_verifier(
            vec![VerificationStrategies::JWKs {
                jwks_uri: server.endpoints.jwks.clone(),
            }],
            &server.endpoints,
            None,
        )
        .await
        .with_allowed_algorithms(vec![Algorithm::ES256]);

        let token = server.generate_jwt(&client, server.jwt_options().user_id("hal").build());

        let err = verifier.verify_token(token).await.unwrap_err();
        assert!(matches!(
            err,
            AuthenticationError::TokenVerificationFailed { .. }
        ));
    }
}