jwt-verify 0.1.0

JWT verification library for AWS Cognito tokens and any OIDC-compatible IDP
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
use std::collections::HashSet;
use std::time::Duration;

use crate::claims::ClaimValidator;
use crate::common::error::{ErrorVerbosity, JwtError};
use crate::oidc::discovery::{DiscoveryDocument, OidcDiscovery};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenUse {
    /// ID token - used for authentication and contains user identity information
    Id,
    /// Access token - used for authorization and contains scopes/permissions
    Access,
}

impl TokenUse {
    /// Get the string representation of the token use
    pub fn as_str(&self) -> &'static str {
        match self {
            TokenUse::Id => "id",
            TokenUse::Access => "access",
        }
    }

    /// Create a TokenUse from a string
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "id" => Some(TokenUse::Id),
            "access" => Some(TokenUse::Access),
            _ => None,
        }
    }
}

/// Configuration for OIDC providers.
///
/// This struct holds all configuration options for verifying JWTs from OIDC-compatible
/// identity providers, including issuer URL, JWKS URL, allowed client IDs, token types,
/// clock skew, cache duration, required claims, custom validators, and error verbosity.
///
/// The configuration is immutable after creation, but can be modified using the builder
/// pattern methods like `with_clock_skew`, `with_cache_duration`, etc.
///
/// # Examples
///
/// ```
/// use jwt_verify::oidc::OidcProviderConfig;
/// use std::time::Duration;
///
/// // Create a basic configuration
/// let config = OidcProviderConfig::new(
///     "https://accounts.example.com",
///     Some("https://accounts.example.com/.well-known/jwks.json"),
///     &["client1".to_string()],
/// ).unwrap();
///
/// // Create a configuration with custom settings
/// let config = OidcProviderConfig::new(
///     "https://accounts.example.com",
///     None, // Will use discovery to find JWKS URL
///     &["client1".to_string()],
/// ).unwrap()
///     .with_clock_skew(Duration::from_secs(120))
///     .with_cache_duration(Duration::from_secs(3600 * 12));
/// ```
pub struct OidcProviderConfig {
    /// OIDC issuer URL
    pub issuer: String,
    /// JWKS URL (optional, can be discovered from issuer)
    pub jwks_url: Option<String>,
    /// List of allowed client IDs for this provider
    pub client_ids: Vec<String>,
    /// List of allowed token types (ID tokens, Access tokens)
    pub allowed_token_uses: Vec<TokenUse>,
    /// Clock skew tolerance for token expiration and issuance time validation
    pub clock_skew: Duration,
    /// Duration for which JWKs are cached before refreshing
    pub jwk_cache_duration: Duration,
    /// Duration for which discovery documents are cached before refreshing
    pub discovery_cache_duration: Duration,
    /// Set of claims that must be present and valid in the token
    pub required_claims: HashSet<String>,
    /// List of custom validators for additional claim validation
    #[allow(clippy::type_complexity)]
    pub custom_validators: Vec<Box<dyn ClaimValidator + Send + Sync>>,
    /// Level of detail in error messages
    pub error_verbosity: ErrorVerbosity,
    /// Whether to use auto-discovery for JWKS URL
    pub use_discovery: bool,
}

// Manual implementation of Debug for OidcProviderConfig since custom_validators doesn't implement Debug
impl std::fmt::Debug for OidcProviderConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OidcProviderConfig")
            .field("issuer", &self.issuer)
            .field("jwks_url", &self.jwks_url)
            .field("client_ids", &self.client_ids)
            .field("clock_skew", &self.clock_skew)
            .field("jwk_cache_duration", &self.jwk_cache_duration)
            .field("discovery_cache_duration", &self.discovery_cache_duration)
            .field("required_claims", &self.required_claims)
            .field(
                "custom_validators",
                &format!("[{} validators]", self.custom_validators.len()),
            )
            .field("error_verbosity", &self.error_verbosity)
            .field("use_discovery", &self.use_discovery)
            .finish()
    }
}

// Manual implementation of Clone for OidcProviderConfig since custom_validators doesn't implement Clone
impl Clone for OidcProviderConfig {
    fn clone(&self) -> Self {
        Self {
            issuer: self.issuer.clone(),
            jwks_url: self.jwks_url.clone(),
            client_ids: self.client_ids.clone(),
            allowed_token_uses: self.allowed_token_uses.clone(),
            clock_skew: self.clock_skew,
            jwk_cache_duration: self.jwk_cache_duration,
            discovery_cache_duration: self.discovery_cache_duration,
            required_claims: self.required_claims.clone(),
            custom_validators: Vec::new(), // Custom validators can't be cloned, so we create an empty vector
            error_verbosity: self.error_verbosity,
            use_discovery: self.use_discovery,
        }
    }
}

impl OidcProviderConfig {
    /// Create a new OIDC provider configuration with validation for required parameters.
    ///
    /// This method creates a new `OidcProviderConfig` with the specified issuer URL,
    /// optional JWKS URL, and client IDs. It validates that the issuer URL is not empty
    /// and is a valid URL.
    ///
    /// # Parameters
    ///
    /// * `issuer` - OIDC issuer URL (e.g., "https://accounts.example.com")
    /// * `jwks_url` - Optional JWKS URL (if None, will be discovered from issuer)
    /// * `client_ids` - List of allowed client IDs for this provider
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the new `OidcProviderConfig` if successful, or a `JwtError`
    /// if validation fails.
    ///
    /// # Errors
    ///
    /// Returns a `JwtError::ConfigurationError` if:
    /// - The issuer URL is empty
    /// - The issuer URL is not a valid URL
    /// - The JWKS URL is provided but is not a valid URL
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    ///
    /// // Create a basic configuration
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     Some("https://accounts.example.com/.well-known/jwks.json"),
    ///     &["client1".to_string()],
    /// ).unwrap();
    /// ```
    pub fn new(
        issuer: &str,
        jwks_url: Option<&str>,
        client_ids: &[String],
        token_uses: Option<Vec<TokenUse>>,
    ) -> Result<Self, JwtError> {
        // Validate issuer
        if issuer.is_empty() {
            return Err(JwtError::ConfigurationError {
                parameter: Some("issuer".to_string()),
                error: "Issuer URL cannot be empty".to_string(),
            });
        }

        // Validate issuer URL format
        if !issuer.starts_with("http://") && !issuer.starts_with("https://") {
            return Err(JwtError::ConfigurationError {
                parameter: Some("issuer".to_string()),
                error: "Issuer URL must start with http:// or https://".to_string(),
            });
        }

        // Validate JWKS URL format if provided
        if let Some(url) = jwks_url {
            if !url.starts_with("http://") && !url.starts_with("https://") {
                return Err(JwtError::ConfigurationError {
                    parameter: Some("jwks_url".to_string()),
                    error: "JWKS URL must start with http:// or https://".to_string(),
                });
            }
        }

        let token_uses = match token_uses {
            None => vec![TokenUse::Id, TokenUse::Access],
            Some(tu) => tu,
        };

        Ok(Self {
            issuer: issuer.to_string(),
            jwks_url: jwks_url.map(|s| s.to_string()),
            client_ids: client_ids.to_vec(),
            allowed_token_uses: token_uses,
            clock_skew: Duration::from_secs(60), // Default: 1 minute
            jwk_cache_duration: Duration::from_secs(3600 * 24), // Default: 24 hours
            discovery_cache_duration: Duration::from_secs(3600 * 24), // Default: 24 hours
            required_claims: HashSet::from([
                "sub".to_string(),
                "iss".to_string(),
                "aud".to_string(),
                "exp".to_string(),
                "iat".to_string(),
            ]),
            custom_validators: Vec::new(),
            error_verbosity: ErrorVerbosity::Standard,
            use_discovery: jwks_url.is_none(), // Use discovery if no JWKS URL is provided
        })
    }

    /// Create a new OIDC provider configuration with auto-discovery.
    ///
    /// This method creates a new `OidcProviderConfig` that will use auto-discovery
    /// to find the JWKS URL and other OIDC provider configuration.
    ///
    /// # Parameters
    ///
    /// * `issuer` - OIDC issuer URL (e.g., "https://accounts.example.com")
    /// * `client_ids` - List of allowed client IDs for this provider
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the new `OidcProviderConfig` if successful, or a `JwtError`
    /// if validation fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    ///
    /// // Create a configuration with auto-discovery
    /// let config = OidcProviderConfig::with_discovery(
    ///     "https://accounts.example.com",
    ///     &["client1".to_string()],
    /// ).unwrap();
    /// ```
    pub fn with_discovery(issuer: &str, client_ids: &[String]) -> Result<Self, JwtError> {
        let mut config = Self::new(issuer, None, client_ids, None)?;
        config.use_discovery = true;
        Ok(config)
    }

    /// Enable or disable auto-discovery.
    ///
    /// When auto-discovery is enabled, the JWKS URL will be discovered from the
    /// OIDC provider's well-known endpoint. When disabled, the JWKS URL must be
    /// provided explicitly.
    ///
    /// # Parameters
    ///
    /// * `use_discovery` - Whether to use auto-discovery
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the updated auto-discovery setting.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     Some("https://accounts.example.com/.well-known/jwks.json"),
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .set_discovery_enabled(true); // Enable auto-discovery even though JWKS URL is provided
    /// ```
    pub fn set_discovery_enabled(mut self, use_discovery: bool) -> Self {
        self.use_discovery = use_discovery;
        self
    }

    /// Set clock skew tolerance for token validation.
    ///
    /// Clock skew is used to account for time differences between the token issuer
    /// and the token verifier. This is important for validating token expiration
    /// and issuance times.
    ///
    /// # Parameters
    ///
    /// * `skew` - The clock skew duration to allow (default: 60 seconds)
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the updated clock skew.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    /// use std::time::Duration;
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_clock_skew(Duration::from_secs(120)); // 2 minutes
    /// ```
    pub fn with_clock_skew(mut self, skew: Duration) -> Self {
        self.clock_skew = skew;
        self
    }

    /// Set JWK cache duration for key management.
    ///
    /// This determines how long JWKs (JSON Web Keys) are cached before being refreshed
    /// from the OIDC provider endpoint. Longer durations reduce network requests but may
    /// delay key rotation recognition.
    ///
    /// # Parameters
    ///
    /// * `duration` - The cache duration (default: 24 hours)
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the updated cache duration.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    /// use std::time::Duration;
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_cache_duration(Duration::from_secs(3600 * 12)); // 12 hours
    /// ```
    pub fn with_cache_duration(mut self, duration: Duration) -> Self {
        self.jwk_cache_duration = duration;
        self
    }

    /// Set discovery cache duration.
    ///
    /// This determines how long OIDC discovery documents are cached before being refreshed
    /// from the OIDC provider endpoint. Longer durations reduce network requests but may
    /// delay configuration changes recognition.
    ///
    /// # Parameters
    ///
    /// * `duration` - The cache duration (default: 24 hours)
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the updated discovery cache duration.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    /// use std::time::Duration;
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_discovery_cache_duration(Duration::from_secs(3600 * 12)); // 12 hours
    /// ```
    pub fn with_discovery_cache_duration(mut self, duration: Duration) -> Self {
        self.discovery_cache_duration = duration;
        self
    }

    /// Add a required claim to the validation process.
    ///
    /// Required claims must be present in the token and will be validated.
    /// By default, the following claims are required: "sub", "iss", "aud", "exp", "iat".
    ///
    /// # Parameters
    ///
    /// * `claim` - The name of the claim to require
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the added required claim.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_required_claim("nonce");
    /// ```
    pub fn with_required_claim(mut self, claim: &str) -> Self {
        self.required_claims.insert(claim.to_string());
        self
    }

    /// Add a custom validator for additional claim validation.
    ///
    /// Custom validators allow for application-specific validation logic beyond
    /// the standard JWT claim validation. They can validate specific claim values,
    /// formats, or relationships between claims.
    ///
    /// # Parameters
    ///
    /// * `validator` - A boxed implementation of the `ClaimValidator` trait
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the added custom validator.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::{oidc::OidcProviderConfig, StringValueValidator};
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_custom_validator(Box::new(StringValueValidator::new(
    ///         "app_id", "my-application"
    ///     )));
    /// ```
    pub fn with_custom_validator(
        mut self,
        validator: Box<dyn ClaimValidator + Send + Sync>,
    ) -> Self {
        self.custom_validators.push(validator);
        self
    }

    /// Set the error verbosity level for error reporting.
    ///
    /// This controls how much detail is included in error messages and logs.
    /// Higher verbosity levels include more information but may expose sensitive data.
    ///
    /// # Parameters
    ///
    /// * `verbosity` - The error verbosity level (default: Standard)
    ///
    /// # Returns
    ///
    /// Returns a new `OidcProviderConfig` with the updated error verbosity.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::{oidc::OidcProviderConfig, ErrorVerbosity};
    ///
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap()
    ///     .with_error_verbosity(ErrorVerbosity::Detailed);
    /// ```
    pub fn with_error_verbosity(mut self, verbosity: ErrorVerbosity) -> Self {
        self.error_verbosity = verbosity;
        self
    }

    /// Get the well-known configuration URL for the OIDC provider.
    ///
    /// This URL is used to discover the OIDC provider configuration, including
    /// the JWKS URL, if not explicitly provided.
    ///
    /// # Returns
    ///
    /// Returns the well-known configuration URL for the OIDC provider.
    pub fn get_well_known_url(&self) -> String {
        format!(
            "{}/.well-known/openid-configuration",
            self.issuer.trim_end_matches('/')
        )
    }

    /// Discover the JWKS URL from the OIDC provider's well-known endpoint.
    ///
    /// This method fetches the OIDC provider configuration from the well-known
    /// endpoint and extracts the JWKS URL.
    ///
    /// # Parameters
    ///
    /// * `discovery` - The OIDC discovery service to use
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the JWKS URL if successful, or a `JwtError`
    /// if discovery fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::{OidcProviderConfig, OidcDiscovery};
    /// use std::time::Duration;
    ///
    /// // Create a discovery service
    /// let discovery = OidcDiscovery::new(Duration::from_secs(3600));
    ///
    /// // Create a configuration
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap();
    ///
    /// // Discover the JWKS URL
    /// // let jwks_url = config.discover_jwks_url(&discovery).await.unwrap();
    /// ```
    pub async fn discover_jwks_url(&self, discovery: &OidcDiscovery) -> Result<String, JwtError> {
        // If we have a JWKS URL and aren't using discovery, return it
        if let Some(url) = &self.jwks_url {
            if !self.use_discovery {
                return Ok(url.clone());
            }
        }

        // Otherwise, discover the JWKS URL
        let document = discovery
            .discover_with_fallback(&self.issuer, self.jwks_url.as_deref())
            .await?;
        Ok(document.jwks_uri.clone())
    }

    /// Discover the OIDC provider configuration.
    ///
    /// This method fetches the OIDC provider configuration from the well-known
    /// endpoint or uses the provided JWKS URL to create a minimal configuration.
    ///
    /// # Parameters
    ///
    /// * `discovery` - The OIDC discovery service to use
    ///
    /// # Returns
    ///
    /// Returns a `Result` containing the discovery document if successful, or a `JwtError`
    /// if discovery fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::{OidcProviderConfig, OidcDiscovery};
    /// use std::time::Duration;
    ///
    /// // Create a discovery service
    /// let discovery = OidcDiscovery::new(Duration::from_secs(3600));
    ///
    /// // Create a configuration
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap();
    ///
    /// // Discover the OIDC provider configuration
    /// // let document = config.discover(&discovery).await.unwrap();
    /// ```
    pub async fn discover(&self, discovery: &OidcDiscovery) -> Result<DiscoveryDocument, JwtError> {
        if self.use_discovery {
            // Use discovery to get the full configuration
            discovery
                .discover_with_fallback(&self.issuer, self.jwks_url.as_deref())
                .await
        } else if let Some(jwks_url) = &self.jwks_url {
            // Create a minimal configuration with the provided JWKS URL
            Ok(DiscoveryDocument::new(&self.issuer, jwks_url))
        } else {
            // No JWKS URL and not using discovery
            Err(JwtError::ConfigurationError {
                parameter: Some("jwks_url".to_string()),
                error: "JWKS URL is required when auto-discovery is disabled".to_string(),
            })
        }
    }

    /// Create a new OIDC discovery service based on the configuration.
    ///
    /// This method creates a new `OidcDiscovery` instance with the cache duration
    /// specified in the configuration.
    ///
    /// # Returns
    ///
    /// Returns a new `OidcDiscovery` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use jwt_verify::oidc::OidcProviderConfig;
    ///
    /// // Create a configuration
    /// let config = OidcProviderConfig::new(
    ///     "https://accounts.example.com",
    ///     None,
    ///     &["client1".to_string()],
    /// ).unwrap();
    ///
    /// // Create a discovery service
    /// let discovery = config.create_discovery();
    /// ```
    pub fn create_discovery(&self) -> OidcDiscovery {
        OidcDiscovery::new(self.discovery_cache_duration)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_valid_config() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            Some("https://accounts.example.com/.well-known/jwks.json"),
            &["client1".to_string()],
            None,
        );
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.issuer, "https://accounts.example.com");
        assert_eq!(
            config.jwks_url,
            Some("https://accounts.example.com/.well-known/jwks.json".to_string())
        );
        assert_eq!(config.client_ids, vec!["client1".to_string()]);
        assert!(!config.use_discovery); // Should not use discovery when JWKS URL is provided
    }

    #[test]
    fn test_new_with_discovery() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        );
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.issuer, "https://accounts.example.com");
        assert_eq!(config.jwks_url, None);
        assert!(config.use_discovery); // Should use discovery when no JWKS URL is provided
    }

    #[test]
    fn test_with_discovery_explicit() {
        let config = OidcProviderConfig::with_discovery(
            "https://accounts.example.com",
            &["client1".to_string()],
        );
        assert!(config.is_ok());
        let config = config.unwrap();
        assert_eq!(config.issuer, "https://accounts.example.com");
        assert_eq!(config.jwks_url, None);
        assert!(config.use_discovery); // Should use discovery when explicitly requested
    }

    #[test]
    fn test_new_empty_issuer() {
        let config = OidcProviderConfig::new(
            "",
            Some("https://accounts.example.com/.well-known/jwks.json"),
            &["client1".to_string()],
            None,
        );
        assert!(config.is_err());
        match config.unwrap_err() {
            JwtError::ConfigurationError { parameter, .. } => {
                assert_eq!(parameter, Some("issuer".to_string()));
            }
            _ => panic!("Expected ConfigurationError"),
        }
    }

    #[test]
    fn test_new_invalid_issuer_url() {
        let config = OidcProviderConfig::new(
            "invalid-url",
            Some("https://accounts.example.com/.well-known/jwks.json"),
            &["client1".to_string()],
            None,
        );
        assert!(config.is_err());
        match config.unwrap_err() {
            JwtError::ConfigurationError { parameter, .. } => {
                assert_eq!(parameter, Some("issuer".to_string()));
            }
            _ => panic!("Expected ConfigurationError"),
        }
    }

    #[test]
    fn test_new_invalid_jwks_url() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            Some("invalid-url"),
            &["client1".to_string()],
            None,
        );
        assert!(config.is_err());
        match config.unwrap_err() {
            JwtError::ConfigurationError { parameter, .. } => {
                assert_eq!(parameter, Some("jwks_url".to_string()));
            }
            _ => panic!("Expected ConfigurationError"),
        }
    }

    #[test]
    fn test_with_clock_skew() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .with_clock_skew(Duration::from_secs(120));
        assert_eq!(config.clock_skew, Duration::from_secs(120));
    }

    #[test]
    fn test_with_cache_duration() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .with_cache_duration(Duration::from_secs(3600 * 12));
        assert_eq!(config.jwk_cache_duration, Duration::from_secs(3600 * 12));
    }

    #[test]
    fn test_with_discovery_cache_duration() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .with_discovery_cache_duration(Duration::from_secs(3600 * 6));
        assert_eq!(
            config.discovery_cache_duration,
            Duration::from_secs(3600 * 6)
        );
    }

    #[test]
    fn test_with_required_claim() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .with_required_claim("nonce");
        assert!(config.required_claims.contains("nonce"));
    }

    #[test]
    fn test_with_discovery_flag() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            Some("https://accounts.example.com/.well-known/jwks.json"),
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .set_discovery_enabled(true);
        assert!(config.use_discovery);

        let config = config.set_discovery_enabled(false);
        assert!(!config.use_discovery);
    }

    #[test]
    fn test_get_well_known_url() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap();
        assert_eq!(
            config.get_well_known_url(),
            "https://accounts.example.com/.well-known/openid-configuration"
        );

        // Test with trailing slash
        let config = OidcProviderConfig::new(
            "https://accounts.example.com/",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap();
        assert_eq!(
            config.get_well_known_url(),
            "https://accounts.example.com/.well-known/openid-configuration"
        );
    }

    #[test]
    fn test_create_discovery() {
        let config = OidcProviderConfig::new(
            "https://accounts.example.com",
            None,
            &["client1".to_string()],
            None,
        )
        .unwrap()
        .with_discovery_cache_duration(Duration::from_secs(7200));

        let discovery = config.create_discovery();
        assert_eq!(discovery.get_cache_duration(), Duration::from_secs(7200));
    }
}