Skip to content

Commit 09ccfe6

Browse files
authored
Small clippy and documentation fixes (#514)
* Fix some pedantic clippy complaints * Add some doc, more consistent style * Update readme
1 parent a89c743 commit 09ccfe6

8 files changed

Lines changed: 42 additions & 38 deletions

File tree

README.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Add the following to Cargo.toml:
99

1010
```toml
1111
# You will have to select either `aws_lc_rs` or `rust_crypto` as backend if you're not using your own
12-
jsonwebtoken = { version = "10", features = ["aws_lc_rs"] }
12+
jsonwebtoken = { version = "11", features = ["aws_lc_rs"] }
1313
# If you do not need pem decoding, you can disable the default feature `use_pem` that way:
1414
# jsonwebtoken = {version = "10", default-features = false, features = ["aws_lc_rs"] }
1515
serde = {version = "1.0", features = ["derive"] }
@@ -18,7 +18,7 @@ serde = {version = "1.0", features = ["derive"] }
1818
Two crypto backends are available via features, `aws_lc_rs` and `rust_crypto`, at most one of which must be enabled. If you select neither feature, you need to provide your own `CryptoProvider`.
1919

2020
For examples of how to implement a `CryptoProvider`, see
21-
- [arckoor/jsonwebtoken-botan](https://github.com/arckoor/jsonwebtoken-botan)
21+
- [arckoor/jsonwebtoken-providers](https://github.com/arckoor/jsonwebtoken-providers)
2222

2323
The minimum required Rust version (MSRV) is specified in the `rust-version` field in this project's [Cargo.toml](Cargo.toml).
2424

@@ -45,7 +45,7 @@ Complete examples are available in the examples directory: a basic one and one w
4545
In terms of imports and structs:
4646
```rust
4747
use serde::{Serialize, Deserialize};
48-
use jsonwebtoken::{encode, decode, Header, Algorithm, Validation, EncodingKey, DecodingKey};
48+
use jsonwebtoken::{encode, decode, Header, Extras, Algorithm, Validation, EncodingKey, DecodingKey};
4949

5050
/// Our claims struct, it needs to derive `Serialize` and/or `Deserialize`
5151
#[derive(Debug, Serialize, Deserialize)]
@@ -86,7 +86,7 @@ If you want to set the `kid` parameter or change the algorithm for example:
8686
let mut header = Header::new(Algorithm::HS512);
8787
header.kid = Some("blabla".to_owned());
8888

89-
let mut extras = HashMap::with_capacity(1);
89+
let mut extras = Extras::default();
9090
extras.insert("custom".to_string(), "header".to_string());
9191
header.extras = Some(extras);
9292

@@ -134,8 +134,8 @@ when the Jws is nested in another struct.
134134

135135
If you have a JWK object, you can generate a thumbprint like
136136

137-
```
138-
let tp = my_jwk.thumbprint(&jsonwebtoken::DIGEST_SHA256);
137+
```rust
138+
let tp = my_jwk.thumbprint(&jsonwebtoken::DIGEST_SHA256)?;
139139
```
140140

141141
### Decoding

src/crypto/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,11 @@ impl CryptoProvider {
114114

115115
#[allow(unreachable_code)]
116116
{
117-
const NOT_INSTALLED_ERROR: &str = r###"
117+
const NOT_INSTALLED_ERROR: &str = r"
118118
Could not automatically determine the process-level CryptoProvider from jsonwebtoken crate features.
119119
Call CryptoProvider::install_default() before this point to select a provider manually, or make sure exactly one of the 'rust_crypto' and 'aws_lc_rs' features is enabled.
120120
See the documentation of the CryptoProvider type for more information.
121-
"###;
121+
";
122122

123123
static INSTANCE: CryptoProvider = CryptoProvider {
124124
signer_factory: |_, _| panic!("{}", NOT_INSTALLED_ERROR),
@@ -151,11 +151,11 @@ impl JwkUtils {
151151
/// Initialises all values to dummies.
152152
/// Will lead to a panic when JWKs are required, so only use it if you don't want to support JWKs.
153153
pub const fn new_unimplemented() -> Self {
154-
const NOT_INSTALLED_OR_UNIMPLEMENTED_ERROR: &str = r###"
154+
const NOT_INSTALLED_OR_UNIMPLEMENTED_ERROR: &str = r"
155155
Could not automatically determine the process-level CryptoProvider from jsonwebtoken crate features, or your CryptoProvider does not support JWKs.
156156
Call CryptoProvider::install_default() before this point to select a provider manually, or make sure exactly one of the 'rust_crypto' and 'aws_lc_rs' features is enabled.
157157
See the documentation of the CryptoProvider type for more information.
158-
"###;
158+
";
159159
Self {
160160
extract_rsa_public_key_components: |_| {
161161
panic!("{}", NOT_INSTALLED_OR_UNIMPLEMENTED_ERROR)

src/crypto/rust_crypto/hmac.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use sha2::{Sha256, Sha384, Sha512};
66
use signature::{Signer, Verifier};
77

88
use crate::crypto::{JwtSigner, JwtVerifier};
9-
use crate::errors::Result;
9+
use crate::errors::{ErrorKind, Result};
1010
use crate::{Algorithm, DecodingKey, EncodingKey};
1111

1212
type HmacSha256 = Hmac<Sha256>;
@@ -21,7 +21,7 @@ macro_rules! define_hmac_signer {
2121
impl $name {
2222
pub(crate) fn new(encoding_key: &EncodingKey) -> Result<Self> {
2323
let inner = <$hmac_type>::new_from_slice(encoding_key.try_get_hmac_secret()?)
24-
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
24+
.map_err(|_| ErrorKind::InvalidKeyFormat)?;
2525

2626
Ok(Self(inner))
2727
}
@@ -53,7 +53,7 @@ macro_rules! define_hmac_verifier {
5353
impl $name {
5454
pub(crate) fn new(decoding_key: &DecodingKey) -> Result<Self> {
5555
let inner = <$hmac_type>::new_from_slice(decoding_key.try_get_hmac_secret()?)
56-
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
56+
.map_err(|_| ErrorKind::InvalidKeyFormat)?;
5757

5858
Ok(Self(inner))
5959
}

src/header.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ impl Header {
248248
zip: None,
249249
url: None,
250250
nonce: None,
251-
extras: Default::default(),
251+
extras: Extras::default(),
252252
}
253253
}
254254

src/jwk.rs

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
#![allow(missing_docs)]
21
//! This crate contains types only for working JWK and JWK Sets
32
//! This is only meant to be used to deal with public JWK, not generate ones.
43
//! Most of the code in this file is taken from <https://github.com/lawliet89/biscuit> but
@@ -11,7 +10,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
1110
use crate::crypto::CryptoProvider;
1211
use crate::serialization::b64_encode;
1312
use crate::{
14-
Algorithm, EncodingKey,
13+
Algorithm, AlgorithmFamily, EncodingKey,
1514
errors::{self, Error, ErrorKind},
1615
};
1716

@@ -242,8 +241,8 @@ pub struct CommonParameters {
242241
#[serde(rename = "use", skip_serializing_if = "Option::is_none", default)]
243242
pub public_key_use: Option<PublicKeyUse>,
244243

245-
/// The "key_ops" (key operations) parameter identifies the operation(s)
246-
/// for which the key is intended to be used. The "key_ops" parameter is
244+
/// The `key_ops` (key operations) parameter identifies the operation(s)
245+
/// for which the key is intended to be used. The `key_ops` parameter is
247246
/// intended for use cases in which public, private, or symmetric keys
248247
/// may be present.
249248
/// Should not be specified with `public_key_use`.
@@ -403,6 +402,7 @@ pub struct OctetKeyPairParameters {
403402
/// Algorithm specific parameters
404403
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
405404
#[serde(untagged)]
405+
#[allow(missing_docs)]
406406
pub enum AlgorithmParameters {
407407
EllipticCurve(EllipticCurveKeyParameters),
408408
RSA(RSAKeyParameters),
@@ -412,13 +412,15 @@ pub enum AlgorithmParameters {
412412

413413
/// The function to use to hash the intermediate thumbprint data.
414414
#[derive(Debug, Clone, Eq, PartialEq)]
415+
#[allow(missing_docs)]
415416
pub enum ThumbprintHash {
416417
SHA256,
417418
SHA384,
418419
SHA512,
419420
}
420421

421422
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash)]
423+
#[allow(missing_docs)]
422424
pub struct Jwk {
423425
#[serde(flatten)]
424426
pub common: CommonParameters,
@@ -435,7 +437,11 @@ impl Jwk {
435437
_ => false,
436438
}
437439
}
438-
pub fn from_encoding_key(key: &EncodingKey, alg: Algorithm) -> crate::errors::Result<Self> {
440+
441+
/// Create a `JWK` from an `EncodingKey`.
442+
///
443+
/// Edwards curve based keys are not supported.
444+
pub fn from_encoding_key(key: &EncodingKey, alg: Algorithm) -> errors::Result<Self> {
439445
Ok(Self {
440446
common: CommonParameters {
441447
key_algorithm: Some(match alg {
@@ -455,13 +461,11 @@ impl Jwk {
455461
..Default::default()
456462
},
457463
algorithm: match key.family() {
458-
crate::algorithms::AlgorithmFamily::Hmac => {
459-
AlgorithmParameters::OctetKey(OctetKeyParameters {
460-
key_type: OctetKeyType::Octet,
461-
value: b64_encode(key.inner()),
462-
})
463-
}
464-
crate::algorithms::AlgorithmFamily::Rsa => {
464+
AlgorithmFamily::Hmac => AlgorithmParameters::OctetKey(OctetKeyParameters {
465+
key_type: OctetKeyType::Octet,
466+
value: b64_encode(key.inner()),
467+
}),
468+
AlgorithmFamily::Rsa => {
465469
let (n, e) = (CryptoProvider::get_default()
466470
.jwk_utils
467471
.extract_rsa_public_key_components)(
@@ -473,7 +477,7 @@ impl Jwk {
473477
e: b64_encode(e),
474478
})
475479
}
476-
crate::algorithms::AlgorithmFamily::Ec => {
480+
AlgorithmFamily::Ec => {
477481
let (curve, x, y) = (CryptoProvider::get_default()
478482
.jwk_utils
479483
.extract_ec_public_key_coordinates)(
@@ -486,8 +490,8 @@ impl Jwk {
486490
y: b64_encode(y),
487491
})
488492
}
489-
crate::algorithms::AlgorithmFamily::Ed => {
490-
unimplemented!();
493+
AlgorithmFamily::Ed => {
494+
unimplemented!("Edwards curves are not supported");
491495
}
492496
},
493497
})
@@ -549,6 +553,7 @@ impl Jwk {
549553

550554
/// A JWK set
551555
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
556+
#[allow(missing_docs)]
552557
pub struct JwkSet {
553558
pub keys: Vec<Jwk>,
554559
}

src/pem/decoder.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,8 @@ impl PemEncodedKey {
5353
pub fn new(input: &[u8]) -> Result<PemEncodedKey> {
5454
match pem::parse(input) {
5555
Ok(content) => {
56-
let asn1_content = match simple_asn1::from_der(content.contents()) {
57-
Ok(asn1) => asn1,
58-
Err(_) => return Err(ErrorKind::InvalidKeyFormat.into()),
56+
let Ok(asn1_content) = simple_asn1::from_der(content.contents()) else {
57+
return Err(ErrorKind::InvalidKeyFormat.into());
5958
};
6059

6160
match content.tag() {
@@ -78,7 +77,7 @@ impl PemEncodedKey {
7877
// "there is no such thing as a "PKCS#1 format" for elliptic curve (EC) keys"
7978

8079
// This handles PKCS#8 certificates and public & private keys
81-
tag @ "PRIVATE KEY" | tag @ "PUBLIC KEY" | tag @ "CERTIFICATE" => {
80+
tag @ ("PRIVATE KEY" | "PUBLIC KEY" | "CERTIFICATE") => {
8281
match classify_pem(&asn1_content) {
8382
Some(c) => {
8483
let is_private = tag == "PRIVATE KEY";
@@ -187,7 +186,7 @@ impl PemEncodedKey {
187186
// Though PKCS#11 keys shouldn't have anything else.
188187
// It will get confusing with certificates.
189188
fn extract_first_bitstring(asn1: &[simple_asn1::ASN1Block]) -> Result<&[u8]> {
190-
for asn1_entry in asn1.iter() {
189+
for asn1_entry in asn1 {
191190
match asn1_entry {
192191
simple_asn1::ASN1Block::Sequence(_, entries) => {
193192
if let Ok(result) = extract_first_bitstring(entries) {
@@ -215,7 +214,7 @@ fn classify_pem(asn1: &[simple_asn1::ASN1Block]) -> Option<Classification> {
215214
let rsa_public_key_oid = simple_asn1::oid!(1, 2, 840, 113_549, 1, 1, 1);
216215
let ed25519_oid = simple_asn1::oid!(1, 3, 101, 112);
217216

218-
for asn1_entry in asn1.iter() {
217+
for asn1_entry in asn1 {
219218
match asn1_entry {
220219
simple_asn1::ASN1Block::Sequence(_, entries) => {
221220
if let Some(classification) = classify_pem(entries) {

src/serialization.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ pub(crate) fn b64_encode_part<T: Serialize>(input: &T) -> Result<String> {
2121

2222
/// This is used to decode from base64 then deserialize from JSON to several structs:
2323
/// - The user-provided struct
24-
/// - The ClaimsForValidation struct from this crate to run validation on
24+
/// - The `ClaimsForValidation` struct from this crate to run validation on
2525
pub(crate) struct DecodedJwtPartClaims {
2626
b64_decoded: Vec<u8>,
2727
}

src/validation.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,13 @@ impl Validation {
144144
/// `aud` is a collection of one or more acceptable audience members
145145
/// The simple usage is `set_audience(&["some aud name"])`
146146
pub fn set_audience<T: ToString>(&mut self, items: &[T]) {
147-
self.aud = Some(items.iter().map(|x| x.to_string()).collect())
147+
self.aud = Some(items.iter().map(|x| x.to_string()).collect());
148148
}
149149

150150
/// `iss` is a collection of one or more acceptable issuers members
151151
/// The simple usage is `set_issuer(&["some iss name"])`
152152
pub fn set_issuer<T: ToString>(&mut self, items: &[T]) {
153-
self.iss = Some(items.iter().map(|x| x.to_string()).collect())
153+
self.iss = Some(items.iter().map(|x| x.to_string()).collect());
154154
}
155155

156156
/// Which claims are required to be present for this JWT to be considered valid.

0 commit comments

Comments
 (0)