jsonwebtoken 11.0.0

Create and decode JWTs in a strongly typed way.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
//! This crate contains types only for working JWK and JWK Sets
//! This is only meant to be used to deal with public JWK, not generate ones.
//! Most of the code in this file is taken from <https://github.com/lawliet89/biscuit> but
//! tweaked to remove the private bits as it's not the goal for this crate currently.

use std::collections::BTreeMap;
use std::{fmt, str::FromStr};

use serde::{Deserialize, Deserializer, Serialize, Serializer, de};

use crate::crypto::{CryptoProvider, ec_pub_components_from_public_key};
use crate::errors::{self, Error, ErrorKind, new_error};
use crate::serialization::b64_encode;
use crate::{Algorithm, AlgorithmFamily, DecodingKey, EncodingKey, decoding::DecodingKeyKind};

/// The intended usage of the public `KeyType`. This enum is serialized `untagged`
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum PublicKeyUse {
    /// Indicates a public key is meant for signature verification
    Signature,
    /// Indicates a public key is meant for encryption
    Encryption,
    /// Other usage
    Other(String),
}

impl Serialize for PublicKeyUse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let string = match self {
            PublicKeyUse::Signature => "sig",
            PublicKeyUse::Encryption => "enc",
            PublicKeyUse::Other(other) => other,
        };

        serializer.serialize_str(string)
    }
}

impl<'de> Deserialize<'de> for PublicKeyUse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct PublicKeyUseVisitor;
        impl de::Visitor<'_> for PublicKeyUseVisitor {
            type Value = PublicKeyUse;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "a string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(match v {
                    "sig" => PublicKeyUse::Signature,
                    "enc" => PublicKeyUse::Encryption,
                    other => PublicKeyUse::Other(other.to_string()),
                })
            }
        }

        deserializer.deserialize_string(PublicKeyUseVisitor)
    }
}

/// Operations that the key is intended to be used for. This enum is serialized `untagged`
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum KeyOperations {
    /// Computer digital signature or MAC
    Sign,
    /// Verify digital signature or MAC
    Verify,
    /// Encrypt content
    Encrypt,
    /// Decrypt content and validate decryption, if applicable
    Decrypt,
    /// Encrypt key
    WrapKey,
    /// Decrypt key and validate decryption, if applicable
    UnwrapKey,
    /// Derive key
    DeriveKey,
    /// Derive bits not to be used as a key
    DeriveBits,
    /// Other operation
    Other(String),
}

impl Serialize for KeyOperations {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let string = match self {
            KeyOperations::Sign => "sign",
            KeyOperations::Verify => "verify",
            KeyOperations::Encrypt => "encrypt",
            KeyOperations::Decrypt => "decrypt",
            KeyOperations::WrapKey => "wrapKey",
            KeyOperations::UnwrapKey => "unwrapKey",
            KeyOperations::DeriveKey => "deriveKey",
            KeyOperations::DeriveBits => "deriveBits",
            KeyOperations::Other(other) => other,
        };

        serializer.serialize_str(string)
    }
}

impl<'de> Deserialize<'de> for KeyOperations {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct KeyOperationsVisitor;
        impl de::Visitor<'_> for KeyOperationsVisitor {
            type Value = KeyOperations;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "a string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(match v {
                    "sign" => KeyOperations::Sign,
                    "verify" => KeyOperations::Verify,
                    "encrypt" => KeyOperations::Encrypt,
                    "decrypt" => KeyOperations::Decrypt,
                    "wrapKey" => KeyOperations::WrapKey,
                    "unwrapKey" => KeyOperations::UnwrapKey,
                    "deriveKey" => KeyOperations::DeriveKey,
                    "deriveBits" => KeyOperations::DeriveBits,
                    other => KeyOperations::Other(other.to_string()),
                })
            }
        }

        deserializer.deserialize_string(KeyOperationsVisitor)
    }
}

/// The algorithms of the keys
#[allow(non_camel_case_types, clippy::upper_case_acronyms)]
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum KeyAlgorithm {
    /// HMAC using SHA-256
    HS256,
    /// HMAC using SHA-384
    HS384,
    /// HMAC using SHA-512
    HS512,

    /// ECDSA using SHA-256
    ES256,
    /// ECDSA using SHA-384
    ES384,

    /// RSASSA-PKCS1-v1_5 using SHA-256
    RS256,
    /// RSASSA-PKCS1-v1_5 using SHA-384
    RS384,
    /// RSASSA-PKCS1-v1_5 using SHA-512
    RS512,

    /// RSASSA-PSS using SHA-256
    PS256,
    /// RSASSA-PSS using SHA-384
    PS384,
    /// RSASSA-PSS using SHA-512
    PS512,

    /// Edwards-curve Digital Signature Algorithm (EdDSA)
    EdDSA,

    /// RSAES-PKCS1-V1_5
    RSA1_5,

    /// RSAES-OAEP using SHA-1
    #[serde(rename = "RSA-OAEP")]
    RSA_OAEP,

    /// RSAES-OAEP-256 using SHA-2
    #[serde(rename = "RSA-OAEP-256")]
    RSA_OAEP_256,

    /// Catch-All for when the key algorithm can not be determined or is not supported
    #[serde(other)]
    UNKNOWN_ALGORITHM,
}

impl FromStr for KeyAlgorithm {
    type Err = Error;
    fn from_str(s: &str) -> errors::Result<Self> {
        match s {
            "HS256" => Ok(KeyAlgorithm::HS256),
            "HS384" => Ok(KeyAlgorithm::HS384),
            "HS512" => Ok(KeyAlgorithm::HS512),
            "ES256" => Ok(KeyAlgorithm::ES256),
            "ES384" => Ok(KeyAlgorithm::ES384),
            "RS256" => Ok(KeyAlgorithm::RS256),
            "RS384" => Ok(KeyAlgorithm::RS384),
            "PS256" => Ok(KeyAlgorithm::PS256),
            "PS384" => Ok(KeyAlgorithm::PS384),
            "PS512" => Ok(KeyAlgorithm::PS512),
            "RS512" => Ok(KeyAlgorithm::RS512),
            "EdDSA" => Ok(KeyAlgorithm::EdDSA),
            "RSA1_5" => Ok(KeyAlgorithm::RSA1_5),
            "RSA-OAEP" => Ok(KeyAlgorithm::RSA_OAEP),
            "RSA-OAEP-256" => Ok(KeyAlgorithm::RSA_OAEP_256),
            _ => Err(ErrorKind::InvalidAlgorithmName.into()),
        }
    }
}

impl From<Algorithm> for KeyAlgorithm {
    fn from(alg: Algorithm) -> Self {
        match alg {
            Algorithm::HS256 => KeyAlgorithm::HS256,
            Algorithm::HS384 => KeyAlgorithm::HS384,
            Algorithm::HS512 => KeyAlgorithm::HS512,
            Algorithm::ES256 => KeyAlgorithm::ES256,
            Algorithm::ES384 => KeyAlgorithm::ES384,
            Algorithm::RS256 => KeyAlgorithm::RS256,
            Algorithm::RS384 => KeyAlgorithm::RS384,
            Algorithm::RS512 => KeyAlgorithm::RS512,
            Algorithm::PS256 => KeyAlgorithm::PS256,
            Algorithm::PS384 => KeyAlgorithm::PS384,
            Algorithm::PS512 => KeyAlgorithm::PS512,
            Algorithm::EdDSA => KeyAlgorithm::EdDSA,
        }
    }
}

impl TryFrom<KeyAlgorithm> for Algorithm {
    type Error = Error;

    fn try_from(alg: KeyAlgorithm) -> Result<Self, Self::Error> {
        match alg {
            KeyAlgorithm::HS256 => Ok(Algorithm::HS256),
            KeyAlgorithm::HS384 => Ok(Algorithm::HS384),
            KeyAlgorithm::HS512 => Ok(Algorithm::HS512),
            KeyAlgorithm::ES256 => Ok(Algorithm::ES256),
            KeyAlgorithm::ES384 => Ok(Algorithm::ES384),
            KeyAlgorithm::RS256 => Ok(Algorithm::RS256),
            KeyAlgorithm::RS384 => Ok(Algorithm::RS384),
            KeyAlgorithm::RS512 => Ok(Algorithm::RS512),
            KeyAlgorithm::PS256 => Ok(Algorithm::PS256),
            KeyAlgorithm::PS384 => Ok(Algorithm::PS384),
            KeyAlgorithm::PS512 => Ok(Algorithm::PS512),
            KeyAlgorithm::EdDSA => Ok(Algorithm::EdDSA),
            _ => Err(new_error(ErrorKind::UnsupportedAlgorithm)),
        }
    }
}

impl fmt::Display for KeyAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl KeyAlgorithm {
    fn to_algorithm(self) -> errors::Result<Algorithm> {
        Algorithm::from_str(self.to_string().as_str())
    }
}

/// Common JWK parameters
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct CommonParameters {
    /// The intended use of the public key. Should not be specified with `key_operations`.
    /// See sections 4.2 and 4.3 of [RFC7517](https://tools.ietf.org/html/rfc7517).
    #[serde(rename = "use", skip_serializing_if = "Option::is_none", default)]
    pub public_key_use: Option<PublicKeyUse>,

    /// The `key_ops` (key operations) parameter identifies the operation(s)
    /// for which the key is intended to be used.  The `key_ops` parameter is
    /// intended for use cases in which public, private, or symmetric keys
    /// may be present.
    /// Should not be specified with `public_key_use`.
    /// See sections 4.2 and 4.3 of [RFC7517](https://tools.ietf.org/html/rfc7517).
    #[serde(rename = "key_ops", skip_serializing_if = "Option::is_none", default)]
    pub key_operations: Option<Vec<KeyOperations>>,

    /// The algorithm keys intended for use with the key.
    #[serde(rename = "alg", skip_serializing_if = "Option::is_none", default)]
    pub key_algorithm: Option<KeyAlgorithm>,

    /// The case sensitive Key ID for the key
    #[serde(rename = "kid", skip_serializing_if = "Option::is_none", default)]
    pub key_id: Option<String>,

    /// X.509 Public key certificate URL. This is currently not implemented (correctly).
    ///
    /// Serialized to `x5u`.
    #[serde(rename = "x5u", skip_serializing_if = "Option::is_none")]
    pub x509_url: Option<String>,

    /// X.509 public key certificate chain. This is currently not implemented (correctly).
    ///
    /// Serialized to `x5c`.
    #[serde(rename = "x5c", skip_serializing_if = "Option::is_none")]
    pub x509_chain: Option<Vec<String>>,

    /// X.509 Certificate SHA1 thumbprint. This is currently not implemented (correctly).
    ///
    /// Serialized to `x5t`.
    #[serde(rename = "x5t", skip_serializing_if = "Option::is_none")]
    pub x509_sha1_fingerprint: Option<String>,

    /// X.509 Certificate SHA256 thumbprint. This is currently not implemented (correctly).
    ///
    /// Serialized to `x5t#S256`.
    #[serde(rename = "x5t#S256", skip_serializing_if = "Option::is_none")]
    pub x509_sha256_fingerprint: Option<String>,
}

/// Key type value for an Elliptic Curve Key.
/// This single value enum is a workaround for Rust not supporting associated constants.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum EllipticCurveKeyType {
    /// Key type value for an Elliptic Curve Key.
    #[default]
    EC,
}

/// Type of cryptographic curve used by a key. This is defined in
/// [RFC 7518 #7.6](https://tools.ietf.org/html/rfc7518#section-7.6)
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[non_exhaustive]
pub enum EllipticCurve {
    /// P-256 curve
    #[serde(rename = "P-256")]
    #[default]
    P256,
    /// P-384 curve
    #[serde(rename = "P-384")]
    P384,
    /// P-521 curve -- unsupported by `ring`.
    #[serde(rename = "P-521")]
    P521,
    /// Ed25519 curve
    #[serde(rename = "Ed25519")]
    Ed25519,
}

/// Parameters for an Elliptic Curve Key
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct EllipticCurveKeyParameters {
    /// Key type value for an Elliptic Curve Key.
    #[serde(rename = "kty")]
    pub key_type: EllipticCurveKeyType,
    /// The "crv" (curve) parameter identifies the cryptographic curve used
    /// with the key.
    #[serde(rename = "crv")]
    pub curve: EllipticCurve,
    /// The "x" (x coordinate) parameter contains the x coordinate for the
    /// Elliptic Curve point.
    pub x: String,
    /// The "y" (y coordinate) parameter contains the y coordinate for the
    /// Elliptic Curve point.
    pub y: String,
}

/// Key type value for an RSA Key.
/// This single value enum is a workaround for Rust not supporting associated constants.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum RSAKeyType {
    /// Key type value for an RSA Key.
    #[default]
    RSA,
}

/// Parameters for a RSA Key
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct RSAKeyParameters {
    /// Key type value for a RSA Key
    #[serde(rename = "kty")]
    pub key_type: RSAKeyType,

    /// The "n" (modulus) parameter contains the modulus value for the RSA
    /// public key.
    pub n: String,

    /// The "e" (exponent) parameter contains the exponent value for the RSA
    /// public key.
    pub e: String,
}

/// Key type value for an Octet symmetric key.
/// This single value enum is a workaround for Rust not supporting associated constants.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum OctetKeyType {
    /// Key type value for an Octet symmetric key.
    #[serde(rename = "oct")]
    #[default]
    Octet,
}

/// Parameters for an Octet Key
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct OctetKeyParameters {
    /// Key type value for an Octet Key
    #[serde(rename = "kty")]
    pub key_type: OctetKeyType,
    /// The octet key value
    #[serde(rename = "k")]
    pub value: String,
}

/// Key type value for an Octet Key Pair.
/// This single value enum is a workaround for Rust not supporting associated constants.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, Hash)]
pub enum OctetKeyPairType {
    /// Key type value for an Octet Key Pair.
    #[serde(rename = "OKP")]
    #[default]
    OctetKeyPair,
}

/// Parameters for an Octet Key Pair
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct OctetKeyPairParameters {
    /// Key type value for an Octet Key Pair
    #[serde(rename = "kty")]
    pub key_type: OctetKeyPairType,
    /// The "crv" (curve) parameter identifies the cryptographic curve used
    /// with the key.
    #[serde(rename = "crv")]
    pub curve: EllipticCurve,
    /// The "x" parameter contains the base64 encoded public key
    pub x: String,
}

/// Parameters for unknown keys
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default, Hash)]
pub struct OtherKeyParameters {
    #[serde(flatten)]
    #[allow(missing_docs)]
    pub fields: BTreeMap<String, serde_json::Value>,
}

/// Algorithm specific parameters
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[serde(untagged)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum AlgorithmParameters {
    EllipticCurve(EllipticCurveKeyParameters),
    RSA(RSAKeyParameters),
    OctetKey(OctetKeyParameters),
    OctetKeyPair(OctetKeyPairParameters),
    Other(OtherKeyParameters),
}

/// The function to use to hash the intermediate thumbprint data.
#[derive(Debug, Clone, Eq, PartialEq)]
#[allow(missing_docs)]
#[non_exhaustive]
pub enum ThumbprintHash {
    SHA256,
    SHA384,
    SHA512,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
#[allow(missing_docs)]
pub struct Jwk {
    #[serde(flatten)]
    pub common: CommonParameters,
    /// Key algorithm specific parameters
    #[serde(flatten)]
    pub algorithm: AlgorithmParameters,
}

impl Jwk {
    /// Find whether the Algorithm is implemented and supported
    pub fn is_supported(&self) -> bool {
        match self.common.key_algorithm {
            Some(alg) => alg.to_algorithm().is_ok(),
            _ => false,
        }
    }

    /// Create a `JWK` from an `EncodingKey`.
    pub fn from_encoding_key(key: &EncodingKey, alg: Algorithm) -> errors::Result<Self> {
        Ok(Self {
            common: CommonParameters { key_algorithm: Some(alg.into()), ..Default::default() },
            algorithm: match key.family() {
                AlgorithmFamily::Hmac => AlgorithmParameters::OctetKey(OctetKeyParameters {
                    key_type: OctetKeyType::Octet,
                    value: b64_encode(key.as_bytes()),
                }),
                AlgorithmFamily::Rsa => {
                    let (n, e) = (CryptoProvider::get_default()
                        .key_utils
                        .rsa_pub_components_from_private_key)(
                        key.as_bytes()
                    )?;
                    AlgorithmParameters::RSA(RSAKeyParameters {
                        key_type: RSAKeyType::RSA,
                        n: b64_encode(n),
                        e: b64_encode(e),
                    })
                }
                AlgorithmFamily::Ec => {
                    let (curve, x, y) = (CryptoProvider::get_default()
                        .key_utils
                        .ec_pub_components_from_private_key)(
                        key.as_bytes(), alg
                    )?;
                    AlgorithmParameters::EllipticCurve(EllipticCurveKeyParameters {
                        key_type: EllipticCurveKeyType::EC,
                        curve,
                        x: b64_encode(x),
                        y: b64_encode(y),
                    })
                }
                AlgorithmFamily::Ed => {
                    // Get the curve type based off the encoding key length
                    // Note: here we will receive a DER key which contains a 16 byte ANS.1 header
                    let curve_type: EllipticCurve = match key.as_bytes().len() {
                        // 16 byte header + 32 byte Ed25519 key
                        48 => Ok(EllipticCurve::Ed25519),
                        _ => Err(Error::from(ErrorKind::InvalidEddsaKey)),
                    }?;

                    // Extract the public key from the encoding key
                    let public_key_bytes = (CryptoProvider::get_default()
                        .key_utils
                        .ed_pub_components_from_private_key)(
                        key.as_bytes(), &curve_type
                    )?;

                    AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters {
                        key_type: OctetKeyPairType::OctetKeyPair,
                        curve: curve_type,
                        x: b64_encode(public_key_bytes),
                    })
                }
            },
        })
    }

    /// Create a `JWK` from a `DecodingKey`.
    pub fn from_decoding_key(
        key: &DecodingKey,
        alg: Option<Algorithm>,
    ) -> crate::errors::Result<Self> {
        Ok(Self {
            common: CommonParameters { key_algorithm: alg.map(|a| a.into()), ..Default::default() },
            algorithm: match key.family() {
                crate::algorithms::AlgorithmFamily::Hmac => {
                    AlgorithmParameters::OctetKey(OctetKeyParameters {
                        key_type: OctetKeyType::Octet,
                        value: b64_encode(key.try_get_as_bytes()?),
                    })
                }
                crate::algorithms::AlgorithmFamily::Rsa => {
                    let (n, e) = match &key.kind() {
                        DecodingKeyKind::RsaModulusExponent { n, e } => {
                            (b64_encode(n), b64_encode(e))
                        }
                        DecodingKeyKind::SecretOrDer(der) => {
                            let (n, e) = (CryptoProvider::get_default()
                                .key_utils
                                .rsa_pub_components_from_public_key)(
                                der
                            )?;
                            (b64_encode(n), b64_encode(e))
                        }
                    };

                    AlgorithmParameters::RSA(RSAKeyParameters { key_type: RSAKeyType::RSA, n, e })
                }
                crate::algorithms::AlgorithmFamily::Ec => {
                    let (curve, x, y) = ec_pub_components_from_public_key(key.try_get_as_bytes()?)?;
                    AlgorithmParameters::EllipticCurve(EllipticCurveKeyParameters {
                        key_type: EllipticCurveKeyType::EC,
                        curve,
                        x: b64_encode(x),
                        y: b64_encode(y),
                    })
                }
                crate::algorithms::AlgorithmFamily::Ed => {
                    let pub_bytes = key.try_get_as_bytes()?;
                    let (curve_type, x) = match pub_bytes.len() {
                        // ED25519: https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
                        32 => (EllipticCurve::Ed25519, pub_bytes),
                        _ => return Err(ErrorKind::InvalidEddsaKey.into()),
                    };

                    AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters {
                        key_type: OctetKeyPairType::OctetKeyPair,
                        curve: curve_type,
                        x: b64_encode(x),
                    })
                }
            },
        })
    }

    /// Compute the thumbprint of the JWK.
    ///
    /// Per [RFC-7638](https://datatracker.ietf.org/doc/html/rfc7638)
    pub fn thumbprint(&self, hash_function: ThumbprintHash) -> errors::Result<String> {
        let pre = match &self.algorithm {
            AlgorithmParameters::EllipticCurve(a) => match a.curve {
                EllipticCurve::P256 | EllipticCurve::P384 | EllipticCurve::P521 => {
                    format!(
                        r#"{{"crv":{},"kty":{},"x":"{}","y":"{}"}}"#,
                        serde_json::to_string(&a.curve).unwrap(),
                        serde_json::to_string(&a.key_type).unwrap(),
                        a.x,
                        a.y,
                    )
                }
                EllipticCurve::Ed25519 => {
                    return Err(ErrorKind::InvalidKeyFormat.into());
                }
            },
            AlgorithmParameters::RSA(a) => {
                format!(
                    r#"{{"e":"{}","kty":{},"n":"{}"}}"#,
                    a.e,
                    serde_json::to_string(&a.key_type).unwrap(),
                    a.n,
                )
            }
            AlgorithmParameters::OctetKey(a) => {
                format!(
                    r#"{{"k":"{}","kty":{}}}"#,
                    a.value,
                    serde_json::to_string(&a.key_type).unwrap()
                )
            }
            AlgorithmParameters::OctetKeyPair(a) => match a.curve {
                EllipticCurve::P256 | EllipticCurve::P384 | EllipticCurve::P521 => {
                    return Err(ErrorKind::InvalidKeyFormat.into());
                }
                EllipticCurve::Ed25519 => {
                    format!(
                        r#"{{"crv":{},"kty":{},"x":"{}"}}"#,
                        serde_json::to_string(&a.curve).unwrap(),
                        serde_json::to_string(&a.key_type).unwrap(),
                        a.x,
                    )
                }
            },
            AlgorithmParameters::Other(_) => return Err(ErrorKind::UnsupportedAlgorithm.into()),
        };

        Ok(b64_encode((CryptoProvider::get_default().key_utils.compute_digest)(
            pre.as_bytes(),
            hash_function,
        )?))
    }
}

/// A JWK set
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, Hash)]
#[allow(missing_docs)]
pub struct JwkSet {
    pub keys: Vec<Jwk>,
}

impl JwkSet {
    /// Find the key in the set that matches the given key id, if any.
    pub fn find(&self, kid: &str) -> Option<&Jwk> {
        self.keys
            .iter()
            .find(|jwk| jwk.common.key_id.is_some() && jwk.common.key_id.as_ref().unwrap() == kid)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use serde_json::json;
    use wasm_bindgen_test::wasm_bindgen_test;

    use crate::Algorithm;
    use crate::errors::ErrorKind;
    use crate::jwk::{
        AlgorithmParameters, CommonParameters, EllipticCurve, Jwk, JwkSet, KeyAlgorithm,
        OctetKeyPairParameters, OctetKeyPairType, OctetKeyType, RSAKeyParameters, ThumbprintHash,
    };
    use crate::serialization::b64_encode;
    use crate::{DecodingKey, EncodingKey};

    #[test]
    #[wasm_bindgen_test]
    fn check_hs256() {
        let key = b64_encode("abcdefghijklmnopqrstuvwxyz012345");
        let jwks_json = json!({
            "keys": [
                {
                    "kty": "oct",
                    "alg": "HS256",
                    "kid": "abc123",
                    "k": key
                }
            ]
        });

        let set: JwkSet = serde_json::from_value(jwks_json).expect("Failed HS256 check");
        assert_eq!(set.keys.len(), 1);
        let key = &set.keys[0];
        assert_eq!(key.common.key_id, Some("abc123".to_string()));
        let algorithm = key.common.key_algorithm.unwrap().to_algorithm().unwrap();
        assert_eq!(algorithm, Algorithm::HS256);

        match &key.algorithm {
            AlgorithmParameters::OctetKey(key) => {
                assert_eq!(key.key_type, OctetKeyType::Octet);
                assert_eq!(key.value, key.value)
            }
            _ => panic!("Unexpected key algorithm"),
        }
    }

    #[test]
    fn deserialize_unknown_key_algorithm() {
        let key_alg_json = json!("");
        let key_alg_result: KeyAlgorithm =
            serde_json::from_value(key_alg_json).expect("Could not deserialize json");
        assert_eq!(key_alg_result, KeyAlgorithm::UNKNOWN_ALGORITHM);
    }

    #[test]
    fn deserialize_unknown_kty() {
        let parameters_json = json!({
            "kty": "AKP",
            "foo": "bar",
            "solution": 42
        });
        let parameters_result: AlgorithmParameters =
            serde_json::from_value(parameters_json).expect("Could not deserialize json");
        match parameters_result {
            AlgorithmParameters::Other(other_key_parameters) => {
                let mut expected = BTreeMap::new();
                expected.insert("kty".to_owned(), serde_json::to_value("AKP").unwrap());
                expected.insert("foo".to_owned(), serde_json::to_value("bar").unwrap());
                expected.insert("solution".to_owned(), serde_json::to_value(42).unwrap());
                assert_eq!(other_key_parameters.fields, expected);
            }
            _ => {
                panic!("Unexpected deserialization result");
            }
        }

        // RFC 9964 Appendix A.1 JWK
        let jwk: Jwk = serde_json::from_value(json!({
            "kid": "T4xl70S7MT6Zeq6r9V9fPJGVn76wfnXJ21-gyo0Gu6o",
            "kty": "AKP",
            "alg": "ML-DSA-44",
            "pub": "...",
            "priv": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
        }))
        .expect("Could not deserialize json");

        assert!(!jwk.is_supported());
        assert!(matches!(jwk.algorithm, AlgorithmParameters::Other(_)));
    }

    #[test]
    #[wasm_bindgen_test]
    fn check_thumbprint() {
        let tp = Jwk {
            common: crate::jwk::CommonParameters { key_id: Some("2011-04-29".to_string()), ..Default::default() },
            algorithm: AlgorithmParameters::RSA(RSAKeyParameters {
                key_type: crate::jwk::RSAKeyType::RSA,
                n: "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw".to_string(),
                e: "AQAB".to_string(),
            }),
        }
        .thumbprint(ThumbprintHash::SHA256)
        .unwrap();

        assert_eq!(tp.as_str(), "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs");
    }

    #[test]
    fn check_thumbprint_bad_key() {
        let jwk = Jwk {
            common: CommonParameters {
                key_algorithm: Some(KeyAlgorithm::ES256),
                ..Default::default()
            },
            algorithm: AlgorithmParameters::OctetKeyPair(OctetKeyPairParameters {
                key_type: OctetKeyPairType::OctetKeyPair,
                curve: EllipticCurve::P256,
                x: "".to_string(),
            }),
        };

        assert_eq!(
            jwk.thumbprint(ThumbprintHash::SHA256).unwrap_err().into_kind(),
            ErrorKind::InvalidKeyFormat
        );
    }

    #[test]
    #[wasm_bindgen_test]
    fn check_alg_key_alg_conversion() {
        let pairs = [
            (Algorithm::HS256, KeyAlgorithm::HS256),
            (Algorithm::HS384, KeyAlgorithm::HS384),
            (Algorithm::HS512, KeyAlgorithm::HS512),
            (Algorithm::ES256, KeyAlgorithm::ES256),
            (Algorithm::ES384, KeyAlgorithm::ES384),
            (Algorithm::RS256, KeyAlgorithm::RS256),
            (Algorithm::RS384, KeyAlgorithm::RS384),
            (Algorithm::RS512, KeyAlgorithm::RS512),
            (Algorithm::PS256, KeyAlgorithm::PS256),
            (Algorithm::PS384, KeyAlgorithm::PS384),
            (Algorithm::PS512, KeyAlgorithm::PS512),
            (Algorithm::EdDSA, KeyAlgorithm::EdDSA),
        ];

        for (alg, k_alg) in pairs {
            assert_eq!(KeyAlgorithm::from(alg), k_alg);
            assert_eq!(Algorithm::try_from(k_alg), Ok(alg));
        }

        assert!(
            Algorithm::try_from(KeyAlgorithm::RSA1_5)
                .is_err_and(|e| *e.kind() == ErrorKind::UnsupportedAlgorithm)
        );
        assert!(
            Algorithm::try_from(KeyAlgorithm::RSA_OAEP)
                .is_err_and(|e| *e.kind() == ErrorKind::UnsupportedAlgorithm)
        );
        assert!(
            Algorithm::try_from(KeyAlgorithm::RSA_OAEP_256)
                .is_err_and(|e| *e.kind() == ErrorKind::UnsupportedAlgorithm)
        );
    }

    #[test]
    #[cfg(feature = "use_pem")]
    fn check_jwk_from_decoding_key_rsa() {
        let enc_key =
            EncodingKey::from_rsa_pem(include_bytes!("../tests/rsa/private_rsa_key_pkcs8.pem"))
                .unwrap();
        let dec_key =
            DecodingKey::from_rsa_pem(include_bytes!("../tests/rsa/public_rsa_key_pkcs8.pem"))
                .unwrap();
        let expected_jwk = Jwk::from_encoding_key(&enc_key, Algorithm::RS256).unwrap();
        let jwk = Jwk::from_decoding_key(&dec_key, Some(Algorithm::RS256)).unwrap();
        assert_eq!(jwk, expected_jwk);
    }

    #[test]
    #[cfg(feature = "use_pem")]
    fn check_jwk_from_decoding_key_ec() {
        let enc_key =
            EncodingKey::from_ec_pem(include_bytes!("../tests/ecdsa/private_ecdsa_key.pem"))
                .unwrap();
        let dec_key =
            DecodingKey::from_ec_pem(include_bytes!("../tests/ecdsa/public_ecdsa_key.pem"))
                .unwrap();
        let expected_jwk = Jwk::from_encoding_key(&enc_key, Algorithm::ES256).unwrap();
        let jwk = Jwk::from_decoding_key(&dec_key, Some(Algorithm::ES256)).unwrap();
        assert_eq!(jwk, expected_jwk);
    }

    #[test]
    #[cfg(feature = "use_pem")]
    fn check_jwk_from_decoding_key_ed() {
        let enc_key =
            EncodingKey::from_ed_pem(include_bytes!("../tests/eddsa/private_ed25519_key.pem"))
                .unwrap();
        let dec_key =
            DecodingKey::from_ed_pem(include_bytes!("../tests/eddsa/public_ed25519_key.pem"))
                .unwrap();
        let expected_jwk = Jwk::from_encoding_key(&enc_key, Algorithm::EdDSA).unwrap();
        let jwk = Jwk::from_decoding_key(&dec_key, Some(Algorithm::EdDSA)).unwrap();
        assert_eq!(jwk, expected_jwk);
    }

    #[test]
    fn check_jwkset_default() {
        #[derive(Default)]
        struct Derived(JwkSet);

        assert!(Derived::default().0.keys.is_empty());
    }
}