webgates-codecs 1.0.0

Framework-agnostic JWT codecs and validation helpers for webgates.
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
//! JWT claim types, codecs, validation helpers, and JWKS support.
//!
//! This module contains the main JWT-facing API of `webgates-codecs`.
//!
//! It provides:
//! - registered JWT claims via [`RegisteredClaims`]
//! - combined application and registered claims via [`JwtClaims`]
//! - a configurable JWT codec via [`JsonWebToken`] and [`JsonWebTokenOptions`]
//! - validation helpers in [`validation_service`] and [`validation_result`]
//! - JWKS helpers in [`jwks`]
//!
//! The implementation is framework-agnostic and depends only on shared types
//! from `webgates-core` plus the codec abstractions from this crate.
//!
//! Prefer the canonical module-owned public paths for validation helpers:
//! - [`validation_service::JwtValidationService`]
//! - [`validation_result::JwtValidationResult`]

use crate::errors::{JwtError, JwtOperation};
use crate::jwt::authority::JwtAuthority;
use crate::{Codec, Error, Result};

use std::collections::HashMap;
use std::collections::HashSet;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::sync::RwLock;

use chrono::Utc;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode_header};
use p384::elliptic_curve::rand_core::OsRng;
use p384::pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_with::skip_serializing_none;
use uuid::Uuid;

pub mod authority;
pub mod jwks;
pub mod remote_verifier;
pub mod validation_result;
pub mod validation_service;

fn validation_with_es384_only() -> Validation {
    let mut validation = Validation::new(Algorithm::ES384);
    validation.algorithms = vec![Algorithm::ES384];
    validation
}

fn canonical_es384_header_with_kid(kid: &str) -> Header {
    let mut header = Header::new(Algorithm::ES384);
    header.typ = Some("JWT".to_string());
    header.kid = Some(kid.to_string());
    header
}

/// File paths for an ES384 key pair managed on disk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Es384KeyPairPaths {
    private_key_path: PathBuf,
    public_key_path: PathBuf,
}

impl Es384KeyPairPaths {
    /// Creates key pair paths from explicit private and public key locations.
    pub fn new(private_key_path: impl Into<PathBuf>, public_key_path: impl Into<PathBuf>) -> Self {
        Self {
            private_key_path: private_key_path.into(),
            public_key_path: public_key_path.into(),
        }
    }

    /// Returns the private key file path.
    pub fn private_key_path(&self) -> &Path {
        &self.private_key_path
    }

    /// Returns the public key file path.
    pub fn public_key_path(&self) -> &Path {
        &self.public_key_path
    }

    /// Returns whether both key files currently exist.
    pub fn both_exist(&self) -> bool {
        self.private_key_path.is_file() && self.public_key_path.is_file()
    }
}

/// In-memory ES384 key material loaded from disk or generated on startup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Es384KeyPair {
    paths: Es384KeyPairPaths,
    private_key_pem: Vec<u8>,
    public_key_pem: Vec<u8>,
}

impl Es384KeyPair {
    /// Creates an in-memory key pair from explicit paths and PEM bytes.
    pub fn new(
        paths: Es384KeyPairPaths,
        private_key_pem: impl Into<Vec<u8>>,
        public_key_pem: impl Into<Vec<u8>>,
    ) -> Self {
        Self {
            paths,
            private_key_pem: private_key_pem.into(),
            public_key_pem: public_key_pem.into(),
        }
    }

    /// Returns the file paths associated with this key pair.
    pub fn paths(&self) -> &Es384KeyPairPaths {
        &self.paths
    }

    /// Returns the private key file path.
    pub fn private_key_path(&self) -> &Path {
        self.paths.private_key_path()
    }

    /// Returns the public key file path.
    pub fn public_key_path(&self) -> &Path {
        self.paths.public_key_path()
    }

    /// Returns the PEM-encoded private key bytes.
    pub fn private_key_pem(&self) -> &[u8] {
        &self.private_key_pem
    }

    /// Returns the PEM-encoded public key bytes.
    pub fn public_key_pem(&self) -> &[u8] {
        &self.public_key_pem
    }

    /// Converts the loaded key pair into JWT codec options.
    pub fn to_jwt_options(&self) -> Result<JsonWebTokenOptions> {
        JsonWebTokenOptions::from_es384_pem(&self.private_key_pem, &self.public_key_pem)
    }

    /// Builds a JWT codec directly from this loaded key pair.
    pub fn to_codec<P>(&self) -> Result<JsonWebToken<P>> {
        Ok(JsonWebToken::new_with_options(self.to_jwt_options()?))
    }

    /// Builds a JWT authority directly from this loaded key pair.
    pub fn to_authority<P>(&self) -> Result<JwtAuthority<P>>
    where
        P: Serialize + DeserializeOwned + Clone,
    {
        JwtAuthority::from_es384_pem(&self.private_key_pem, &self.public_key_pem)
    }
}

/// Loads or initializes an ES384 key pair from the filesystem.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Es384KeyPairLoader {
    paths: Es384KeyPairPaths,
}

impl Es384KeyPairLoader {
    /// Creates a new loader for the given private and public key paths.
    pub fn new(private_key_path: impl Into<PathBuf>, public_key_path: impl Into<PathBuf>) -> Self {
        Self {
            paths: Es384KeyPairPaths::new(private_key_path, public_key_path),
        }
    }

    /// Returns the configured key paths.
    pub fn paths(&self) -> &Es384KeyPairPaths {
        &self.paths
    }

    /// Creates the key pair if missing and then loads both PEM files.
    ///
    /// If both files already exist, they are reused unchanged. If neither file
    /// exists, a new ES384 key pair is generated, written to disk, and loaded.
    ///
    /// # Errors
    ///
    /// Returns an error when only one key file exists, when directories or
    /// files cannot be created or read, or when the resulting PEM bytes are not
    /// a valid ES384 key pair.
    pub async fn initialize_if_required(&self) -> Result<Es384KeyPair> {
        let private_exists = self.paths.private_key_path.is_file();
        let public_exists = self.paths.public_key_path.is_file();

        match (private_exists, public_exists) {
            (true, true) => self.load().await,
            (false, false) => {
                self.create_parent_directories().await?;
                let (private_key_pem, public_key_pem) = generate_es384_key_pair_pem()?;
                tokio::fs::write(&self.paths.private_key_path, &private_key_pem)
                    .await
                    .map_err(|error| {
                        Error::Jwt(JwtError::processing(
                            JwtOperation::Encode,
                            format!(
                                "failed to write ES384 private key `{}`: {error}",
                                self.paths.private_key_path.display()
                            ),
                        ))
                    })?;
                tokio::fs::write(&self.paths.public_key_path, &public_key_pem)
                    .await
                    .map_err(|error| {
                        Error::Jwt(JwtError::processing(
                            JwtOperation::Encode,
                            format!(
                                "failed to write ES384 public key `{}`: {error}",
                                self.paths.public_key_path.display()
                            ),
                        ))
                    })?;
                self.validate_loaded_pair(Es384KeyPair::new(
                    self.paths.clone(),
                    private_key_pem,
                    public_key_pem,
                ))
            }
            _ => Err(Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                format!(
                    "ES384 key initialization requires both key files to exist or neither to exist; private=`{}`, public=`{}`",
                    self.paths.private_key_path.display(),
                    self.paths.public_key_path.display()
                ),
            ))),
        }
    }

    /// Loads both PEM files from disk.
    ///
    /// # Errors
    ///
    /// Returns an error if either file cannot be read or if the loaded bytes do
    /// not form a valid ES384 key pair.
    pub async fn load(&self) -> Result<Es384KeyPair> {
        let private_key_pem = tokio::fs::read(&self.paths.private_key_path)
            .await
            .map_err(|error| {
                Error::Jwt(JwtError::processing(
                    JwtOperation::Decode,
                    format!(
                        "failed to read ES384 private key `{}`: {error}",
                        self.paths.private_key_path.display()
                    ),
                ))
            })?;
        let public_key_pem =
            tokio::fs::read(&self.paths.public_key_path)
                .await
                .map_err(|error| {
                    Error::Jwt(JwtError::processing(
                        JwtOperation::Decode,
                        format!(
                            "failed to read ES384 public key `{}`: {error}",
                            self.paths.public_key_path.display()
                        ),
                    ))
                })?;

        self.validate_loaded_pair(Es384KeyPair::new(
            self.paths.clone(),
            private_key_pem,
            public_key_pem,
        ))
    }

    async fn create_parent_directories(&self) -> Result<()> {
        if let Some(parent) = self.paths.private_key_path.parent()
            && !parent.as_os_str().is_empty()
        {
            tokio::fs::create_dir_all(parent).await.map_err(|error| {
                Error::Jwt(JwtError::processing(
                    JwtOperation::Encode,
                    format!(
                        "failed to create private key directory `{}`: {error}",
                        parent.display()
                    ),
                ))
            })?;
        }

        if let Some(parent) = self.paths.public_key_path.parent()
            && !parent.as_os_str().is_empty()
        {
            tokio::fs::create_dir_all(parent).await.map_err(|error| {
                Error::Jwt(JwtError::processing(
                    JwtOperation::Encode,
                    format!(
                        "failed to create public key directory `{}`: {error}",
                        parent.display()
                    ),
                ))
            })?;
        }

        Ok(())
    }

    fn validate_loaded_pair(&self, key_pair: Es384KeyPair) -> Result<Es384KeyPair> {
        key_pair.to_jwt_options()?;
        Ok(key_pair)
    }
}

fn generate_es384_key_pair_pem() -> Result<(Vec<u8>, Vec<u8>)> {
    let signing_key = p384::ecdsa::SigningKey::random(&mut OsRng);
    let verifying_key = signing_key.verifying_key();

    let private_key_pem = signing_key
        .to_pkcs8_pem(LineEnding::LF)
        .map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                format!("failed to encode ES384 private key as PKCS#8 PEM: {error}"),
            ))
        })?
        .to_string()
        .into_bytes();
    let public_key_pem = verifying_key
        .to_public_key_pem(LineEnding::LF)
        .map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                format!("failed to encode ES384 public key as PEM: {error}"),
            ))
        })?
        .into_bytes();

    Ok((private_key_pem, public_key_pem))
}

/// Registered claims defined by the JWT specification.
///
/// These are the standard metadata fields that travel alongside your
/// application-specific payload in a JWT.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[skip_serializing_none]
pub struct RegisteredClaims {
    /// Issuer of the JWT.
    #[serde(rename = "iss")]
    pub issuer: String,
    /// Subject of the JWT.
    #[serde(rename = "sub")]
    pub subject: Option<String>,
    /// Recipient for which the JWT is intended.
    #[serde(rename = "aud")]
    pub audience: Option<HashSet<String>>,
    /// Time after which the JWT expires.
    #[serde(rename = "exp")]
    pub expiration_time: u64,
    /// Time before which the JWT must not be accepted for processing.
    #[serde(rename = "nbf")]
    pub not_before_time: Option<u64>,
    /// Time at which the JWT was issued.
    #[serde(rename = "iat")]
    pub issued_at_time: u64,
    /// Unique token identifier.
    #[serde(rename = "jti")]
    pub jwt_id: Option<String>,
    /// Session identifier for session-backed tokens.
    #[serde(rename = "sid")]
    pub session_id: Option<String>,
}

impl RegisteredClaims {
    /// Creates new registered claims and sets `issued_at_time` to `Utc::now()`.
    pub fn new(issuer: &str, expiration_time: u64) -> Self {
        // chrono::DateTime::timestamp() returns i64; use a checked conversion so a
        // negative timestamp (clock correction, pre-epoch test date) does not wrap
        // silently to a very large u64 and produce a malformed `iat` claim.
        let issued_at_time = u64::try_from(Utc::now().timestamp()).unwrap_or(0);
        Self {
            issuer: issuer.to_string(),
            subject: None,
            audience: None,
            expiration_time,
            not_before_time: None,
            issued_at_time,
            jwt_id: Some(Uuid::now_v7().to_string()),
            session_id: None,
        }
    }

    /// Returns updated claims with an explicit session identifier.
    #[must_use]
    pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
        self.session_id = Some(session_id.into());
        self
    }
}

/// Combined registered and application-specific JWT claims.
///
/// This is the main typed claim container used with [`JsonWebToken<T>`].
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct JwtClaims<CustomClaims> {
    /// Standard JWT registered claims.
    #[serde(flatten)]
    pub registered_claims: RegisteredClaims,
    /// Application-specific claims.
    #[serde(flatten)]
    pub custom_claims: CustomClaims,
}

impl<CustomClaims> JwtClaims<CustomClaims> {
    /// Creates a new combined claims value.
    pub fn new(custom_claims: CustomClaims, registered_claims: RegisteredClaims) -> Self {
        Self {
            custom_claims,
            registered_claims,
        }
    }

    /// Returns `true` when the issuer matches `issuer`.
    pub fn has_issuer(&self, issuer: &str) -> bool {
        self.registered_claims.issuer == issuer
    }
}

/// Options used to configure a [`JsonWebToken`] codec.
///
/// Use this when you need explicit control over signing keys, verification keys,
/// key identifiers, or validation settings.
#[derive(Debug, Clone)]
pub struct JsonWebTokenOptions {
    /// Key for ES384 encoding.
    encoding_key: Option<EncodingKey>,
    /// Canonical key id used when minting JWTs.
    key_id: String,
    /// Public verification keys indexed by `kid`.
    decoding_keys_by_kid: HashMap<String, DecodingKey>,
    /// Legacy fallback verification key when no `kid` was provided in the token.
    fallback_decoding_key: Option<DecodingKey>,
    /// Header used for encoding.
    header: Header,
    /// Validation options used during decoding.
    validation: Validation,
}

const DEV_ES384_PRIVATE_KEY_PEM: &[u8] = br#"-----BEGIN PRIVATE KEY-----
MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCFT7MfRqWZfNgVX/cH
bxFTlPkBeCKqjsLkZXD/J3ZYHV1EtQksdrKtOzTr2hMs6pmhZANiAASyND9eQ5Qk
7ZteSEPMpExbVJenRWwyobExJMb62mmp3eA7Fszy8uBbLj8HRB16y3QbLcTxCBoo
ldBXfNFzM133OuTV2bBWXq5h34l+A0h4gU/odZ678LfAgnrRYMG4ZjU=
-----END PRIVATE KEY-----
"#;

const DEV_ES384_PUBLIC_KEY_PEM: &[u8] = br#"-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEsjQ/XkOUJO2bXkhDzKRMW1SXp0VsMqGx
MSTG+tppqd3gOxbM8vLgWy4/B0Qdest0Gy3E8QgaKJXQV3zRczNd9zrk1dmwVl6u
Yd+JfgNIeIFP6HWeu/C3wIJ60WDBuGY1
-----END PUBLIC KEY-----
"#;

impl Default for JsonWebTokenOptions {
    /// Creates ES384 encoding and decoding keys from built-in development keys.
    ///
    /// This default is intended for tests and local development only. Production
    /// deployments should provide explicit key material with
    /// [`JsonWebTokenOptions::from_es384_pem`].
    fn default() -> Self {
        match Self::from_es384_pem(DEV_ES384_PRIVATE_KEY_PEM, DEV_ES384_PUBLIC_KEY_PEM) {
            Ok(options) => options,
            Err(error) => panic!("failed to initialize default ES384 JWT options: {error}"),
        }
    }
}

impl JsonWebTokenOptions {
    /// Creates ES384 JWT options from PEM-encoded private and public keys.
    ///
    /// # Errors
    ///
    /// Returns a JWT processing error when either key cannot be parsed.
    pub fn from_es384_pem(private_key_pem: &[u8], public_key_pem: &[u8]) -> Result<Self> {
        let encoding_key = EncodingKey::from_ec_pem(private_key_pem).map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                format!("failed to parse ES384 private key: {error}"),
            ))
        })?;
        let decoding_key = DecodingKey::from_ec_pem(public_key_pem).map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Decode,
                format!("failed to parse ES384 public key: {error}"),
            ))
        })?;
        let key_id = jwks::es384_kid_from_public_key_pem(public_key_pem)?;
        let header = canonical_es384_header_with_kid(&key_id);
        let validation = validation_with_es384_only();
        let mut decoding_keys_by_kid = HashMap::new();
        decoding_keys_by_kid.insert(key_id.clone(), decoding_key.clone());

        Ok(Self {
            encoding_key: Some(encoding_key),
            key_id,
            decoding_keys_by_kid,
            fallback_decoding_key: Some(decoding_key),
            header,
            validation,
        })
    }

    /// Creates verification-only ES384 JWT options from a PEM public key.
    ///
    /// Codecs built from these options can decode and validate tokens but will
    /// reject encoding attempts.
    ///
    /// # Errors
    ///
    /// Returns a JWT processing error when the public key cannot be parsed.
    pub fn for_es384_verification_only(public_key_pem: &[u8]) -> Result<Self> {
        let decoding_key = DecodingKey::from_ec_pem(public_key_pem).map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Decode,
                format!("failed to parse ES384 public key: {error}"),
            ))
        })?;
        let key_id = jwks::es384_kid_from_public_key_pem(public_key_pem)?;
        let header = canonical_es384_header_with_kid(&key_id);
        let validation = validation_with_es384_only();
        let mut decoding_keys_by_kid = HashMap::new();
        decoding_keys_by_kid.insert(key_id.clone(), decoding_key.clone());

        Ok(Self {
            encoding_key: None,
            key_id,
            decoding_keys_by_kid,
            fallback_decoding_key: Some(decoding_key),
            header,
            validation,
        })
    }

    /// Creates verification-only ES384 options from JWKS keys.
    ///
    /// This enables key selection by `kid` and rejects JWTs that do not include
    /// a matching `kid`.
    ///
    /// # Errors
    ///
    /// Returns a JWT processing error if no valid ES384 verification key can be
    /// constructed from the provided JWKS entries.
    pub fn for_es384_jwks_keys(keys: &[jwks::EcP384Jwk]) -> Result<Self> {
        if keys.is_empty() {
            return Err(Error::Jwt(JwtError::processing(
                JwtOperation::Validate,
                "JWKS key set is empty",
            )));
        }

        let mut decoding_keys_by_kid = HashMap::new();
        for key in keys {
            let decoding_key = key.to_decoding_key()?;
            decoding_keys_by_kid.insert(key.kid.clone(), decoding_key);
        }

        let key_id = keys[0].kid.clone();
        let header = canonical_es384_header_with_kid(&key_id);
        let validation = validation_with_es384_only();

        Ok(Self {
            encoding_key: None,
            key_id,
            decoding_keys_by_kid,
            fallback_decoding_key: None,
            header,
            validation,
        })
    }

    /// Returns the active signing key id (`kid`).
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Returns the number of configured verification keys.
    pub fn verification_key_count(&self) -> usize {
        self.decoding_keys_by_kid.len()
    }

    /// Returns whether verification accepts missing `kid` by using a fallback
    /// decoding key.
    pub fn allows_missing_kid_fallback(&self) -> bool {
        self.fallback_decoding_key.is_some()
    }

    /// Returns updated options with an explicit `kid` for signing.
    ///
    /// This always keeps a canonical ES384 JWT header (`alg = ES384`,
    /// `typ = JWT`, `kid = ...`).
    pub fn with_key_id(mut self, key_id: impl Into<String>) -> Self {
        let key_id = key_id.into();
        self.key_id = key_id.clone();
        self.header = canonical_es384_header_with_kid(&key_id);
        self
    }

    /// Returns updated options with a replaced verification-key map.
    ///
    /// The first key is used as fallback only when
    /// `allow_missing_kid_fallback` is `true`.
    pub fn with_verification_keys(
        mut self,
        keys: HashMap<String, DecodingKey>,
        allow_missing_kid_fallback: bool,
    ) -> Self {
        let fallback = if allow_missing_kid_fallback {
            keys.values().next().cloned()
        } else {
            None
        };
        self.decoding_keys_by_kid = keys;
        self.fallback_decoding_key = fallback;
        self
    }

    /// Returns updated options with an added verification key.
    pub fn with_added_verification_key(mut self, kid: impl Into<String>, key: DecodingKey) -> Self {
        self.decoding_keys_by_kid.insert(kid.into(), key);
        self
    }

    /// Returns updated options with custom validation settings.
    pub fn with_validation(self, validation: Validation) -> Self {
        let mut validation = validation;
        validation.algorithms = vec![Algorithm::ES384];

        Self { validation, ..self }
    }
}

/// JWT codec backed by the `jsonwebtoken` crate.
///
/// This is the main codec implementation provided by the crate.
///
/// # Key management
///
/// The default constructor uses built-in ES384 development keys.
/// This is convenient for tests or local development.
///
/// For persistent sessions across restarts or multiple instances, construct the
/// codec with explicit keys via [`JsonWebToken::new_with_options`].
#[derive(Clone)]
pub struct JsonWebToken<P> {
    enc_key: Option<EncodingKey>,
    key_id: String,
    verification_state: std::sync::Arc<RwLock<VerificationState>>,
    header: Header,
    validation: Validation,
    phantom_payload: PhantomData<P>,
}

#[derive(Clone)]
struct VerificationState {
    dec_keys_by_kid: HashMap<String, DecodingKey>,
    fallback_dec_key: Option<DecodingKey>,
}

impl<P> JsonWebToken<P> {
    /// Creates a codec from explicit options.
    ///
    /// Use this when you need explicit signing or verification configuration.
    pub fn new_with_options(options: JsonWebTokenOptions) -> Self {
        let JsonWebTokenOptions {
            encoding_key,
            key_id,
            decoding_keys_by_kid,
            fallback_decoding_key,
            header,
            validation,
        } = options;

        Self {
            enc_key: encoding_key,
            key_id,
            verification_state: std::sync::Arc::new(RwLock::new(VerificationState {
                dec_keys_by_kid: decoding_keys_by_kid,
                fallback_dec_key: fallback_decoding_key,
            })),
            header,
            validation,
            phantom_payload: PhantomData,
        }
    }

    /// Returns the signing `kid` used by this codec.
    pub fn key_id(&self) -> &str {
        &self.key_id
    }

    /// Returns the number of currently configured verification keys.
    pub fn verification_key_count(&self) -> usize {
        self.verification_state
            .read()
            .map(|state| state.dec_keys_by_kid.len())
            .unwrap_or(0)
    }

    /// Returns whether a verification key for the given `kid` exists.
    pub fn has_verification_key(&self, kid: &str) -> bool {
        self.verification_state
            .read()
            .map(|state| state.dec_keys_by_kid.contains_key(kid))
            .unwrap_or(false)
    }

    /// Returns whether this codec allows verification without `kid`.
    pub fn allows_missing_kid_fallback(&self) -> bool {
        self.verification_state
            .read()
            .map(|state| state.fallback_dec_key.is_some())
            .unwrap_or(false)
    }

    /// Atomically replaces all verification keys.
    pub fn replace_verification_keys(
        &self,
        keys: HashMap<String, DecodingKey>,
        allow_missing_kid_fallback: bool,
    ) {
        if let Ok(mut state) = self.verification_state.write() {
            let fallback = if allow_missing_kid_fallback {
                keys.values().next().cloned()
            } else {
                None
            };
            state.dec_keys_by_kid = keys;
            state.fallback_dec_key = fallback;
        }
    }

    /// Atomically replaces all verification keys from canonical ES384 JWK entries.
    ///
    /// # Errors
    ///
    /// Returns an error when any provided key cannot be converted.
    pub fn replace_verification_keys_from_jwks(
        &self,
        keys: &[jwks::EcP384Jwk],
        allow_missing_kid_fallback: bool,
    ) -> Result<()> {
        let mut decoding_keys = HashMap::new();
        for key in keys {
            let decoding_key = key.to_decoding_key()?;
            decoding_keys.insert(key.kid.clone(), decoding_key);
        }
        self.replace_verification_keys(decoding_keys, allow_missing_kid_fallback);
        Ok(())
    }

    fn decoding_key_for_header(&self, header: &Header) -> Result<DecodingKey> {
        if header.alg != Algorithm::ES384 {
            return Err(Error::Jwt(JwtError::processing(
                JwtOperation::Validate,
                format!(
                    "JWT header algorithm mismatch: expected ES384 but got {:?}",
                    header.alg
                ),
            )));
        }

        if header.typ.as_deref() != Some("JWT") {
            return Err(Error::Jwt(JwtError::processing(
                JwtOperation::Validate,
                "JWT header `typ` must be `JWT`",
            )));
        }

        let state = self.verification_state.read().map_err(|_| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Validate,
                "verification key state lock is poisoned",
            ))
        })?;

        if let Some(kid) = header.kid.as_deref() {
            return state.dec_keys_by_kid.get(kid).cloned().ok_or_else(|| {
                Error::Jwt(JwtError::processing(
                    JwtOperation::Validate,
                    format!("JWT `kid` `{kid}` is not configured for verification"),
                ))
            });
        }

        state.fallback_dec_key.clone().ok_or_else(|| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Validate,
                "JWT header is missing `kid` and no fallback verification key is configured",
            ))
        })
    }
}

impl<P> Default for JsonWebToken<P> {
    fn default() -> Self {
        Self::new_with_options(JsonWebTokenOptions::default())
    }
}

impl<P> Codec for JsonWebToken<P>
where
    P: Serialize + DeserializeOwned + Clone,
{
    type Payload = P;

    fn encode(&self, payload: &Self::Payload) -> Result<Vec<u8>> {
        let Some(enc_key) = &self.enc_key else {
            return Err(Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                "JWT encoding key is not configured for this codec",
            )));
        };
        let token = jsonwebtoken::encode(&self.header, payload, enc_key).map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Encode,
                format!("JWT encoding failed: {error}"),
            ))
        })?;

        Ok(token.into_bytes())
    }

    fn decode(&self, encoded_value: &[u8]) -> Result<Self::Payload> {
        let header = decode_header(std::str::from_utf8(encoded_value).map_err(|error| {
            Error::Jwt(JwtError::processing(
                JwtOperation::Decode,
                format!("JWT bytes are not valid UTF-8: {error}"),
            ))
        })?)
        .map_err(|error| {
            Error::Jwt(JwtError::processing_with_preview(
                JwtOperation::Decode,
                format!("JWT header decoding failed: {error}"),
                Some(format!("token_len={}", encoded_value.len())),
            ))
        })?;

        let decoding_key = self.decoding_key_for_header(&header)?;

        let claims =
            jsonwebtoken::decode::<Self::Payload>(encoded_value, &decoding_key, &self.validation)
                .map_err(|error| {
                // Do not include token bytes in the error to avoid leaking token
                // material into logs or error messages if log levels are
                // misconfigured.  Report only the byte length for diagnostics.
                Error::Jwt(JwtError::processing_with_preview(
                    JwtOperation::Decode,
                    format!("JWT decoding failed: {error}"),
                    Some(format!("token_len={}", encoded_value.len())),
                ))
            })?;

        Ok(claims.claims)
    }
}