Skip to content

Commit

Permalink
Merge branch 'allow-any-key-use' of https://github.com/maxlambrecht/j…
Browse files Browse the repository at this point in the history
…wk-rs into allow-any-key-use
  • Loading branch information
maxlambrecht committed Apr 21, 2022
2 parents b6a9651 + 4b61780 commit f14d979
Show file tree
Hide file tree
Showing 10 changed files with 101 additions and 34 deletions.
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions .idea/jwk-rs.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "jsonwebkey"
version = "0.3.4"
version = "0.3.5"
authors = ["Nick Hynes <[email protected]>"]
description = "JSON Web Key (JWK) (de)serialization, generation, and conversion."
readme = "README.md"
Expand All @@ -13,7 +13,7 @@ edition = "2018"
base64 = "0.13"
bitflags = "1.2"
generic-array = "0.14"
jsonwebtoken = { version = "7.2", optional = true }
jsonwebtoken = { version = "8.0", optional = true }
num-bigint = { version = "0.4", optional = true }
p256 = { version = "0.9", optional = true, features = ["arithmetic"] }
rand = { version = "0.8", optional = true }
Expand All @@ -29,7 +29,7 @@ jwt-convert = ["pkcs-convert", "jsonwebtoken"]
generate = ["p256", "rand"]

[dev-dependencies]
jsonwebtoken = "7.2"
jsonwebtoken = "8.0"

[package.metadata.docs.rs]
all-features = true
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,17 @@ extern crate jsonwebtoken as jwt;
extern crate jsonwebkey as jwk;

#[derive(serde::Serialize, serde::Deserialize)]
struct TokenClaims {}
struct TokenClaims {
exp: usize
}

let mut my_jwk = jwk::JsonWebKey::new(jwk::Key::generate_p256());
my_jwk.set_algorithm(jwk::Algorithm::ES256);

let alg: jwt::Algorithm = my_jwk.algorithm.unwrap().into();
let token = jwt::encode(
&jwt::Header::new(alg),
&TokenClaims {},
&TokenClaims { exp: 1492 },
&my_jwk.key.to_encoding_key(),
).unwrap();

Expand Down
2 changes: 1 addition & 1 deletion src/byte_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ mod tests {
static BASE64_JSON: &str = "\"AQIDBAUGBw\"";

fn get_de() -> serde_json::Deserializer<serde_json::de::StrRead<'static>> {
serde_json::Deserializer::from_str(&BASE64_JSON)
serde_json::Deserializer::from_str(BASE64_JSON)
}

#[test]
Expand Down
56 changes: 43 additions & 13 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,19 @@
//! extern crate jsonwebkey as jwk;
//!
//! #[derive(serde::Serialize, serde::Deserialize)]
//! struct TokenClaims {}
//! struct TokenClaims {
//! exp: usize,
//! }
//!
//! let mut my_jwk = jwk::JsonWebKey::new(jwk::Key::generate_p256());
//! my_jwk.set_algorithm(jwk::Algorithm::ES256);
//!
//! let alg: jwt::Algorithm = my_jwk.algorithm.unwrap().into();
//! let token = jwt::encode(
//! &jwt::Header::new(alg),
//! &TokenClaims {},
//! &TokenClaims {
//! exp: 0,
//! },
//! &my_jwk.key.to_encoding_key(),
//! ).unwrap();
//!
Expand Down Expand Up @@ -80,7 +84,7 @@ pub struct JsonWebKey {
pub key: Box<Key>,

#[serde(default, rename = "use", skip_serializing_if = "Option::is_none")]
pub key_use: Option<String>,
pub key_use: Option<KeyUse>,

#[serde(default, skip_serializing_if = "KeyOps::is_empty")]
pub key_ops: KeyOps,
Expand Down Expand Up @@ -309,7 +313,7 @@ impl Key {
]);
let oids = &[Some(&rsa_encryption_oid), None];
let write_bytevec = |writer: DERWriter<'_>, vec: &ByteVec| {
let bigint = BigUint::from_bytes_be(&vec);
let bigint = BigUint::from_bytes_be(vec);
writer.write_biguint(&bigint);
};

Expand All @@ -333,9 +337,7 @@ impl Key {

match private {
Some(
private
@
RsaPrivate {
private @ RsaPrivate {
d: _,
p: Some(_),
q: Some(_),
Expand Down Expand Up @@ -523,6 +525,35 @@ impl fmt::Debug for RsaPrivate {
}
}

#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyUse {
Signing,
Encryption,
Custom(String),
}

impl Serialize for KeyUse {
fn serialize<S: serde::ser::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Self::Signing => "sig",
Self::Encryption => "enc",
Self::Custom(u) => u.as_str(),
}
.serialize(s)
}
}

impl<'de> Deserialize<'de> for KeyUse {
fn deserialize<D: serde::de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Ok(match <&'de str>::deserialize(d)? {
"sig" => Self::Signing,
"enc" => Self::Encryption,
u => Self::Custom(u.into()),
})
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[allow(clippy::upper_case_acronyms)]
pub enum Algorithm {
Expand Down Expand Up @@ -569,20 +600,19 @@ const _IMPL_JWT_CONVERSIONS: () = {
self.try_to_encoding_key().unwrap()
}

pub fn to_decoding_key(&self) -> jwt::DecodingKey<'static> {
pub fn to_decoding_key(&self) -> jwt::DecodingKey {
match self {
Self::Symmetric { key } => jwt::DecodingKey::from_secret(key).into_static(),
Self::Symmetric { key } => jwt::DecodingKey::from_secret(key),
Self::EC { .. } => {
// The following will not panic: all EC JWKs have public components due to
// typing. PEM conversion will always succeed, for the same reason.
// Hence, jwt::DecodingKey shall have no issue with de-converting.
jwt::DecodingKey::from_ec_pem(self.to_public().unwrap().to_pem().as_bytes())
.unwrap()
.into_static()
}
Self::RSA { .. } => jwt::DecodingKey::from_rsa_pem(self.to_pem().as_bytes())
.unwrap()
.into_static(),
Self::RSA { .. } => {
jwt::DecodingKey::from_rsa_pem(self.to_pem().as_bytes()).unwrap()
}
}
}
}
Expand Down
30 changes: 16 additions & 14 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn deserialize_es256() {
algorithm: Some(Algorithm::ES256),
key_id: Some("a key".into()),
key_ops: KeyOps::empty(),
key_use: Some("enc".to_string()),
key_use: Some(KeyUse::Encryption),
x5: Default::default(),
}
);
Expand Down Expand Up @@ -121,7 +121,7 @@ fn deserialize_es256_with_other_use() {
algorithm: Some(Algorithm::ES256),
key_id: Some("a key".into()),
key_ops: KeyOps::empty(),
key_use: Some("jwt-svid".into()),
key_use: Some(KeyUse::Custom("jwt-svid".into())),
x5: Default::default(),
}
);
Expand Down Expand Up @@ -155,15 +155,17 @@ fn generate_p256() {
extern crate jsonwebtoken as jwt;

#[derive(Serialize, Deserialize)]
struct TokenClaims {}
struct TokenClaims {
exp: usize,
}

let mut the_jwk = JsonWebKey::new(Key::generate_p256());
the_jwk.set_algorithm(Algorithm::ES256).unwrap();

let encoding_key = jwt::EncodingKey::from_ec_der(&the_jwk.key.to_der());
let token = jwt::encode(
&jwt::Header::new(the_jwk.algorithm.unwrap().into()),
&TokenClaims {},
&TokenClaims { exp: 0 },
&encoding_key,
)
.unwrap();
Expand Down Expand Up @@ -286,7 +288,7 @@ fn deserialize_rs256() {
algorithm: None,
key_id: None,
key_ops: KeyOps::WRAP_KEY,
key_use: Some("enc".into()),
key_use: Some(KeyUse::Encryption),
x5: Default::default(),
}
);
Expand All @@ -307,7 +309,7 @@ fn deserialize_rs256_other_use() {
168, 141, 85, 152, 107, 76, 110, 140, 47, 153, 63, 182, 97, 196, 28, 143,
199, 39, 54, 61, 172, 240, 20, 146, 98, 246, 43, 217, 254, 8, 17, 195
]
.into()
.into()
},
private: Some(RsaPrivate {
d: vec![
Expand All @@ -316,51 +318,51 @@ fn deserialize_rs256_other_use() {
44, 209, 101, 31, 104, 135, 249, 115, 121, 253, 233, 26, 195, 12, 12, 230,
48, 76, 32, 42, 114, 123, 3, 83, 73, 244, 217, 115, 207, 134, 116, 1
]
.into(),
.into(),
p: Some(
vec![
232, 4, 56, 200, 119, 159, 215, 182, 167, 254, 46, 75, 64, 241, 205,
35, 28, 233, 31, 174, 113, 88, 228, 159, 254, 160, 129, 238, 175, 165,
95, 35
]
.into()
.into()
),
q: Some(
vec![
181, 37, 95, 165, 231, 194, 177, 253, 98, 90, 96, 44, 215, 54, 47, 197,
209, 44, 82, 43, 244, 84, 193, 46, 64, 27, 91, 78, 40, 227, 252, 225
]
.into()
.into()
),
dp: Some(
vec![
169, 89, 203, 136, 167, 168, 72, 111, 206, 151, 61, 123, 56, 96, 70,
119, 134, 182, 178, 165, 69, 158, 184, 225, 255, 157, 112, 185, 164, 3,
117, 57
]
.into()
.into()
),
dq: Some(
vec![
24, 191, 196, 115, 172, 88, 131, 108, 245, 21, 23, 242, 200, 108, 148,
214, 88, 31, 208, 18, 69, 77, 151, 31, 52, 143, 8, 72, 131, 121, 178,
193
]
.into()
.into()
),
qi: Some(
vec![
105, 216, 80, 28, 127, 8, 25, 113, 95, 44, 67, 39, 103, 155, 127, 77,
224, 169, 231, 56, 18, 193, 9, 45, 39, 105, 102, 202, 92, 84, 27, 67
]
.into()
.into()
)
})
}),
algorithm: None,
key_id: None,
key_ops: KeyOps::WRAP_KEY,
key_use: Some("x509-svid".to_string()),
key_use: Some(KeyUse::Custom("x509-svid".to_string())),
x5: Default::default(),
}
);
Expand All @@ -386,7 +388,7 @@ fn serialize_rs256() {
key_id: None,
algorithm: None,
key_ops: KeyOps::empty(),
key_use: Some("sig".into()),
key_use: Some(KeyUse::Signing),
x5: Default::default(),
};
assert_eq!(
Expand Down
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) mod serde_base64 {
let err_msg = e.to_string().to_lowercase();
#[cfg(not(debug_assertions))]
let err_msg = "invalid base64";
de::Error::custom(err_msg.strip_suffix(".").unwrap_or(&err_msg))
de::Error::custom(err_msg.strip_suffix('.').unwrap_or(&err_msg))
})
}
}
Expand Down

0 comments on commit f14d979

Please sign in to comment.