jsonwebtokens 1.2.0

A Json Web Token implementation for Rust
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
use ring::signature;
use serde::{Deserialize, Serialize};
use simple_asn1::BigUint;
use std::fmt;
use std::str::FromStr;

use crate::crypto::*;
use crate::error::{Error, ErrorDetails};
use crate::pem::decoder::PemEncodedKey;
use crate::raw::*;

impl From<AlgorithmID> for &dyn signature::VerificationAlgorithm {
    fn from(alg: AlgorithmID) -> Self {
        match alg {
            AlgorithmID::ES256 => &signature::ECDSA_P256_SHA256_FIXED,
            AlgorithmID::ES384 => &signature::ECDSA_P384_SHA384_FIXED,

            AlgorithmID::RS256 => &signature::RSA_PKCS1_2048_8192_SHA256,
            AlgorithmID::RS384 => &signature::RSA_PKCS1_2048_8192_SHA384,
            AlgorithmID::RS512 => &signature::RSA_PKCS1_2048_8192_SHA512,
            AlgorithmID::PS256 => &signature::RSA_PSS_2048_8192_SHA256,
            AlgorithmID::PS384 => &signature::RSA_PSS_2048_8192_SHA384,
            AlgorithmID::PS512 => &signature::RSA_PSS_2048_8192_SHA512,

            _ => unreachable!("algorithm doesn't map to a ring signature verification algorithm"),
        }
    }
}

/// Uniquely identifies a specific cryptographic algorithm for signing or verifying tokens
#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AlgorithmID {
    /// Unsecured JWT
    NONE,

    /// 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,
}

impl From<AlgorithmID> for &'static str {
    fn from(id: AlgorithmID) -> Self {
        match id {
            AlgorithmID::NONE => "none",

            AlgorithmID::HS256 => "HS256",
            AlgorithmID::HS384 => "HS384",
            AlgorithmID::HS512 => "HS512",

            AlgorithmID::ES256 => "ES256",
            AlgorithmID::ES384 => "ES384",

            AlgorithmID::RS256 => "RS256",
            AlgorithmID::RS384 => "RS384",
            AlgorithmID::RS512 => "RS512",

            AlgorithmID::PS256 => "PS256",
            AlgorithmID::PS384 => "PS384",
            AlgorithmID::PS512 => "PS512",
        }
    }
}

impl std::fmt::Display for AlgorithmID {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let alg = *self;
        let s: &'static str = alg.into();
        write!(f, "{s}")
    }
}

impl FromStr for AlgorithmID {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "none" => Ok(AlgorithmID::NONE),

            "HS256" => Ok(AlgorithmID::HS256),
            "HS384" => Ok(AlgorithmID::HS384),
            "HS512" => Ok(AlgorithmID::HS512),

            "ES256" => Ok(AlgorithmID::ES256),
            "ES384" => Ok(AlgorithmID::ES384),

            "RS256" => Ok(AlgorithmID::RS256),
            "RS384" => Ok(AlgorithmID::RS384),
            "RS512" => Ok(AlgorithmID::RS512),

            "PS256" => Ok(AlgorithmID::PS256),
            "PS384" => Ok(AlgorithmID::PS384),
            "PS512" => Ok(AlgorithmID::PS512),

            _ => Err(Error::InvalidInput(ErrorDetails::new(format!(
                "Unknown algorithm name {s}"
            )))),
        }
    }
}

impl From<Algorithm> for &'static str {
    fn from(alg: Algorithm) -> Self {
        alg.name()
    }
}

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

    #[test]
    fn generate_algorithm_enum_from_str() {
        assert!(AlgorithmID::from_str("none").is_ok());

        assert!(AlgorithmID::from_str("HS256").is_ok());
        assert!(AlgorithmID::from_str("HS384").is_ok());
        assert!(AlgorithmID::from_str("HS512").is_ok());

        assert!(AlgorithmID::from_str("ES256").is_ok());
        assert!(AlgorithmID::from_str("ES384").is_ok());

        assert!(AlgorithmID::from_str("RS256").is_ok());
        assert!(AlgorithmID::from_str("RS384").is_ok());
        assert!(AlgorithmID::from_str("RS512").is_ok());

        assert!(AlgorithmID::from_str("PS256").is_ok());
        assert!(AlgorithmID::from_str("PS384").is_ok());
        assert!(AlgorithmID::from_str("PS512").is_ok());

        assert!(AlgorithmID::from_str("").is_err());
    }
}

fn ensure_hmac_id(id: AlgorithmID) -> Result<(), Error> {
    match id {
        AlgorithmID::HS256 => Ok(()),
        AlgorithmID::HS384 => Ok(()),
        AlgorithmID::HS512 => Ok(()),
        _ => Err(Error::AlgorithmMismatch()),
    }
}

fn ensure_ecdsa_id(id: AlgorithmID) -> Result<(), Error> {
    match id {
        AlgorithmID::ES256 => Ok(()),
        AlgorithmID::ES384 => Ok(()),
        _ => Err(Error::AlgorithmMismatch()),
    }
}

fn ensure_rsa_id(id: AlgorithmID) -> Result<(), Error> {
    match id {
        AlgorithmID::RS256 => Ok(()),
        AlgorithmID::RS384 => Ok(()),
        AlgorithmID::RS512 => Ok(()),

        AlgorithmID::PS256 => Ok(()),
        AlgorithmID::PS384 => Ok(()),
        AlgorithmID::PS512 => Ok(()),
        _ => Err(Error::AlgorithmMismatch()),
    }
}

/// A cryptographic function for signing or verifying a token signature
///
/// An Algorithm encapsulates one function for signing or verifying tokens. A key
/// or secret only needs to be decoded once so it can be reused cheaply while
/// signing or verifying tokens. The decoded key or secret and `AlgorithmID` are
/// immutable after construction to avoid the chance of being coerced into using
/// the wrong algorithm to sign or verify a token at runtime.
///
/// Optionally a `kid` Key ID can be assigned to an `Algorithm` to add a strict
/// check that a token's header must include the same `kid` value. This is useful
/// when using an `Algorithm` to represent a single key within a JWKS key set,
/// for example.
///
#[derive(Debug)]
pub struct Algorithm {
    id: AlgorithmID,
    kid: Option<String>,

    secret_or_key: SecretOrKey,
}

impl Algorithm {
    /// Returns the `AlgorithmID` that was used to construct the `Algorithm`
    pub fn id(&self) -> AlgorithmID {
        self.id
    }

    /// Returns the algorithm name as standardized in [RFC 7518](https://tools.ietf.org/html/rfc7518)
    pub fn name(&self) -> &'static str {
        self.id.into()
    }

    /// Optionally if a `kid` is associated with an algorithm there will be an extra
    /// verification that a token's kid matches the one associated with the `Algorithm`
    pub fn set_kid(&mut self, kid: impl Into<String>) {
        self.kid = Some(kid.into());
    }

    /// Returns a reference to any associated `kid` set via `set_kid()`
    pub fn kid(&self) -> Option<&str> {
        match &self.kid {
            Some(string) => Some(string.as_ref()),
            None => None,
        }
    }

    /// Constructs a NOP algorithm for use with unsecured (unsigned) tokens
    pub fn new_unsecured() -> Result<Self, Error> {
        Ok(Algorithm {
            id: AlgorithmID::NONE,
            kid: None,
            secret_or_key: SecretOrKey::None,
        })
    }

    /// Constructs a symmetric HMAC algorithm based on a given secret
    ///
    /// This algorithm may be used for signing and/or verifying signatures
    pub fn new_hmac(id: AlgorithmID, secret: impl Into<Vec<u8>>) -> Result<Self, Error> {
        ensure_hmac_id(id)?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::Secret(secret.into()),
        })
    }

    /// Constructs a symmetric HMAC algorithm based on a given base64 secret
    ///
    /// This is a convenience api in case the secret you're using is base64 encoded
    ///
    /// This algorithm may be used for signing and/or verifying signatures
    pub fn new_hmac_b64(id: AlgorithmID, secret: impl AsRef<str>) -> Result<Self, Error> {
        ensure_hmac_id(id)?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::Secret(b64_decode(secret.as_ref())?),
        })
    }

    /// Constructs an ECDSA algorithm based on a PEM format private key
    ///
    /// This algorithm may only be used for signing tokens
    pub fn new_ecdsa_pem_signer(id: AlgorithmID, key: &[u8]) -> Result<Self, Error> {
        ensure_ecdsa_id(id)?;

        let ring_alg = id.into();
        let pem_key = PemEncodedKey::new(key)?;
        let signing_key =
            signature::EcdsaKeyPair::from_pkcs8(ring_alg, pem_key.as_ec_private_key()?).map_err(
                |e| {
                    Error::InvalidInput(ErrorDetails::map(
                        "Failed to create ECDSA key pair for signing",
                        Box::new(e),
                    ))
                },
            )?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::EcdsaKeyPair(Box::from(signing_key)),
        })
    }

    /// Constructs an ECDSA algorithm based on a PEM format public key
    ///
    /// This algorithm may only be used for verifying tokens
    pub fn new_ecdsa_pem_verifier(id: AlgorithmID, key: &[u8]) -> Result<Self, Error> {
        ensure_ecdsa_id(id)?;

        let pem_key = PemEncodedKey::new(key)?;
        let ec_pub_key = pem_key.as_ec_public_key()?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::EcdsaUnparsedKey(ec_pub_key.to_vec()),
        })
    }

    /// Constructs an RSA algorithm based on a PEM format private key
    ///
    /// This algorithm may only be used for signing tokens
    pub fn new_rsa_pem_signer(id: AlgorithmID, key: &[u8]) -> Result<Self, Error> {
        ensure_rsa_id(id)?;

        let pem_key = PemEncodedKey::new(key)?;
        let key_pair =
            signature::RsaKeyPair::from_der(pem_key.as_rsa_private_key()?).map_err(|e| {
                Error::InvalidInput(ErrorDetails::map(
                    "Failed to create RSA key for signing",
                    Box::new(e),
                ))
            })?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::RsaKeyPair(Box::from(key_pair)),
        })
    }

    /// Constructs an RSA algorithm based on a PEM format public key
    ///
    /// This algorithm may only be used for verifying tokens
    pub fn new_rsa_pem_verifier(id: AlgorithmID, key: &[u8]) -> Result<Self, Error> {
        ensure_rsa_id(id)?;

        let pem_key = PemEncodedKey::new(key)?;
        let rsa_pub_key = pem_key.as_rsa_public_key()?;

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::RsaUnparsedKey(rsa_pub_key.to_vec()),
        })
    }

    /// Constructs an RSA algorithm based on modulus (n) and exponent (e) components
    ///
    /// In some situations (such as JWKS key sets), a public RSA key may be
    /// described in terms of (base64 encoded) modulus and exponent values.
    ///
    /// This algorithm may only be used for verifying tokens
    pub fn new_rsa_n_e_b64_verifier(
        id: AlgorithmID,
        n_b64: &str,
        e_b64: &str,
    ) -> Result<Self, Error> {
        ensure_rsa_id(id)?;

        let n = BigUint::from_bytes_be(&b64_decode(n_b64)?).to_bytes_be();
        let e = BigUint::from_bytes_be(&b64_decode(e_b64)?).to_bytes_be();

        Ok(Algorithm {
            id,
            kid: None,
            secret_or_key: SecretOrKey::RsaParameters(n, e),
        })
    }

    /// Lower-level api that can be used to verify a signature for a given message
    pub fn verify(
        &self,
        kid: Option<&str>,
        message: impl AsRef<str>,
        signature: impl AsRef<str>,
    ) -> Result<(), Error> {
        // We need an Option(&str) instead of Option(String)
        let kid_matches = match &self.kid {
            Some(string) => kid == Some(string.as_ref()),
            None => true,
        };
        if !kid_matches {
            return Err(Error::MalformedToken(ErrorDetails::new(format!(
                "'kid' ({:?}) didn't match ID ({:?}) associated with Algorithm",
                kid, self.kid
            ))));
        }

        match self.id {
            AlgorithmID::NONE => {
                if signature.as_ref() == "" {
                    Ok(())
                } else {
                    Err(Error::InvalidSignature())
                }
            }
            AlgorithmID::HS256 | AlgorithmID::HS384 | AlgorithmID::HS512 => hmac::verify(
                self.id,
                &self.secret_or_key,
                message.as_ref(),
                signature.as_ref(),
            ),
            AlgorithmID::ES256 | AlgorithmID::ES384 => ecdsa::verify(
                self.id,
                &self.secret_or_key,
                message.as_ref(),
                signature.as_ref(),
            ),
            AlgorithmID::RS256
            | AlgorithmID::RS384
            | AlgorithmID::RS512
            | AlgorithmID::PS256
            | AlgorithmID::PS384
            | AlgorithmID::PS512 => rsa::verify(
                self.id,
                &self.secret_or_key,
                message.as_ref(),
                signature.as_ref(),
            ),
        }
    }

    /// Lower-level api that can be used to calculate a signature for a message
    pub fn sign(&self, message: &str) -> Result<String, Error> {
        match self.id {
            AlgorithmID::NONE => Ok("".to_owned()),
            AlgorithmID::HS256 | AlgorithmID::HS384 | AlgorithmID::HS512 => {
                hmac::sign(self.id, &self.secret_or_key, message)
            }
            AlgorithmID::ES256 | AlgorithmID::ES384 => {
                ecdsa::sign(self.id, &self.secret_or_key, message)
            }
            AlgorithmID::RS256
            | AlgorithmID::RS384
            | AlgorithmID::RS512
            | AlgorithmID::PS256
            | AlgorithmID::PS384
            | AlgorithmID::PS512 => rsa::sign(self.id, &self.secret_or_key, message),
        }
    }
}