pmcp 2.3.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! AWS Cognito identity provider.
//!
//! This module provides a Cognito-specific implementation of [`IdentityProvider`].
//! JWT validation is delegated to [`MultiTenantJwtValidator`] for code reuse.

use async_trait::async_trait;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;

use crate::error::{Error, ErrorCode, Result};
#[cfg(feature = "jwt-auth")]
use crate::server::auth::jwt_validator::{JwtValidator, ValidationConfig};
use crate::server::auth::provider::{
    AuthorizationParams, DcrRequest, DcrResponse, IdentityProvider, OidcDiscovery,
    ProviderCapabilities, TokenExchangeParams, TokenResponse,
};
use crate::server::auth::traits::AuthContext;

/// Cached data with expiration.
struct CachedData<T: std::fmt::Debug> {
    data: T,
    fetched_at: Instant,
    ttl: Duration,
}

impl<T: std::fmt::Debug> std::fmt::Debug for CachedData<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachedData")
            .field("data", &self.data)
            .field("fetched_at", &self.fetched_at)
            .field("ttl", &self.ttl)
            .finish()
    }
}

impl<T: std::fmt::Debug> CachedData<T> {
    fn new(data: T, ttl: Duration) -> Self {
        Self {
            data,
            fetched_at: Instant::now(),
            ttl,
        }
    }

    fn is_expired(&self) -> bool {
        self.fetched_at.elapsed() > self.ttl
    }
}

/// Type alias for discovery cache.
#[cfg(not(target_arch = "wasm32"))]
type DiscoveryCache = Arc<RwLock<Option<CachedData<OidcDiscovery>>>>;

/// AWS Cognito identity provider.
///
/// Provides token validation and OIDC discovery for AWS Cognito user pools.
/// Uses [`JwtValidator`] internally for efficient JWKS caching and JWT validation.
///
/// # Example
///
/// ```rust,ignore
/// use pmcp::server::auth::providers::CognitoProvider;
///
/// let cognito = CognitoProvider::new(
///     "us-east-1",
///     "us-east-1_xxxxx",
///     "your-client-id",
/// ).await?;
///
/// // Validate a token
/// let auth = cognito.validate_token("eyJ...").await?;
/// println!("User: {}", auth.user_id());
/// ```
#[derive(Debug)]
pub struct CognitoProvider {
    /// AWS region.
    region: String,
    /// Cognito user pool ID.
    user_pool_id: String,
    /// App client ID.
    client_id: String,
    /// Issuer URL.
    issuer: String,
    /// JWKS URI.
    #[allow(dead_code)]
    jwks_uri: String,
    /// JWT validator with shared JWKS cache.
    #[cfg(all(not(target_arch = "wasm32"), feature = "jwt-auth"))]
    jwt_validator: JwtValidator,
    /// Validation config for this provider.
    #[cfg(all(not(target_arch = "wasm32"), feature = "jwt-auth"))]
    validation_config: ValidationConfig,
    /// Cached discovery document.
    #[cfg(not(target_arch = "wasm32"))]
    discovery_cache: DiscoveryCache,
    /// HTTP client for non-JWT operations.
    #[cfg(not(target_arch = "wasm32"))]
    http_client: reqwest::Client,
    /// Cache TTL.
    cache_ttl: Duration,
}

impl CognitoProvider {
    /// Create a new Cognito provider.
    ///
    /// # Arguments
    ///
    /// * `region` - AWS region (e.g., "us-east-1")
    /// * `user_pool_id` - Cognito user pool ID (e.g., "us-east-1_xxxxx")
    /// * `client_id` - App client ID
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn new(region: &str, user_pool_id: &str, client_id: &str) -> Result<Self> {
        let issuer = format!(
            "https://cognito-idp.{}.amazonaws.com/{}",
            region, user_pool_id
        );
        let jwks_uri = format!("{}/.well-known/jwks.json", issuer);

        let provider = Self {
            region: region.to_string(),
            user_pool_id: user_pool_id.to_string(),
            client_id: client_id.to_string(),
            issuer,
            jwks_uri,
            #[cfg(feature = "jwt-auth")]
            jwt_validator: JwtValidator::new(),
            #[cfg(feature = "jwt-auth")]
            validation_config: ValidationConfig::cognito(region, user_pool_id, client_id),
            discovery_cache: Arc::new(RwLock::new(None)),
            http_client: reqwest::Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .map_err(|e| Error::internal(format!("Failed to create HTTP client: {}", e)))?,
            cache_ttl: Duration::from_secs(3600), // 1 hour
        };

        Ok(provider)
    }

    /// Create a provider with a shared JWT validator.
    ///
    /// Use this when you want multiple providers to share the same JWKS cache.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use pmcp::server::auth::{MultiTenantJwtValidator, CognitoProvider};
    ///
    /// // Create shared validator
    /// let validator = MultiTenantJwtValidator::new();
    ///
    /// // Create providers that share the validator
    /// let provider1 = CognitoProvider::with_validator("us-east-1", "pool1", "client1", validator.clone()).await?;
    /// let provider2 = CognitoProvider::with_validator("us-west-2", "pool2", "client2", validator.clone()).await?;
    /// ```
    #[cfg(all(not(target_arch = "wasm32"), feature = "jwt-auth"))]
    pub async fn with_validator(
        region: &str,
        user_pool_id: &str,
        client_id: &str,
        jwt_validator: JwtValidator,
    ) -> Result<Self> {
        let issuer = format!(
            "https://cognito-idp.{}.amazonaws.com/{}",
            region, user_pool_id
        );
        let jwks_uri = format!("{}/.well-known/jwks.json", issuer);

        let provider = Self {
            region: region.to_string(),
            user_pool_id: user_pool_id.to_string(),
            client_id: client_id.to_string(),
            issuer,
            jwks_uri,
            jwt_validator,
            validation_config: ValidationConfig::cognito(region, user_pool_id, client_id),
            discovery_cache: Arc::new(RwLock::new(None)),
            http_client: reqwest::Client::builder()
                .timeout(Duration::from_secs(10))
                .build()
                .map_err(|e| Error::internal(format!("Failed to create HTTP client: {}", e)))?,
            cache_ttl: Duration::from_secs(3600),
        };

        Ok(provider)
    }

    /// Get the AWS region.
    pub fn region(&self) -> &str {
        &self.region
    }

    /// Get the user pool ID.
    pub fn user_pool_id(&self) -> &str {
        &self.user_pool_id
    }

    /// Get the client ID.
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// Get the Cognito hosted UI authorization endpoint.
    fn hosted_ui_domain(&self) -> String {
        // Default hosted UI domain pattern
        format!(
            "https://{}.auth.{}.amazoncognito.com",
            self.user_pool_id, self.region
        )
    }
}

#[async_trait]
impl IdentityProvider for CognitoProvider {
    fn id(&self) -> &'static str {
        "cognito"
    }

    fn display_name(&self) -> &'static str {
        "AWS Cognito"
    }

    fn capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities {
            oidc: true,
            dcr: false, // Cognito doesn't support DCR
            pkce: true,
            refresh_tokens: true,
            revocation: true,
            introspection: false,
            custom_scopes: true,
            device_flow: false,
        }
    }

    fn issuer(&self) -> &str {
        &self.issuer
    }

    #[cfg(all(not(target_arch = "wasm32"), feature = "jwt-auth"))]
    async fn validate_token(&self, token: &str) -> Result<AuthContext> {
        // Delegate to shared JWT validator
        self.jwt_validator
            .validate(token, &self.validation_config)
            .await
    }

    #[cfg(any(target_arch = "wasm32", not(feature = "jwt-auth")))]
    async fn validate_token(&self, _token: &str) -> Result<AuthContext> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "JWT validation requires the 'jwt-auth' feature and non-WASM target",
        ))
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn discovery(&self) -> Result<OidcDiscovery> {
        // Check cache first
        {
            let cache = self.discovery_cache.read().await;
            if let Some(ref cached) = *cache {
                if !cached.is_expired() {
                    return Ok(cached.data.clone());
                }
            }
        }

        // Fetch discovery document
        let discovery_url = format!("{}/.well-known/openid-configuration", self.issuer);
        tracing::debug!("Fetching OIDC discovery from {}", discovery_url);

        let response = self
            .http_client
            .get(&discovery_url)
            .send()
            .await
            .map_err(|e| Error::internal(format!("Failed to fetch discovery: {}", e)))?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "Discovery endpoint returned status {}",
                response.status()
            )));
        }

        let discovery: OidcDiscovery = response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse discovery: {}", e)))?;

        // Cache the discovery document
        {
            let mut cache = self.discovery_cache.write().await;
            *cache = Some(CachedData::new(discovery.clone(), self.cache_ttl));
        }

        Ok(discovery)
    }

    #[cfg(target_arch = "wasm32")]
    async fn discovery(&self) -> Result<OidcDiscovery> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "Discovery not available on WASM target",
        ))
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn jwks(&self) -> Result<serde_json::Value> {
        let response = self
            .http_client
            .get(&self.jwks_uri)
            .send()
            .await
            .map_err(|e| Error::internal(format!("Failed to fetch JWKS: {}", e)))?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "JWKS endpoint returned status {}",
                response.status()
            )));
        }

        response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse JWKS: {}", e)))
    }

    #[cfg(target_arch = "wasm32")]
    async fn jwks(&self) -> Result<serde_json::Value> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "JWKS not available on WASM target",
        ))
    }

    async fn authorization_url(&self, params: AuthorizationParams) -> Result<String> {
        let hosted_ui = self.hosted_ui_domain();

        let mut url = format!(
            "{}/oauth2/authorize?client_id={}&redirect_uri={}&response_type=code&scope={}&state={}",
            hosted_ui,
            urlencoding::encode(&self.client_id),
            urlencoding::encode(&params.redirect_uri),
            urlencoding::encode(&params.scopes.join(" ")),
            urlencoding::encode(&params.state),
        );

        if let Some(nonce) = &params.nonce {
            url.push_str(&format!("&nonce={}", urlencoding::encode(nonce)));
        }

        if let Some(challenge) = &params.code_challenge {
            url.push_str(&format!(
                "&code_challenge={}&code_challenge_method={}",
                urlencoding::encode(challenge),
                params.code_challenge_method.as_deref().unwrap_or("S256")
            ));
        }

        for (key, value) in &params.extra {
            url.push_str(&format!(
                "&{}={}",
                urlencoding::encode(key),
                urlencoding::encode(value)
            ));
        }

        Ok(url)
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn exchange_code(&self, params: TokenExchangeParams) -> Result<TokenResponse> {
        let hosted_ui = self.hosted_ui_domain();
        let token_url = format!("{}/oauth2/token", hosted_ui);

        let mut form = vec![
            ("grant_type", "authorization_code".to_string()),
            ("client_id", self.client_id.clone()),
            ("code", params.code),
            ("redirect_uri", params.redirect_uri),
        ];

        if let Some(verifier) = params.code_verifier {
            form.push(("code_verifier", verifier));
        }

        let response = self
            .http_client
            .post(&token_url)
            .form(&form)
            .send()
            .await
            .map_err(|e| Error::internal(format!("Token exchange failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("Token exchange failed: {}", error_text),
            ));
        }

        response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse token response: {}", e)))
    }

    #[cfg(target_arch = "wasm32")]
    async fn exchange_code(&self, _params: TokenExchangeParams) -> Result<TokenResponse> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "Code exchange not available on WASM target",
        ))
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn refresh_token(&self, refresh_token: &str) -> Result<TokenResponse> {
        let hosted_ui = self.hosted_ui_domain();
        let token_url = format!("{}/oauth2/token", hosted_ui);

        let form = vec![
            ("grant_type", "refresh_token"),
            ("client_id", &self.client_id),
            ("refresh_token", refresh_token),
        ];

        let response = self
            .http_client
            .post(&token_url)
            .form(&form)
            .send()
            .await
            .map_err(|e| Error::internal(format!("Token refresh failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("Token refresh failed: {}", error_text),
            ));
        }

        response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse token response: {}", e)))
    }

    #[cfg(target_arch = "wasm32")]
    async fn refresh_token(&self, _refresh_token: &str) -> Result<TokenResponse> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "Token refresh not available on WASM target",
        ))
    }

    async fn register_client(&self, _request: DcrRequest) -> Result<DcrResponse> {
        Err(Error::protocol(
            ErrorCode::INVALID_REQUEST,
            "AWS Cognito does not support Dynamic Client Registration",
        ))
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn revoke_token(&self, token: &str) -> Result<()> {
        let hosted_ui = self.hosted_ui_domain();
        let revoke_url = format!("{}/oauth2/revoke", hosted_ui);

        let form = vec![("token", token), ("client_id", &self.client_id)];

        let response = self
            .http_client
            .post(&revoke_url)
            .form(&form)
            .send()
            .await
            .map_err(|e| Error::internal(format!("Token revocation failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("Token revocation failed: {}", error_text),
            ));
        }

        Ok(())
    }

    #[cfg(target_arch = "wasm32")]
    async fn revoke_token(&self, _token: &str) -> Result<()> {
        Ok(()) // No-op on WASM
    }

    #[cfg(not(target_arch = "wasm32"))]
    async fn user_info(&self, access_token: &str) -> Result<serde_json::Value> {
        let hosted_ui = self.hosted_ui_domain();
        let userinfo_url = format!("{}/oauth2/userInfo", hosted_ui);

        let response = self
            .http_client
            .get(&userinfo_url)
            .bearer_auth(access_token)
            .send()
            .await
            .map_err(|e| Error::internal(format!("UserInfo request failed: {}", e)))?;

        if !response.status().is_success() {
            let error_text = response.text().await.unwrap_or_default();
            return Err(Error::protocol(
                ErrorCode::INVALID_REQUEST,
                format!("UserInfo request failed: {}", error_text),
            ));
        }

        response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse UserInfo response: {}", e)))
    }

    #[cfg(target_arch = "wasm32")]
    async fn user_info(&self, _access_token: &str) -> Result<serde_json::Value> {
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            "UserInfo not available on WASM target",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::auth::traits::ClaimMappings;

    // =========================================================================
    // CachedData Tests
    // =========================================================================

    #[test]
    fn test_cached_data_creation() {
        let data: CachedData<String> = CachedData::new("test".to_string(), Duration::from_secs(60));
        assert_eq!(data.data, "test");
        assert!(!data.is_expired());
    }

    #[test]
    fn test_cached_data_expiration() {
        let data: CachedData<String> =
            CachedData::new("test".to_string(), Duration::from_millis(1));
        // Wait for it to expire
        std::thread::sleep(Duration::from_millis(10));
        assert!(data.is_expired());
    }

    #[test]
    fn test_cached_data_debug() {
        let data: CachedData<String> = CachedData::new("test".to_string(), Duration::from_secs(60));
        let debug_str = format!("{:?}", data);
        assert!(debug_str.contains("CachedData"));
        assert!(debug_str.contains("data"));
        assert!(debug_str.contains("ttl"));
    }

    // =========================================================================
    // Provider Capabilities Tests
    // =========================================================================

    #[test]
    fn test_cognito_capabilities() {
        // Test the expected capabilities for Cognito
        let caps = ProviderCapabilities {
            oidc: true,
            dcr: false, // Cognito doesn't support DCR
            pkce: true,
            refresh_tokens: true,
            revocation: true,
            introspection: false,
            custom_scopes: true,
            device_flow: false,
        };

        assert!(caps.oidc);
        assert!(!caps.dcr);
        assert!(caps.pkce);
        assert!(caps.refresh_tokens);
        assert!(caps.revocation);
        assert!(!caps.introspection);
        assert!(caps.custom_scopes);
        assert!(!caps.device_flow);
    }

    // =========================================================================
    // URL Generation Tests (Unit tests without network)
    // =========================================================================

    #[test]
    fn test_issuer_url_format() {
        let region = "us-east-1";
        let user_pool_id = "us-east-1_ABC123";
        let expected = format!(
            "https://cognito-idp.{}.amazonaws.com/{}",
            region, user_pool_id
        );
        assert_eq!(
            expected,
            "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123"
        );
    }

    #[test]
    fn test_jwks_uri_format() {
        let issuer = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123";
        let jwks_uri = format!("{}/.well-known/jwks.json", issuer);
        assert!(jwks_uri.ends_with("/.well-known/jwks.json"));
        assert!(jwks_uri.contains("cognito-idp"));
    }

    #[test]
    fn test_hosted_ui_domain_format() {
        let user_pool_id = "us-east-1_ABC123";
        let region = "us-east-1";
        let expected = format!("https://{}.auth.{}.amazoncognito.com", user_pool_id, region);
        assert_eq!(
            expected,
            "https://us-east-1_ABC123.auth.us-east-1.amazoncognito.com"
        );
    }

    #[test]
    fn test_authorization_url_components() {
        // Test URL components without needing actual provider
        let hosted_ui = "https://us-east-1_ABC123.auth.us-east-1.amazoncognito.com";
        let client_id = "test-client-id";
        let redirect_uri = "https://example.com/callback";
        let scopes = ["openid", "email", "profile"];
        let state = "random-state";

        let url = format!(
            "{}/oauth2/authorize?client_id={}&redirect_uri={}&response_type=code&scope={}&state={}",
            hosted_ui,
            urlencoding::encode(client_id),
            urlencoding::encode(redirect_uri),
            urlencoding::encode(&scopes.join(" ")),
            urlencoding::encode(state),
        );

        assert!(url.contains("/oauth2/authorize"));
        assert!(url.contains("client_id=test-client-id"));
        assert!(url.contains("redirect_uri=https%3A%2F%2Fexample.com%2Fcallback"));
        assert!(url.contains("response_type=code"));
        assert!(url.contains("scope=openid%20email%20profile"));
        assert!(url.contains("state=random-state"));
    }

    #[test]
    fn test_authorization_url_with_pkce() {
        let base_url = "https://auth.example.com/oauth2/authorize?client_id=test";
        let code_challenge = "challenge123";
        let code_challenge_method = "S256";

        let url = format!(
            "{}&code_challenge={}&code_challenge_method={}",
            base_url,
            urlencoding::encode(code_challenge),
            code_challenge_method
        );

        assert!(url.contains("code_challenge=challenge123"));
        assert!(url.contains("code_challenge_method=S256"));
    }

    #[test]
    fn test_authorization_url_with_nonce() {
        let base_url = "https://auth.example.com/oauth2/authorize?client_id=test";
        let nonce = "nonce456";

        let url = format!("{}&nonce={}", base_url, urlencoding::encode(nonce));

        assert!(url.contains("nonce=nonce456"));
    }

    // =========================================================================
    // ClaimMappings Tests
    // =========================================================================

    #[test]
    fn test_cognito_claim_mappings() {
        let mappings = ClaimMappings::cognito();
        assert_eq!(mappings.user_id, "sub");
        assert_eq!(mappings.tenant_id, Some("custom:tenant_id".to_string()));
        assert_eq!(mappings.email, Some("email".to_string()));
        assert_eq!(mappings.groups, Some("cognito:groups".to_string()));
    }

    #[test]
    fn test_cognito_claim_normalization() {
        let mappings = ClaimMappings::cognito();

        let claims = serde_json::json!({
            "sub": "user-123",
            "email": "user@example.com",
            "custom:tenant_id": "tenant-456",
            "cognito:groups": ["admin", "users"]
        });

        let normalized = mappings.normalize_claims(&claims);

        assert_eq!(
            normalized.get("sub").and_then(|v| v.as_str()),
            Some("user-123")
        );
        assert_eq!(
            normalized.get("email").and_then(|v| v.as_str()),
            Some("user@example.com")
        );
        assert_eq!(
            normalized.get("tenant_id").and_then(|v| v.as_str()),
            Some("tenant-456")
        );
        assert!(normalized.contains_key("groups"));
    }

    // =========================================================================
    // Error Message Tests
    // =========================================================================

    #[test]
    fn test_dcr_not_supported_message() {
        // Cognito doesn't support DCR - verify the error message
        let error_msg = "AWS Cognito does not support Dynamic Client Registration";
        assert!(error_msg.contains("Cognito"));
        assert!(error_msg.contains("Dynamic Client Registration"));
    }

    #[tokio::test]
    async fn test_dcr_returns_error() {
        // This test would require a mock provider, but we can verify the trait default
        use crate::server::auth::provider::IdentityProvider;

        // Create a mock that has the same behavior
        struct MockCognito;

        #[async_trait]
        impl IdentityProvider for MockCognito {
            fn id(&self) -> &'static str {
                "cognito"
            }
            fn display_name(&self) -> &'static str {
                "AWS Cognito"
            }
            fn capabilities(&self) -> ProviderCapabilities {
                ProviderCapabilities {
                    oidc: true,
                    dcr: false,
                    pkce: true,
                    refresh_tokens: true,
                    revocation: true,
                    introspection: false,
                    custom_scopes: true,
                    device_flow: false,
                }
            }
            #[allow(clippy::unnecessary_literal_bound)]
            fn issuer(&self) -> &str {
                "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_test"
            }
            async fn validate_token(&self, _token: &str) -> Result<AuthContext> {
                Ok(AuthContext::new("test-user"))
            }
            async fn discovery(&self) -> Result<OidcDiscovery> {
                unimplemented!()
            }
            async fn jwks(&self) -> Result<serde_json::Value> {
                unimplemented!()
            }
            async fn register_client(
                &self,
                _request: crate::server::auth::provider::DcrRequest,
            ) -> Result<crate::server::auth::provider::DcrResponse> {
                Err(crate::error::Error::protocol(
                    crate::error::ErrorCode::INVALID_REQUEST,
                    "AWS Cognito does not support Dynamic Client Registration",
                ))
            }
        }

        impl std::fmt::Debug for MockCognito {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct("MockCognito").finish()
            }
        }

        let provider = MockCognito;
        let request = crate::server::auth::provider::DcrRequest {
            redirect_uris: vec!["https://example.com/callback".to_string()],
            client_name: None,
            client_uri: None,
            logo_uri: None,
            contacts: vec![],
            token_endpoint_auth_method: None,
            grant_types: vec![],
            response_types: vec![],
            scope: None,
            software_id: None,
            software_version: None,
            extra: std::collections::HashMap::new(),
        };

        let result = provider.register_client(request).await;
        assert!(result.is_err());
    }
}