From 2cf6de86d0cf4f3e73813d8d14eb1bf8230d877e Mon Sep 17 00:00:00 2001 From: Yong Wen Chua Date: Fri, 19 Jul 2019 15:35:52 +0800 Subject: [PATCH] Change Cargo Fmt line length --- .rustfmt.toml | 1 - src/errors.rs | 22 +- src/jwa.rs | 262 +++++++++++++++------ src/jwe.rs | 89 ++++--- src/jwk.rs | 228 +++++++++++------- src/jws.rs | 67 ++++-- src/lib.rs | 118 +++++++--- src/serde_custom/base64_url_uint.rs | 4 +- src/serde_custom/byte_sequence.rs | 4 +- src/serde_custom/flatten.rs | 46 +++- src/serde_custom/option_base64_url_uint.rs | 4 +- src/serde_custom/option_byte_sequence.rs | 4 +- 12 files changed, 592 insertions(+), 257 deletions(-) delete mode 100644 .rustfmt.toml diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index 75306517..00000000 --- a/.rustfmt.toml +++ /dev/null @@ -1 +0,0 @@ -max_width = 120 diff --git a/src/errors.rs b/src/errors.rs index c3f791e9..3b2d2113 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -142,7 +142,9 @@ impl error::Error for Error { IOError(ref err) => err.description(), UriParseError(ref err) => err.description(), KeyRejected(ref err) => err.description_(), - WrongKeyType { .. } => "The wrong type of key was provided for the cryptographic operation", + WrongKeyType { .. } => { + "The wrong type of key was provided for the cryptographic operation" + } WrongEncryptionOptions { .. } => { "Wrong variant of `EncryptionOptions` was provided for the encryption operation" } @@ -209,7 +211,9 @@ impl error::Error for ValidationError { match *self { InvalidSignature => "Invalid Signature", - WrongAlgorithmHeader => "Token provided was signed or encrypted with an unexpected algorithm", + WrongAlgorithmHeader => { + "Token provided was signed or encrypted with an unexpected algorithm" + } MissingRequiredClaims(_) => "Missing required claim", Expired(_) => "Token expired", NotYetValid(_) => "Token not yet valid", @@ -241,11 +245,17 @@ impl fmt::Display for ValidationError { use std::error::Error; match *self { - MissingRequiredClaims(ref fields) => { - write!(f, "The following claims are required, but missing: {:?}", fields) - } + MissingRequiredClaims(ref fields) => write!( + f, + "The following claims are required, but missing: {:?}", + fields + ), Expired(ago) => write!(f, "Token expired {} seconds ago", ago.num_seconds()), - NotYetValid(nyv_for) => write!(f, "Token will be valid in {} seconds", nyv_for.num_seconds()), + NotYetValid(nyv_for) => write!( + f, + "Token will be valid in {} seconds", + nyv_for.num_seconds() + ), TooOld(duration) => write!( f, "Token has been considered too old for {} seconds", diff --git a/src/jwa.rs b/src/jwa.rs index 111749a3..66d03ee2 100644 --- a/src/jwa.rs +++ b/src/jwa.rs @@ -292,7 +292,12 @@ impl SignatureAlgorithm { } /// Verify signature based on the algorithm and secret provided. - pub fn verify(&self, expected_signature: &[u8], data: &[u8], secret: &Secret) -> Result<(), Error> { + pub fn verify( + &self, + expected_signature: &[u8], + data: &[u8], + secret: &Secret, + ) -> Result<(), Error> { use self::SignatureAlgorithm::*; match self { @@ -313,7 +318,11 @@ impl SignatureAlgorithm { Ok(vec![]) } - fn sign_hmac(data: &[u8], secret: &Secret, algorithm: &SignatureAlgorithm) -> Result, Error> { + fn sign_hmac( + data: &[u8], + secret: &Secret, + algorithm: &SignatureAlgorithm, + ) -> Result, Error> { let secret = match *secret { Secret::Bytes(ref secret) => secret, _ => Err("Invalid secret type. A byte array is required".to_string())?, @@ -329,7 +338,11 @@ impl SignatureAlgorithm { Ok(hmac::sign(&key, data).as_ref().to_vec()) } - fn sign_rsa(data: &[u8], secret: &Secret, algorithm: &SignatureAlgorithm) -> Result, Error> { + fn sign_rsa( + data: &[u8], + secret: &Secret, + algorithm: &SignatureAlgorithm, + ) -> Result, Error> { let key_pair = match *secret { Secret::RsaKeyPair(ref key_pair) => key_pair, _ => Err("Invalid secret type. A RsaKeyPair is required".to_string())?, @@ -351,7 +364,11 @@ impl SignatureAlgorithm { Ok(signature) } - fn sign_ecdsa(data: &[u8], secret: &Secret, algorithm: &SignatureAlgorithm) -> Result, Error> { + fn sign_ecdsa( + data: &[u8], + secret: &Secret, + algorithm: &SignatureAlgorithm, + ) -> Result, Error> { let key_pair = match *secret { Secret::EcdsaKeyPair(ref key_pair) => key_pair, _ => Err("Invalid secret type. An EcdsaKeyPair is required".to_string())?, @@ -398,7 +415,8 @@ impl SignatureAlgorithm { ) -> Result<(), Error> { match *secret { Secret::PublicKey(ref public_key) => { - let verification_algorithm: &dyn signature::VerificationAlgorithm = match *algorithm { + let verification_algorithm: &dyn signature::VerificationAlgorithm = match *algorithm + { SignatureAlgorithm::RS256 => &signature::RSA_PKCS1_2048_8192_SHA256, SignatureAlgorithm::RS384 => &signature::RSA_PKCS1_2048_8192_SHA384, SignatureAlgorithm::RS512 => &signature::RSA_PKCS1_2048_8192_SHA512, @@ -411,7 +429,10 @@ impl SignatureAlgorithm { _ => unreachable!("Should not happen"), }; - let public_key = signature::UnparsedPublicKey::new(verification_algorithm, public_key.as_slice()); + let public_key = signature::UnparsedPublicKey::new( + verification_algorithm, + public_key.as_slice(), + ); public_key.verify(&data, &expected_signature)?; Ok(()) } @@ -446,12 +467,16 @@ impl KeyManagementAlgorithm { use self::KeyManagementAlgorithm::*; match self { - A128KW | A192KW | A256KW | A128GCMKW | A192GCMKW | A256GCMKW | PBES2_HS256_A128KW | PBES2_HS384_A192KW - | PBES2_HS512_A256KW => KeyManagementAlgorithmType::SymmetricKeyWrapping, + A128KW | A192KW | A256KW | A128GCMKW | A192GCMKW | A256GCMKW | PBES2_HS256_A128KW + | PBES2_HS384_A192KW | PBES2_HS512_A256KW => { + KeyManagementAlgorithmType::SymmetricKeyWrapping + } RSA1_5 | RSA_OAEP | RSA_OAEP_256 => KeyManagementAlgorithmType::AsymmetricKeyEncryption, DirectSymmetricKey => KeyManagementAlgorithmType::DirectEncryption, ECDH_ES => KeyManagementAlgorithmType::DirectKeyAgreement, - ECDH_ES_A128KW | ECDH_ES_A192KW | ECDH_ES_A256KW => KeyManagementAlgorithmType::KeyAgreementWithKeyWrapping, + ECDH_ES_A128KW | ECDH_ES_A192KW | ECDH_ES_A256KW => { + KeyManagementAlgorithmType::KeyAgreementWithKeyWrapping + } } } @@ -460,7 +485,11 @@ impl KeyManagementAlgorithm { /// If the algorithm is `dir` or `DirectSymmetricKey`, the key provided is the CEK. /// Otherwise, the appropriate algorithm will be used to derive or generate the required CEK /// using the provided key. - pub fn cek(&self, content_alg: ContentEncryptionAlgorithm, key: &jwk::JWK) -> Result, Error> + pub fn cek( + &self, + content_alg: ContentEncryptionAlgorithm, + key: &jwk::JWK, + ) -> Result, Error> where T: Serialize + DeserializeOwned, { @@ -483,7 +512,10 @@ impl KeyManagementAlgorithm { } } - fn cek_aes_gcm(&self, content_alg: ContentEncryptionAlgorithm) -> Result, Error> { + fn cek_aes_gcm( + &self, + content_alg: ContentEncryptionAlgorithm, + ) -> Result, Error> { let key = content_alg.generate_key()?; Ok(jwk::JWK { algorithm: jwk::AlgorithmParameters::OctectKey { @@ -512,7 +544,10 @@ impl KeyManagementAlgorithm { A128GCMKW | A192GCMKW | A256GCMKW => self.aes_gcm_encrypt(payload, key, options), DirectSymmetricKey => match *options { EncryptionOptions::None => Ok(Default::default()), - ref other => Err(unexpected_encryption_options_error!(EncryptionOptions::None, other)), + ref other => Err(unexpected_encryption_options_error!( + EncryptionOptions::None, + other + )), }, _ => Err(Error::UnsupportedOperation), } @@ -550,7 +585,10 @@ impl KeyManagementAlgorithm { let nonce = match *options { EncryptionOptions::AES_GCM { ref nonce } => Ok(nonce), - ref others => Err(unexpected_encryption_options_error!(AES_GCM_ZEROED_NONCE, others)), + ref others => Err(unexpected_encryption_options_error!( + AES_GCM_ZEROED_NONCE, + others + )), }?; // FIXME: Should we check the nonce length here or leave it to ring? @@ -661,7 +699,10 @@ impl ContentEncryptionAlgorithm { let nonce = match *options { EncryptionOptions::AES_GCM { ref nonce } => Ok(nonce), - ref others => Err(unexpected_encryption_options_error!(AES_GCM_ZEROED_NONCE, others)), + ref others => Err(unexpected_encryption_options_error!( + AES_GCM_ZEROED_NONCE, + others + )), }?; // FIXME: Should we check the nonce length here or leave it to ring? @@ -745,7 +786,8 @@ fn aes_gcm_decrypt( let mut in_out = encrypted.encrypted.to_vec(); in_out.append(&mut encrypted.tag.to_vec()); - let plaintext = opening_key.open_in_place(aead::Aad::from(&encrypted.additional_data), &mut in_out)?; + let plaintext = + opening_key.open_in_place(aead::Aad::from(&encrypted.additional_data), &mut in_out)?; Ok(plaintext.to_vec()) } @@ -766,11 +808,16 @@ mod tests { #[test] fn sign_and_verify_none() { let expected_signature: Vec = vec![]; - let actual_signature = - not_err!(SignatureAlgorithm::None.sign("payload".to_string().as_bytes(), &Secret::None,)); + let actual_signature = not_err!( + SignatureAlgorithm::None.sign("payload".to_string().as_bytes(), &Secret::None,) + ); assert_eq!(expected_signature, actual_signature); - not_err!(SignatureAlgorithm::None.verify(vec![].as_slice(), "payload".to_string().as_bytes(), &Secret::None)); + not_err!(SignatureAlgorithm::None.verify( + vec![].as_slice(), + "payload".to_string().as_bytes(), + &Secret::None + )); } #[test] @@ -778,9 +825,10 @@ mod tests { let expected_base64 = "uC_LeRrOxXhZuYm0MKgmSIzi5Hn9-SMmvQoug3WkK6Q"; let expected_bytes: Vec = not_err!(CompactPart::from_base64(&expected_base64)); - let actual_signature = not_err!( - SignatureAlgorithm::HS256.sign("payload".to_string().as_bytes(), &Secret::bytes_from_str("secret"),) - ); + let actual_signature = not_err!(SignatureAlgorithm::HS256.sign( + "payload".to_string().as_bytes(), + &Secret::bytes_from_str("secret"), + )); assert_eq!(&*not_err!(actual_signature.to_base64()), expected_base64); not_err!(SignatureAlgorithm::HS256.verify( @@ -799,22 +847,30 @@ mod tests { /// The base64 encoding from this command will be in `STANDARD` form and not URL_SAFE. #[test] fn sign_and_verify_rs256() { - let private_key = Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); + let private_key = + Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); let payload = "payload".to_string(); let payload_bytes = payload.as_bytes(); // This is standard base64 - let expected_signature = "JIHqiBfUknrFPDLT0gxyoufD06S43ZqWN_PzQqHZqQ-met7kZmkSTYB_rUyotLMxlKkuXdnvKmWm\ - dwGAHWEwDvb5392pCmAAtmUIl6LormxJptWYb2PoF5jmtX_lwV8y4RYIh54Ai51162VARQCKAsxL\ - uH772MEChkcpjd31NWzaePWoi_IIk11iqy6uFWmbLLwzD_Vbpl2C6aHR3vQjkXZi05gA3zksjYAh\ - j-m7GgBt0UFOE56A4USjhQwpb4g3NEamgp51_kZ2ULi4Aoo_KJC6ynIm_pR6rEzBgwZjlCUnE-6o\ - 5RPQZ8Oau03UDVH2EwZe-Q91LaWRvkKjGg5Tcw"; - let expected_signature_bytes: Vec = not_err!(CompactPart::from_base64(&expected_signature)); - - let actual_signature = not_err!(SignatureAlgorithm::RS256.sign(payload_bytes, &private_key)); + let expected_signature = + "JIHqiBfUknrFPDLT0gxyoufD06S43ZqWN_PzQqHZqQ-met7kZmkSTYB_rUyotLMxlKkuXdnvKmWm\ + dwGAHWEwDvb5392pCmAAtmUIl6LormxJptWYb2PoF5jmtX_lwV8y4RYIh54Ai51162VARQCKAsxL\ + uH772MEChkcpjd31NWzaePWoi_IIk11iqy6uFWmbLLwzD_Vbpl2C6aHR3vQjkXZi05gA3zksjYAh\ + j-m7GgBt0UFOE56A4USjhQwpb4g3NEamgp51_kZ2ULi4Aoo_KJC6ynIm_pR6rEzBgwZjlCUnE-6o\ + 5RPQZ8Oau03UDVH2EwZe-Q91LaWRvkKjGg5Tcw"; + let expected_signature_bytes: Vec = + not_err!(CompactPart::from_base64(&expected_signature)); + + let actual_signature = + not_err!(SignatureAlgorithm::RS256.sign(payload_bytes, &private_key)); assert_eq!(&*not_err!(actual_signature.to_base64()), expected_signature); let public_key = Secret::public_key_from_file("test/fixtures/rsa_public_key.der").unwrap(); - not_err!(SignatureAlgorithm::RS256.verify(expected_signature_bytes.as_slice(), payload_bytes, &public_key,)); + not_err!(SignatureAlgorithm::RS256.verify( + expected_signature_bytes.as_slice(), + payload_bytes, + &public_key, + )); } #[test] @@ -839,26 +895,38 @@ mod tests { }; let payload = "payload".to_string(); let payload_bytes = payload.as_bytes(); - let expected_signature = "JIHqiBfUknrFPDLT0gxyoufD06S43ZqWN_PzQqHZqQ-met7kZmkSTYB_rUyotLMxlKkuXdnvKmWm\ - dwGAHWEwDvb5392pCmAAtmUIl6LormxJptWYb2PoF5jmtX_lwV8y4RYIh54Ai51162VARQCKAsxL\ - uH772MEChkcpjd31NWzaePWoi_IIk11iqy6uFWmbLLwzD_Vbpl2C6aHR3vQjkXZi05gA3zksjYAh\ - j-m7GgBt0UFOE56A4USjhQwpb4g3NEamgp51_kZ2ULi4Aoo_KJC6ynIm_pR6rEzBgwZjlCUnE-6o\ - 5RPQZ8Oau03UDVH2EwZe-Q91LaWRvkKjGg5Tcw"; - let expected_signature_bytes: Vec = not_err!(CompactPart::from_base64(&expected_signature)); - not_err!(SignatureAlgorithm::RS256.verify(expected_signature_bytes.as_slice(), payload_bytes, ¶ms,)); + let expected_signature = + "JIHqiBfUknrFPDLT0gxyoufD06S43ZqWN_PzQqHZqQ-met7kZmkSTYB_rUyotLMxlKkuXdnvKmWm\ + dwGAHWEwDvb5392pCmAAtmUIl6LormxJptWYb2PoF5jmtX_lwV8y4RYIh54Ai51162VARQCKAsxL\ + uH772MEChkcpjd31NWzaePWoi_IIk11iqy6uFWmbLLwzD_Vbpl2C6aHR3vQjkXZi05gA3zksjYAh\ + j-m7GgBt0UFOE56A4USjhQwpb4g3NEamgp51_kZ2ULi4Aoo_KJC6ynIm_pR6rEzBgwZjlCUnE-6o\ + 5RPQZ8Oau03UDVH2EwZe-Q91LaWRvkKjGg5Tcw"; + let expected_signature_bytes: Vec = + not_err!(CompactPart::from_base64(&expected_signature)); + not_err!(SignatureAlgorithm::RS256.verify( + expected_signature_bytes.as_slice(), + payload_bytes, + ¶ms, + )); } /// This signature is non-deterministic. #[test] fn sign_and_verify_ps256_round_trip() { - let private_key = Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); + let private_key = + Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); let payload = "payload".to_string(); let payload_bytes = payload.as_bytes(); - let actual_signature = not_err!(SignatureAlgorithm::PS256.sign(payload_bytes, &private_key)); + let actual_signature = + not_err!(SignatureAlgorithm::PS256.sign(payload_bytes, &private_key)); let public_key = Secret::public_key_from_file("test/fixtures/rsa_public_key.der").unwrap(); - not_err!(SignatureAlgorithm::PS256.verify(actual_signature.as_slice(), payload_bytes, &public_key,)); + not_err!(SignatureAlgorithm::PS256.verify( + actual_signature.as_slice(), + payload_bytes, + &public_key, + )); } /// To generate a (non-deterministic) signature: @@ -875,28 +943,42 @@ mod tests { let payload = "payload".to_string(); let payload_bytes = payload.as_bytes(); - let signature = "TiMXtt3Wmv/a/tbLWuJPDlFYMfuKsD7U5lbBUn2mBu8DLMLj1EplEZNmkB8w65BgUijnu9hxmhwv\ - ET2k7RrsYamEst6BHZf20hIK1yE/YWaktbVmAZwUDdIpXYaZn8ukTsMT06CDrVk6RXF0EPMaSL33\ - tFNPZpz4/3pYQdxco/n6DpaR5206wsur/8H0FwoyiFKanhqLb1SgZqyc+SXRPepjKc28wzBnfWl4\ - mmlZcJ2xk8O2/t1Y1/m/4G7drBwOItNl7EadbMVCetYnc9EILv39hjcL9JvaA9q0M2RB75DIu8SF\ - 9Kr/l+wzUJjWAHthgqSBpe15jLkpO8tvqR89fw=="; + let signature = + "TiMXtt3Wmv/a/tbLWuJPDlFYMfuKsD7U5lbBUn2mBu8DLMLj1EplEZNmkB8w65BgUijnu9hxmhwv\ + ET2k7RrsYamEst6BHZf20hIK1yE/YWaktbVmAZwUDdIpXYaZn8ukTsMT06CDrVk6RXF0EPMaSL33\ + tFNPZpz4/3pYQdxco/n6DpaR5206wsur/8H0FwoyiFKanhqLb1SgZqyc+SXRPepjKc28wzBnfWl4\ + mmlZcJ2xk8O2/t1Y1/m/4G7drBwOItNl7EadbMVCetYnc9EILv39hjcL9JvaA9q0M2RB75DIu8SF\ + 9Kr/l+wzUJjWAHthgqSBpe15jLkpO8tvqR89fw=="; let signature_bytes: Vec = not_err!(BASE64.decode(signature.as_bytes())); let public_key = Secret::public_key_from_file("test/fixtures/rsa_public_key.der").unwrap(); - not_err!(SignatureAlgorithm::PS256.verify(signature_bytes.as_slice(), payload_bytes, &public_key,)); + not_err!(SignatureAlgorithm::PS256.verify( + signature_bytes.as_slice(), + payload_bytes, + &public_key, + )); } /// This signature is non-deterministic. #[test] fn sign_and_verify_es256_round_trip() { - let private_key = - Secret::ecdsa_keypair_from_file(SignatureAlgorithm::ES256, "test/fixtures/ecdsa_private_key.p8").unwrap(); + let private_key = Secret::ecdsa_keypair_from_file( + SignatureAlgorithm::ES256, + "test/fixtures/ecdsa_private_key.p8", + ) + .unwrap(); let payload = "payload".to_string(); let payload_bytes = payload.as_bytes(); - let actual_signature = not_err!(SignatureAlgorithm::ES256.sign(payload_bytes, &private_key)); - - let public_key = Secret::public_key_from_file("test/fixtures/ecdsa_public_key.der").unwrap(); - not_err!(SignatureAlgorithm::ES256.verify(actual_signature.as_slice(), payload_bytes, &public_key,)); + let actual_signature = + not_err!(SignatureAlgorithm::ES256.sign(payload_bytes, &private_key)); + + let public_key = + Secret::public_key_from_file("test/fixtures/ecdsa_public_key.der").unwrap(); + not_err!(SignatureAlgorithm::ES256.verify( + actual_signature.as_slice(), + payload_bytes, + &public_key, + )); } /// Test case from https://github.com/briansmith/ring/blob/a13b8e2/src/ec/suite_b/ecdsa_verify_fixed_tests.txt @@ -911,7 +993,11 @@ mod tests { let signature = "341F6779B75E98BB42E01095DD48356CBF9002DC704AC8BD2A8240B88D3796C6555843B1B\ 4E264FE6FFE6E2B705A376C05C09404303FFE5D2711F3E3B3A010A1"; let signature_bytes: Vec = not_err!(HEXUPPER.decode(signature.as_bytes())); - not_err!(SignatureAlgorithm::ES256.verify(signature_bytes.as_slice(), &payload_bytes, &public_key,)); + not_err!(SignatureAlgorithm::ES256.verify( + signature_bytes.as_slice(), + &payload_bytes, + &public_key, + )); } /// Test case from https://github.com/briansmith/ring/blob/a13b8e2/src/ec/suite_b/ecdsa_verify_fixed_tests.txt @@ -928,7 +1014,11 @@ mod tests { 3903F58B44148F25142EEF8183475EC1F1392F3D6838ABC0C01724709C446888BED7F2CE4\ 642C6839DC18044A2A6AB9DDC960BFAC79F6988E62D452"; let signature_bytes: Vec = not_err!(HEXUPPER.decode(signature.as_bytes())); - not_err!(SignatureAlgorithm::ES384.verify(signature_bytes.as_slice(), &payload_bytes, &public_key,)); + not_err!(SignatureAlgorithm::ES384.verify( + signature_bytes.as_slice(), + &payload_bytes, + &public_key, + )); } #[test] @@ -948,7 +1038,11 @@ mod tests { let invalid_signature = "broken".to_string(); let signature_bytes = invalid_signature.as_bytes(); SignatureAlgorithm::None - .verify(signature_bytes, "payload".to_string().as_bytes(), &Secret::None) + .verify( + signature_bytes, + "payload".to_string().as_bytes(), + &Secret::None, + ) .unwrap(); } @@ -973,7 +1067,11 @@ mod tests { let invalid_signature = "broken".to_string(); let signature_bytes = invalid_signature.as_bytes(); SignatureAlgorithm::RS256 - .verify(signature_bytes, "payload".to_string().as_bytes(), &public_key) + .verify( + signature_bytes, + "payload".to_string().as_bytes(), + &public_key, + ) .unwrap(); } @@ -984,7 +1082,11 @@ mod tests { let invalid_signature = "broken".to_string(); let signature_bytes = invalid_signature.as_bytes(); SignatureAlgorithm::PS256 - .verify(signature_bytes, "payload".to_string().as_bytes(), &public_key) + .verify( + signature_bytes, + "payload".to_string().as_bytes(), + &public_key, + ) .unwrap(); } @@ -995,7 +1097,11 @@ mod tests { let invalid_signature = "broken".to_string(); let signature_bytes = invalid_signature.as_bytes(); SignatureAlgorithm::ES256 - .verify(signature_bytes, "payload".to_string().as_bytes(), &public_key) + .verify( + signature_bytes, + "payload".to_string().as_bytes(), + &public_key, + ) .unwrap(); } @@ -1134,7 +1240,9 @@ mod tests { let cek_alg = KeyManagementAlgorithm::DirectSymmetricKey; let cek = not_err!(cek_alg.cek(jwa::ContentEncryptionAlgorithm::A256GCM, &key)); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_ok()); + assert!( + verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_ok() + ); } /// `KeyManagementAlgorithm::A128GCMKW` returns a random key with the right length when CEK is requested @@ -1155,11 +1263,15 @@ mod tests { let cek_alg = KeyManagementAlgorithm::A128GCMKW; let cek = not_err!(cek_alg.cek(jwa::ContentEncryptionAlgorithm::A128GCM, &key)); assert_eq!(cek.octect_key().unwrap().len(), 128 / 8); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err()); + assert!( + verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err() + ); let cek = not_err!(cek_alg.cek(jwa::ContentEncryptionAlgorithm::A256GCM, &key)); assert_eq!(cek.octect_key().unwrap().len(), 256 / 8); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err()); + assert!( + verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err() + ); } /// `KeyManagementAlgorithm::A256GCMKW` returns a random key with the right length when CEK is requested @@ -1180,11 +1292,15 @@ mod tests { let cek_alg = KeyManagementAlgorithm::A256GCMKW; let cek = not_err!(cek_alg.cek(jwa::ContentEncryptionAlgorithm::A128GCM, &key)); assert_eq!(cek.octect_key().unwrap().len(), 128 / 8); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err()); + assert!( + verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err() + ); let cek = not_err!(cek_alg.cek(jwa::ContentEncryptionAlgorithm::A256GCM, &key)); assert_eq!(cek.octect_key().unwrap().len(), 256 / 8); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err()); + assert!( + verify_slices_are_equal(cek.octect_key().unwrap(), key.octect_key().unwrap()).is_err() + ); } #[test] @@ -1212,7 +1328,11 @@ mod tests { let encrypted_cek = not_err!(cek_alg.wrap_key(cek.octect_key().unwrap(), &key, &options)); let decrypted_cek = not_err!(cek_alg.unwrap_key(&encrypted_cek, enc_alg, &key)); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), decrypted_cek.octect_key().unwrap(),).is_ok()); + assert!(verify_slices_are_equal( + cek.octect_key().unwrap(), + decrypted_cek.octect_key().unwrap(), + ) + .is_ok()); } #[test] @@ -1240,7 +1360,11 @@ mod tests { let encrypted_cek = not_err!(cek_alg.wrap_key(cek.octect_key().unwrap(), &key, &options)); let decrypted_cek = not_err!(cek_alg.unwrap_key(&encrypted_cek, enc_alg, &key)); - assert!(verify_slices_are_equal(cek.octect_key().unwrap(), decrypted_cek.octect_key().unwrap(),).is_ok()); + assert!(verify_slices_are_equal( + cek.octect_key().unwrap(), + decrypted_cek.octect_key().unwrap(), + ) + .is_ok()); } /// `ContentEncryptionAlgorithm::A128GCM` generates CEK of the right length @@ -1280,7 +1404,8 @@ mod tests { let payload = "狼よ、我が敵を食らえ!"; let aad = "My servants never die!"; let enc_alg = jwa::ContentEncryptionAlgorithm::A128GCM; - let encrypted_payload = not_err!(enc_alg.encrypt(payload.as_bytes(), aad.as_bytes(), &key, &options,)); + let encrypted_payload = + not_err!(enc_alg.encrypt(payload.as_bytes(), aad.as_bytes(), &key, &options,)); let decrypted_payload = not_err!(enc_alg.decrypt(&encrypted_payload, &key)); assert!(verify_slices_are_equal(payload.as_bytes(), &decrypted_payload).is_ok()); @@ -1307,7 +1432,8 @@ mod tests { let payload = "狼よ、我が敵を食らえ!"; let aad = "My servants never die!"; let enc_alg = jwa::ContentEncryptionAlgorithm::A256GCM; - let encrypted_payload = not_err!(enc_alg.encrypt(payload.as_bytes(), aad.as_bytes(), &key, &options,)); + let encrypted_payload = + not_err!(enc_alg.encrypt(payload.as_bytes(), aad.as_bytes(), &key, &options,)); let decrypted_payload = not_err!(enc_alg.decrypt(&encrypted_payload, &key)); assert!(verify_slices_are_equal(payload.as_bytes(), &decrypted_payload).is_ok()); diff --git a/src/jwe.rs b/src/jwe.rs index 6f99aa31..9cb17cbb 100644 --- a/src/jwe.rs +++ b/src/jwe.rs @@ -10,7 +10,9 @@ use serde::{self, Deserialize, Deserializer, Serialize, Serializer}; use serde_json; use crate::errors::{DecodeError, Error, ValidationError}; -use crate::jwa::{self, ContentEncryptionAlgorithm, EncryptionOptions, EncryptionResult, KeyManagementAlgorithm}; +use crate::jwa::{ + self, ContentEncryptionAlgorithm, EncryptionOptions, EncryptionResult, KeyManagementAlgorithm, +}; use crate::jwk; use crate::serde_custom; use crate::{CompactJson, CompactPart, Empty}; @@ -380,15 +382,21 @@ where use std::borrow::Cow; // Resolve encryption option - let (key_option, content_option): (_, Cow<'_, _>) = match header.registered.cek_algorithm { - KeyManagementAlgorithm::DirectSymmetricKey => { - (jwa::NONE_ENCRYPTION_OPTIONS, Cow::Borrowed(options)) - } - _ => ( - options, - Cow::Owned(header.registered.enc_algorithm.random_encryption_options()?), - ), - }; + let (key_option, content_option): (_, Cow<'_, _>) = + match header.registered.cek_algorithm { + KeyManagementAlgorithm::DirectSymmetricKey => { + (jwa::NONE_ENCRYPTION_OPTIONS, Cow::Borrowed(options)) + } + _ => ( + options, + Cow::Owned( + header + .registered + .enc_algorithm + .random_encryption_options()?, + ), + ), + }; // RFC 7516 Section 5.1 describes the steps involved in encryption. // From steps 1 to 8, we will first determine the CEK, and then encrypt the CEK. @@ -396,11 +404,11 @@ where .registered .cek_algorithm .cek(header.registered.enc_algorithm, key)?; - let encrypted_cek = - header - .registered - .cek_algorithm - .wrap_key(cek.algorithm.octect_key()?, key, key_option)?; + let encrypted_cek = header.registered.cek_algorithm.wrap_key( + cek.algorithm.octect_key()?, + key, + key_option, + )?; // Update header let mut header = header.clone(); header.update_cek_algorithm(&encrypted_cek); @@ -417,11 +425,12 @@ where // Steps 12 to 14 involves the calculation of `Additional Authenticated Data` for encryption. In // our compact example, our header is the AAD. // Step 15 involves the actual encryption. - let encrypted_payload = - header - .registered - .enc_algorithm - .encrypt(&payload, &header.to_bytes()?, &cek, &content_option)?; + let encrypted_payload = header.registered.enc_algorithm.encrypt( + &payload, + &header.to_bytes()?, + &cek, + &content_option, + )?; // Finally create the JWE let mut compact = crate::Compact::with_capacity(5); @@ -475,8 +484,12 @@ where let tag: Vec = encrypted.part(4)?; // Verify that the algorithms are expected - if header.registered.cek_algorithm != cek_alg || header.registered.enc_algorithm != enc_alg { - Err(Error::ValidationError(ValidationError::WrongAlgorithmHeader))?; + if header.registered.cek_algorithm != cek_alg + || header.registered.enc_algorithm != enc_alg + { + Err(Error::ValidationError( + ValidationError::WrongAlgorithmHeader, + ))?; } // TODO: Steps 4-5 not implemented at the moment. @@ -542,7 +555,9 @@ where /// Convenience method to get a mutable reference to the payload from an Decrypted JWE pub fn payload_mut(&mut self) -> Result<&mut T, Error> { match *self { - Compact::Decrypted { ref mut payload, .. } => Ok(payload), + Compact::Decrypted { + ref mut payload, .. + } => Ok(payload), Compact::Encrypted(_) => Err(Error::UnsupportedOperation), } } @@ -644,7 +659,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("DEF"), Token::StructEnd, @@ -657,7 +675,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("xxx"), Token::StructEnd, @@ -799,9 +820,9 @@ mod tests { registered: crate::RegisteredClaims { issuer: Some(not_err!(FromStr::from_str("https://www.acme.com"))), subject: Some(not_err!(FromStr::from_str("John Doe"))), - audience: Some(crate::SingleOrMultiple::Single(not_err!(FromStr::from_str( - "htts://acme-customer.com" - )))), + audience: Some(crate::SingleOrMultiple::Single(not_err!( + FromStr::from_str("htts://acme-customer.com") + ))), not_before: Some(1234.into()), ..Default::default() }, @@ -814,7 +835,8 @@ mod tests { }), claims.clone(), ); - let jws = not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes()))); + let jws = + not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes()))); // Construct the encryption key let key = cek_oct_key(256 / 8); @@ -873,9 +895,9 @@ mod tests { registered: crate::RegisteredClaims { issuer: Some(not_err!(FromStr::from_str("https://www.acme.com"))), subject: Some(not_err!(FromStr::from_str("John Doe"))), - audience: Some(crate::SingleOrMultiple::Single(not_err!(FromStr::from_str( - "htts://acme-customer.com" - )))), + audience: Some(crate::SingleOrMultiple::Single(not_err!( + FromStr::from_str("htts://acme-customer.com") + ))), not_before: Some(1234.into()), ..Default::default() }, @@ -888,7 +910,8 @@ mod tests { }), claims.clone(), ); - let jws = not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes()))); + let jws = + not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes()))); // Construct the encryption key let key = cek_oct_key(256 / 8); diff --git a/src/jwk.rs b/src/jwk.rs index 222d3533..032a6fad 100644 --- a/src/jwk.rs +++ b/src/jwk.rs @@ -592,7 +592,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("enc"), Token::StructEnd, @@ -605,7 +608,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("enc"), Token::StructEnd, @@ -618,7 +624,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("xxx"), Token::StructEnd, @@ -671,7 +680,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("sign"), Token::StructEnd, @@ -684,7 +696,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("verify"), Token::StructEnd, @@ -697,7 +712,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("encrypt"), Token::StructEnd, @@ -710,7 +728,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("decrypt"), Token::StructEnd, @@ -723,7 +744,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("wrapKey"), Token::StructEnd, @@ -736,7 +760,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("unwrapKey"), Token::StructEnd, @@ -749,7 +776,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("deriveKey"), Token::StructEnd, @@ -762,7 +792,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("deriveBits"), Token::StructEnd, @@ -775,7 +808,10 @@ mod tests { assert_tokens( &test_value, &[ - Token::Struct { name: "Test", len: 1 }, + Token::Struct { + name: "Test", + len: 1, + }, Token::Str("test"), Token::Str("xxx"), Token::StructEnd, @@ -875,12 +911,12 @@ mod tests { key_type: Default::default(), curve: EllipticCurve::P256, x: vec![ - 127, 205, 206, 39, 112, 246, 196, 93, 65, 131, 203, 238, 111, 219, 75, 123, 88, 7, 51, 53, 123, - 233, 239, 19, 186, 207, 110, 60, 123, 209, 84, 69, + 127, 205, 206, 39, 112, 246, 196, 93, 65, 131, 203, 238, 111, 219, 75, 123, 88, + 7, 51, 53, 123, 233, 239, 19, 186, 207, 110, 60, 123, 209, 84, 69, ], y: vec![ - 199, 241, 68, 205, 27, 189, 155, 126, 135, 44, 223, 237, 185, 238, 185, 244, 179, 105, 93, 110, - 169, 11, 36, 173, 138, 70, 35, 40, 133, 136, 229, 173, + 199, 241, 68, 205, 27, 189, 155, 126, 135, 44, 223, 237, 185, 238, 185, 244, + 179, 105, 93, 110, 169, 11, 36, 173, 138, 70, 35, 40, 133, 136, 229, 173, ], d: None, }), @@ -903,12 +939,17 @@ mod tests { keys: vec![ JWK { common: CommonParameters { - algorithm: Some(Algorithm::KeyManagement(jwa::KeyManagementAlgorithm::A128KW)), + algorithm: Some(Algorithm::KeyManagement( + jwa::KeyManagementAlgorithm::A128KW, + )), ..Default::default() }, algorithm: AlgorithmParameters::OctectKey { key_type: Default::default(), - value: vec![25, 172, 32, 130, 225, 114, 26, 181, 138, 106, 254, 192, 95, 133, 74, 82], + value: vec![ + 25, 172, 32, 130, 225, 114, 26, 181, 138, 106, 254, 192, 95, 133, 74, + 82, + ], }, additional: Default::default(), }, @@ -920,10 +961,11 @@ mod tests { algorithm: AlgorithmParameters::OctectKey { key_type: Default::default(), value: vec![ - 3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166, 143, 90, 179, 40, 230, - 240, 84, 201, 40, 169, 15, 132, 178, 210, 80, 46, 191, 211, 251, 90, 146, 210, 6, 71, 239, - 150, 138, 180, 195, 119, 98, 61, 34, 61, 46, 33, 114, 5, 46, 79, 8, 192, 205, 154, 245, - 103, 208, 128, 163, + 3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166, 143, + 90, 179, 40, 230, 240, 84, 201, 40, 169, 15, 132, 178, 210, 80, 46, + 191, 211, 251, 90, 146, 210, 6, 71, 239, 150, 138, 180, 195, 119, 98, + 61, 34, 61, 46, 33, 114, 5, 46, 79, 8, 192, 205, 154, 245, 103, 208, + 128, 163, ], }, additional: Default::default(), @@ -963,12 +1005,13 @@ mod tests { key_type: Default::default(), curve: EllipticCurve::P256, x: vec![ - 48, 160, 66, 76, 210, 28, 41, 68, 131, 138, 45, 117, 201, 43, 55, 231, 110, 162, 13, 159, - 0, 137, 58, 59, 78, 238, 138, 60, 10, 175, 236, 62, + 48, 160, 66, 76, 210, 28, 41, 68, 131, 138, 45, 117, 201, 43, 55, 231, + 110, 162, 13, 159, 0, 137, 58, 59, 78, 238, 138, 60, 10, 175, 236, 62, ], y: vec![ - 224, 75, 101, 233, 36, 86, 217, 136, 139, 82, 179, 121, 189, 251, 213, 30, 232, 105, 239, - 31, 15, 198, 91, 102, 89, 105, 91, 108, 206, 8, 23, 35, + 224, 75, 101, 233, 36, 86, 217, 136, 139, 82, 179, 121, 189, 251, 213, + 30, 232, 105, 239, 31, 15, 198, 91, 102, 89, 105, 91, 108, 206, 8, 23, + 35, ], d: None, }), @@ -983,15 +1026,17 @@ mod tests { algorithm: AlgorithmParameters::RSA(RSAKeyParameters { key_type: Default::default(), n: BigUint::new(vec![ - 2661337731, 446995658, 1209332140, 183172752, 955894533, 3140848734, 581365968, 3217299938, - 3520742369, 1559833632, 1548159735, 2303031139, 1726816051, 92775838, 37272772, 1817499268, - 2876656510, 1328166076, 2779910671, 4258539214, 2834014041, 3172137349, 4008354576, - 121660540, 1941402830, 1620936445, 993798294, 47616683, 272681116, 983097263, 225284287, - 3494334405, 4005126248, 1126447551, 2189379704, 4098746126, 3730484719, 3232696701, - 2583545877, 428738419, 2533069420, 2922211325, 2227907999, 4154608099, 679827337, - 1165541732, 2407118218, 3485541440, 799756961, 1854157941, 3062830172, 3270332715, - 1431293619, 3068067851, 2238478449, 2704523019, 2826966453, 1548381401, 3719104923, - 2605577849, 2293389158, 273345423, 169765991, 3539762026, + 2661337731, 446995658, 1209332140, 183172752, 955894533, 3140848734, + 581365968, 3217299938, 3520742369, 1559833632, 1548159735, 2303031139, + 1726816051, 92775838, 37272772, 1817499268, 2876656510, 1328166076, + 2779910671, 4258539214, 2834014041, 3172137349, 4008354576, 121660540, + 1941402830, 1620936445, 993798294, 47616683, 272681116, 983097263, + 225284287, 3494334405, 4005126248, 1126447551, 2189379704, 4098746126, + 3730484719, 3232696701, 2583545877, 428738419, 2533069420, 2922211325, + 2227907999, 4154608099, 679827337, 1165541732, 2407118218, 3485541440, + 799756961, 1854157941, 3062830172, 3270332715, 1431293619, 3068067851, + 2238478449, 2704523019, 2826966453, 1548381401, 3719104923, 2605577849, + 2293389158, 273345423, 169765991, 3539762026, ]), e: BigUint::new(vec![65537]), ..Default::default() @@ -1020,16 +1065,18 @@ mod tests { key_type: Default::default(), curve: EllipticCurve::P256, x: vec![ - 48, 160, 66, 76, 210, 28, 41, 68, 131, 138, 45, 117, 201, 43, 55, 231, 110, 162, 13, 159, - 0, 137, 58, 59, 78, 238, 138, 60, 10, 175, 236, 62, + 48, 160, 66, 76, 210, 28, 41, 68, 131, 138, 45, 117, 201, 43, 55, 231, + 110, 162, 13, 159, 0, 137, 58, 59, 78, 238, 138, 60, 10, 175, 236, 62, ], y: vec![ - 224, 75, 101, 233, 36, 86, 217, 136, 139, 82, 179, 121, 189, 251, 213, 30, 232, 105, 239, - 31, 15, 198, 91, 102, 89, 105, 91, 108, 206, 8, 23, 35, + 224, 75, 101, 233, 36, 86, 217, 136, 139, 82, 179, 121, 189, 251, 213, + 30, 232, 105, 239, 31, 15, 198, 91, 102, 89, 105, 91, 108, 206, 8, 23, + 35, ], d: Some(vec![ - 243, 189, 12, 7, 168, 31, 185, 50, 120, 30, 213, 39, 82, 246, 12, 200, 154, 107, 229, 229, - 25, 52, 254, 1, 147, 141, 219, 85, 216, 247, 120, 1, + 243, 189, 12, 7, 168, 31, 185, 50, 120, 30, 213, 39, 82, 246, 12, 200, + 154, 107, 229, 229, 25, 52, 254, 1, 147, 141, 219, 85, 216, 247, 120, + 1, ]), }), additional: Default::default(), @@ -1042,62 +1089,71 @@ mod tests { }, algorithm: AlgorithmParameters::RSA(RSAKeyParameters { n: BigUint::new(vec![ - 2661337731, 446995658, 1209332140, 183172752, 955894533, 3140848734, 581365968, 3217299938, - 3520742369, 1559833632, 1548159735, 2303031139, 1726816051, 92775838, 37272772, 1817499268, - 2876656510, 1328166076, 2779910671, 4258539214, 2834014041, 3172137349, 4008354576, - 121660540, 1941402830, 1620936445, 993798294, 47616683, 272681116, 983097263, 225284287, - 3494334405, 4005126248, 1126447551, 2189379704, 4098746126, 3730484719, 3232696701, - 2583545877, 428738419, 2533069420, 2922211325, 2227907999, 4154608099, 679827337, - 1165541732, 2407118218, 3485541440, 799756961, 1854157941, 3062830172, 3270332715, - 1431293619, 3068067851, 2238478449, 2704523019, 2826966453, 1548381401, 3719104923, - 2605577849, 2293389158, 273345423, 169765991, 3539762026, + 2661337731, 446995658, 1209332140, 183172752, 955894533, 3140848734, + 581365968, 3217299938, 3520742369, 1559833632, 1548159735, 2303031139, + 1726816051, 92775838, 37272772, 1817499268, 2876656510, 1328166076, + 2779910671, 4258539214, 2834014041, 3172137349, 4008354576, 121660540, + 1941402830, 1620936445, 993798294, 47616683, 272681116, 983097263, + 225284287, 3494334405, 4005126248, 1126447551, 2189379704, 4098746126, + 3730484719, 3232696701, 2583545877, 428738419, 2533069420, 2922211325, + 2227907999, 4154608099, 679827337, 1165541732, 2407118218, 3485541440, + 799756961, 1854157941, 3062830172, 3270332715, 1431293619, 3068067851, + 2238478449, 2704523019, 2826966453, 1548381401, 3719104923, 2605577849, + 2293389158, 273345423, 169765991, 3539762026, ]), e: BigUint::new(vec![65537]), d: Some(BigUint::new(vec![ - 713032433, 400701404, 3861752269, 1672063644, 3365010676, 3983790198, 2118218649, - 1180059196, 3214193513, 103331652, 3890363798, 149974729, 3621157035, 3968873060, - 2871316584, 4055377082, 3404441811, 2991770705, 1288729501, 2747761153, 3336623437, - 2364731106, 1645984872, 1574081430, 3820298762, 2596433775, 3693531604, 4039342668, - 3035475437, 3285541752, 3070172669, 2361416509, 394294662, 2977738861, 2839890465, - 841230222, 883615744, 114031047, 1313725071, 2810669078, 1097346134, 2647740217, - 2124981186, 1406400018, 1957909244, 3961425321, 3596839919, 2973771986, 615724121, - 3146071647, 471749184, 2647156653, 991511652, 3077695114, 748748083, 354410955, 2713339034, - 932263697, 746803531, 2024924924, 1545546613, 4162159596, 3797483017, 1602687925, + 713032433, 400701404, 3861752269, 1672063644, 3365010676, 3983790198, + 2118218649, 1180059196, 3214193513, 103331652, 3890363798, 149974729, + 3621157035, 3968873060, 2871316584, 4055377082, 3404441811, 2991770705, + 1288729501, 2747761153, 3336623437, 2364731106, 1645984872, 1574081430, + 3820298762, 2596433775, 3693531604, 4039342668, 3035475437, 3285541752, + 3070172669, 2361416509, 394294662, 2977738861, 2839890465, 841230222, + 883615744, 114031047, 1313725071, 2810669078, 1097346134, 2647740217, + 2124981186, 1406400018, 1957909244, 3961425321, 3596839919, 2973771986, + 615724121, 3146071647, 471749184, 2647156653, 991511652, 3077695114, + 748748083, 354410955, 2713339034, 932263697, 746803531, 2024924924, + 1545546613, 4162159596, 3797483017, 1602687925, ])), p: Some(BigUint::new(vec![ - 1238724091, 318372667, 1355643853, 485701733, 3341746677, 1035832885, 3721261079, - 425089171, 2054479354, 1436899400, 562311849, 4217170837, 2023494776, 842246473, - 1670171010, 3629471803, 2613338008, 1336058667, 3907465950, 1278837722, 301706526, - 1508904813, 84700477, 281588688, 1051290981, 4013685922, 1648080502, 3208306609, - 3216888618, 207366948, 2345408890, 4084776684, + 1238724091, 318372667, 1355643853, 485701733, 3341746677, 1035832885, + 3721261079, 425089171, 2054479354, 1436899400, 562311849, 4217170837, + 2023494776, 842246473, 1670171010, 3629471803, 2613338008, 1336058667, + 3907465950, 1278837722, 301706526, 1508904813, 84700477, 281588688, + 1051290981, 4013685922, 1648080502, 3208306609, 3216888618, 207366948, + 2345408890, 4084776684, ])), q: Some(BigUint::new(vec![ - 2896074521, 3807517807, 654326695, 805762229, 302497825, 3687241987, 3756840608, - 1743610977, 2621828332, 419985079, 4047291779, 1029002427, 752954010, 2324424862, - 3992768900, 1440975207, 2944332800, 1547302329, 661218096, 1997018012, 248893995, - 1789089172, 2712859322, 2862464495, 3786711083, 2238161202, 1929865911, 3624669681, - 347922466, 3024873892, 3610141359, 3721907783, + 2896074521, 3807517807, 654326695, 805762229, 302497825, 3687241987, + 3756840608, 1743610977, 2621828332, 419985079, 4047291779, 1029002427, + 752954010, 2324424862, 3992768900, 1440975207, 2944332800, 1547302329, + 661218096, 1997018012, 248893995, 1789089172, 2712859322, 2862464495, + 3786711083, 2238161202, 1929865911, 3624669681, 347922466, 3024873892, + 3610141359, 3721907783, ])), dp: Some(BigUint::new(vec![ - 1155663421, 4052197930, 2875421595, 3507788494, 2881675167, 838917555, 2601651989, - 459386695, 3873213880, 2254232621, 4242124217, 15709214, 292087504, 1069982818, 1853923539, - 1580521844, 4073993812, 2986647068, 2540273745, 2068123243, 2660839470, 2352030253, - 323625625, 2640279336, 791777172, 531977105, 3029809343, 2356061851, 4159835023, - 1928495702, 1195008431, 462098270, + 1155663421, 4052197930, 2875421595, 3507788494, 2881675167, 838917555, + 2601651989, 459386695, 3873213880, 2254232621, 4242124217, 15709214, + 292087504, 1069982818, 1853923539, 1580521844, 4073993812, 2986647068, + 2540273745, 2068123243, 2660839470, 2352030253, 323625625, 2640279336, + 791777172, 531977105, 3029809343, 2356061851, 4159835023, 1928495702, + 1195008431, 462098270, ])), dq: Some(BigUint::new(vec![ - 2218750473, 3313252599, 4264517421, 1492081333, 1067765483, 232198298, 2314112310, - 1187650374, 3740239259, 1635257886, 1103093236, 2491201628, 718947546, 1371343186, - 141466945, 37198959, 835764074, 2453692137, 970482580, 2037297103, 698337642, 4078896579, - 3927675986, 897186496, 2305102129, 417341884, 917323172, 1302381423, 1775079932, 672472846, + 2218750473, 3313252599, 4264517421, 1492081333, 1067765483, 232198298, + 2314112310, 1187650374, 3740239259, 1635257886, 1103093236, 2491201628, + 718947546, 1371343186, 141466945, 37198959, 835764074, 2453692137, + 970482580, 2037297103, 698337642, 4078896579, 3927675986, 897186496, + 2305102129, 417341884, 917323172, 1302381423, 1775079932, 672472846, 3621814299, 3017359391, ])), qi: Some(BigUint::new(vec![ - 2822788373, 565097292, 169554874, 2338166229, 3171059040, 2497414769, 2887328684, - 1224315260, 1462577079, 612121502, 660433863, 1066956358, 2410265369, 3691215764, - 1134057558, 843539511, 694371854, 2599950644, 1558711302, 2053393907, 1148250800, - 1108939089, 377893761, 1098804084, 1819782402, 3151682353, 3812854953, 1602843789, - 369269593, 2731498344, 2724945700, 455294887, + 2822788373, 565097292, 169554874, 2338166229, 3171059040, 2497414769, + 2887328684, 1224315260, 1462577079, 612121502, 660433863, 1066956358, + 2410265369, 3691215764, 1134057558, 843539511, 694371854, 2599950644, + 1558711302, 2053393907, 1148250800, 1108939089, 377893761, 1098804084, + 1819782402, 3151682353, 3812854953, 1602843789, 369269593, 2731498344, + 2724945700, 455294887, ])), ..Default::default() }), @@ -1152,7 +1208,11 @@ mod tests { fn jwk_set_find_some_test() { let keys = find_key_set(); let key = keys.find("first").expect("Should have found key"); - let kid = key.common.key_id.as_ref().expect("Key should have a key id"); + let kid = key + .common + .key_id + .as_ref() + .expect("Key should have a key id"); assert_eq!(kid, "first"); } diff --git a/src/jws.rs b/src/jws.rs index be8630f0..41986678 100644 --- a/src/jws.rs +++ b/src/jws.rs @@ -82,7 +82,10 @@ where compact.push(header)?; compact.push(payload)?; let encoded_payload = compact.encode(); - let signature = header.registered.algorithm.sign(encoded_payload.as_bytes(), secret)?; + let signature = header + .registered + .algorithm + .sign(encoded_payload.as_bytes(), secret)?; compact.push(&signature)?; Ok(Compact::Encoded(compact)) } @@ -93,7 +96,11 @@ where /// Consumes self and convert into decoded form, verifying the signature, if any. /// If the token is already decoded, this is a no-op // TODO: Is the no-op dangerous? What if the secret between the previous decode and this time is different? - pub fn into_decoded(self, secret: &Secret, algorithm: SignatureAlgorithm) -> Result { + pub fn into_decoded( + self, + secret: &Secret, + algorithm: SignatureAlgorithm, + ) -> Result { match self { Compact::Encoded(_) => self.decode(secret, algorithm), Compact::Decoded { .. } => Ok(self), @@ -158,7 +165,9 @@ where /// Convenience method to get a reference to the claims set from a decoded compact JWS pub fn payload_mut(&mut self) -> Result<&mut T, Error> { match *self { - Compact::Decoded { ref mut payload, .. } => Ok(payload), + Compact::Decoded { + ref mut payload, .. + } => Ok(payload), Compact::Encoded(_) => Err(Error::UnsupportedOperation), } } @@ -388,7 +397,10 @@ impl Secret { } /// Convenience function to get the ECDSA Keypair from a PKCS8-DER encoded EC private key. - pub fn ecdsa_keypair_from_file(algorithm: SignatureAlgorithm, path: &str) -> Result { + pub fn ecdsa_keypair_from_file( + algorithm: SignatureAlgorithm, + path: &str, + ) -> Result { let der = Self::read_bytes(path)?; let ring_algorithm = match algorithm { SignatureAlgorithm::ES256 => &signature::ECDSA_P256_SHA256_FIXED_SIGNING, @@ -602,10 +614,11 @@ mod tests { #[test] fn compact_jws_round_trip_none() { - let expected_token = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.\ - eyJpc3MiOiJodHRwczovL3d3dy5hY21lLmNvbS8iLCJzdWIiOiJKb2huIERvZSIsImF1ZCI6Imh0dHM6Ly9\ - hY21lLWN1c3RvbWVyLmNvbS8iLCJuYmYiOjEyMzQsImNvbXBhbnkiOiJBQ01FIiwiZGVwYXJ0bWVudCI6Il\ - RvaWxldCBDbGVhbmluZyJ9."; + let expected_token = + "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.\ + eyJpc3MiOiJodHRwczovL3d3dy5hY21lLmNvbS8iLCJzdWIiOiJKb2huIERvZSIsImF1ZCI6Imh0dHM6Ly9\ + hY21lLWN1c3RvbWVyLmNvbS8iLCJuYmYiOjEyMzQsImNvbXBhbnkiOiJBQ01FIiwiZGVwYXJ0bWVudCI6Il\ + RvaWxldCBDbGVhbmluZyJ9."; let expected_claims = ClaimsSet:: { registered: RegisteredClaims { @@ -668,7 +681,8 @@ mod tests { }), expected_claims.clone(), ); - let token = not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); + let token = + not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); assert_eq!(expected_token, not_err!(token.encoded()).to_string()); let biscuit = not_err!(token.into_decoded( @@ -703,7 +717,8 @@ mod tests { company: "ACME".to_string(), }, }; - let private_key = Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); + let private_key = + Secret::rsa_keypair_from_file("test/fixtures/rsa_private_key.der").unwrap(); let expected_jwt = Compact::new_decoded( From::from(RegisteredHeader { @@ -728,8 +743,9 @@ mod tests { // Conversion is not available in `ring` yet. // See https://github.com/lawliet89/biscuit/issues/71#issuecomment-296445140 for a // way to retrieve it from `SubjectPublicKeyInfo`. - let public_key = "043727F96AAD416887DD75CC2E333C3D8E06DCDF968B6024579449A2B802EFC891F638C75\ - 1CF687E6FF9A280E11B7036585E60CA32BB469C3E57998A289E0860A6"; + let public_key = + "043727F96AAD416887DD75CC2E333C3D8E06DCDF968B6024579449A2B802EFC891F638C75\ + 1CF687E6FF9A280E11B7036585E60CA32BB469C3E57998A289E0860A6"; let jwt = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.\ eyJ0b2tlbl90eXBlIjoic2VydmljZSIsImlhdCI6MTQ5MjkzODU4OH0.\ do_XppIOFthPWlTXL95CIBfgRdyAxbcIsUfM0YxMjCjqvp4ehHFA3I-JasABKzC8CAy4ndhCHsZdpAtK\ @@ -771,7 +787,8 @@ mod tests { }; let expected_jwt = Compact::new_decoded(header.clone(), expected_claims); - let token = not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); + let token = + not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); let biscuit = not_err!(token.into_decoded( &Secret::Bytes("secret".to_string().into_bytes()), SignatureAlgorithm::HS256 @@ -782,7 +799,8 @@ mod tests { #[test] #[should_panic(expected = "PartsLengthError { expected: 3, actual: 1 }")] fn compact_jws_decode_token_missing_parts() { - let token = Compact::::new_encoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"); + let token = + Compact::::new_encoded("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"); let claims = token.decode( &Secret::Bytes("secret".to_string().into_bytes()), SignatureAlgorithm::HS256, @@ -835,13 +853,15 @@ mod tests { #[test] fn compact_jws_round_trip_hs256_for_bytes_payload() { - let expected_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6IlJhbmRvbSBieXRlcyJ9.\ - eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcG\ - xlLmNvbS9pc19yb290Ijp0cnVlfQ.E5ahoj_gMO8WZzSUhquWuBkPLGZm18zaLbyHUQA7TIs"; + let expected_token = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImN0eSI6IlJhbmRvbSBieXRlcyJ9.\ + eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcG\ + xlLmNvbS9pc19yb290Ijp0cnVlfQ.E5ahoj_gMO8WZzSUhquWuBkPLGZm18zaLbyHUQA7TIs"; let payload: Vec = vec![ - 123, 34, 105, 115, 115, 34, 58, 34, 106, 111, 101, 34, 44, 13, 10, 32, 34, 101, 120, 112, 34, 58, 49, 51, - 48, 48, 56, 49, 57, 51, 56, 48, 44, 13, 10, 32, 34, 104, 116, 116, 112, 58, 47, 47, 101, 120, 97, 109, 112, - 108, 101, 46, 99, 111, 109, 47, 105, 115, 95, 114, 111, 111, 116, 34, 58, 116, 114, 117, 101, 125, + 123, 34, 105, 115, 115, 34, 58, 34, 106, 111, 101, 34, 44, 13, 10, 32, 34, 101, 120, + 112, 34, 58, 49, 51, 48, 48, 56, 49, 57, 51, 56, 48, 44, 13, 10, 32, 34, 104, 116, 116, + 112, 58, 47, 47, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 47, 105, 115, 95, + 114, 111, 111, 116, 34, 58, 116, 114, 117, 101, 125, ]; let expected_jwt = Compact::new_decoded( @@ -852,7 +872,8 @@ mod tests { }), payload.clone(), ); - let token = not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); + let token = + not_err!(expected_jwt.into_encoded(&Secret::Bytes("secret".to_string().into_bytes()))); assert_eq!(expected_token, not_err!(token.encoded()).to_string()); let biscuit = not_err!(token.into_decoded( @@ -942,8 +963,8 @@ mod tests { let encoded_token: Compact, Empty> = Compact::new_encoded(&token); let expected_signature: Vec = vec![ - 118, 124, 117, 58, 100, 89, 72, 92, 99, 8, 61, 98, 191, 46, 37, 189, 228, 211, 250, 204, 90, 203, 145, 106, - 234, 246, 58, 142, 114, 111, 169, 226, + 118, 124, 117, 58, 100, 89, 72, 92, 99, 8, 61, 98, 191, 46, 37, 189, 228, 211, 250, + 204, 90, 203, 145, 106, 234, 246, 58, 142, 114, 111, 169, 226, ]; let signature = not_err!(encoded_token.signature()); diff --git a/src/lib.rs b/src/lib.rs index 7883a6fc..03c61853 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -551,13 +551,19 @@ impl Compact { /// Convenience function to split an encoded compact representation into a list of `Base64Url`. pub fn decode(encoded: &str) -> Self { // Never fails - let parts = encoded.split('.').map(|s| FromStr::from_str(s).unwrap()).collect(); + let parts = encoded + .split('.') + .map(|s| FromStr::from_str(s).unwrap()) + .collect(); Self { parts } } /// Convenience function to retrieve a part at a certain index and decode into the type desired pub fn part(&self, index: usize) -> Result { - let part = self.parts.get(index).ok_or_else(|| "Out of bounds".to_string())?; + let part = self + .parts + .get(index) + .ok_or_else(|| "Out of bounds".to_string())?; CompactPart::from_base64(part) } @@ -673,7 +679,9 @@ where { match *self { SingleOrMultiple::Single(ref single) => single.borrow() == value, - SingleOrMultiple::Multiple(ref vector) => vector.iter().map(Borrow::borrow).any(|v| v == value), + SingleOrMultiple::Multiple(ref vector) => { + vector.iter().map(Borrow::borrow).any(|v| v == value) + } } } @@ -978,7 +986,10 @@ impl Default for ValidationOptions { impl RegisteredClaims { /// Validates that the token contains the claims defined as required - pub fn validate_claim_presence(&self, options: ClaimPresenceOptions) -> Result<(), ValidationError> { + pub fn validate_claim_presence( + &self, + options: ClaimPresenceOptions, + ) -> Result<(), ValidationError> { use crate::Presence::Required; let mut missing_claims: Vec<&str> = vec![]; @@ -1021,7 +1032,10 @@ impl RegisteredClaims { } /// Validates that if the token has an `exp` claim, it has not passed. - pub fn validate_exp(&self, validation: Validation) -> Result<(), ValidationError> { + pub fn validate_exp( + &self, + validation: Validation, + ) -> Result<(), ValidationError> { match validation { Validation::Ignored => Ok(()), Validation::Validate(temporal_options) => { @@ -1038,7 +1052,10 @@ impl RegisteredClaims { } /// Validates that if the token has an `nbf` claim, it has passed. - pub fn validate_nbf(&self, validation: Validation) -> Result<(), ValidationError> { + pub fn validate_nbf( + &self, + validation: Validation, + ) -> Result<(), ValidationError> { match validation { Validation::Ignored => Ok(()), Validation::Validate(temporal_options) => { @@ -1055,7 +1072,10 @@ impl RegisteredClaims { } /// Validates that if the token has an `iat` claim, it is not in the future and not older than the Duration - pub fn validate_iat(&self, validation: Validation<(Duration, TemporalOptions)>) -> Result<(), ValidationError> { + pub fn validate_iat( + &self, + validation: Validation<(Duration, TemporalOptions)>, + ) -> Result<(), ValidationError> { match validation { Validation::Ignored => Ok(()), Validation::Validate((max_age, temporal_options)) => { @@ -1079,11 +1099,15 @@ impl RegisteredClaims { match validation { Validation::Ignored => Ok(()), Validation::Validate(expected_aud) => match self.audience { - Some(SingleOrMultiple::Single(ref audience)) if audience != &expected_aud => { - Err(ValidationError::InvalidAudience(self.audience.clone().unwrap())) - } - Some(SingleOrMultiple::Multiple(ref audiences)) if !audiences.contains(&expected_aud) => { - Err(ValidationError::InvalidAudience(self.audience.clone().unwrap())) + Some(SingleOrMultiple::Single(ref audience)) if audience != &expected_aud => Err( + ValidationError::InvalidAudience(self.audience.clone().unwrap()), + ), + Some(SingleOrMultiple::Multiple(ref audiences)) + if !audiences.contains(&expected_aud) => + { + Err(ValidationError::InvalidAudience( + self.audience.clone().unwrap(), + )) } _ => Ok(()), }, @@ -1265,7 +1289,11 @@ mod tests { #[test] fn multiple_strings_serialization_round_trip() { let test = SingleOrMultipleStrings { - values: SingleOrMultiple::Multiple(vec!["foo".to_string(), "bar".to_string(), "baz".to_string()]), + values: SingleOrMultiple::Multiple(vec![ + "foo".to_string(), + "bar".to_string(), + "baz".to_string(), + ]), }; let expected_json = r#"{"values":["foo","bar","baz"]}"#; @@ -1290,9 +1318,12 @@ mod tests { let serialized = not_err!(serde_json::to_string(&test)); assert_eq!(expected_json, serialized); - let deserialized: SingleOrMultipleStringOrUris = not_err!(serde_json::from_str(&serialized)); + let deserialized: SingleOrMultipleStringOrUris = + not_err!(serde_json::from_str(&serialized)); assert_eq!(deserialized, test); - assert!(deserialized.values.contains(&FromStr::from_str("foobar").unwrap())); + assert!(deserialized + .values + .contains(&FromStr::from_str("foobar").unwrap())); assert!(!deserialized .values .contains(&FromStr::from_str("does not exist").unwrap())); @@ -1301,14 +1332,17 @@ mod tests { #[test] fn single_string_or_uri_uri_serialization_round_trip() { let test = SingleOrMultipleStringOrUris { - values: SingleOrMultiple::Single(not_err!(FromStr::from_str("https://www.examples.com/"))), + values: SingleOrMultiple::Single(not_err!(FromStr::from_str( + "https://www.examples.com/" + ))), }; let expected_json = r#"{"values":"https://www.examples.com/"}"#; let serialized = not_err!(serde_json::to_string(&test)); assert_eq!(expected_json, serialized); - let deserialized: SingleOrMultipleStringOrUris = not_err!(serde_json::from_str(&serialized)); + let deserialized: SingleOrMultipleStringOrUris = + not_err!(serde_json::from_str(&serialized)); assert_eq!(deserialized, test); assert!(deserialized .values @@ -1335,10 +1369,13 @@ mod tests { let serialized = not_err!(serde_json::to_string(&test)); assert_eq!(expected_json, serialized); - let deserialized: SingleOrMultipleStringOrUris = not_err!(serde_json::from_str(&serialized)); + let deserialized: SingleOrMultipleStringOrUris = + not_err!(serde_json::from_str(&serialized)); assert_eq!(deserialized, test); - assert!(deserialized.values.contains(&FromStr::from_str("foo").unwrap())); + assert!(deserialized + .values + .contains(&FromStr::from_str("foo").unwrap())); assert!(deserialized .values .contains(&FromStr::from_str("https://www.example.com").unwrap())); @@ -1348,7 +1385,9 @@ mod tests { assert!(deserialized .values .contains(&FromStr::from_str("http://[::1]").unwrap())); - assert!(deserialized.values.contains(&FromStr::from_str("baz").unwrap())); + assert!(deserialized + .values + .contains(&FromStr::from_str("baz").unwrap())); assert!(!deserialized .values .contains(&FromStr::from_str("https://ecorp.com").unwrap())); @@ -1392,7 +1431,8 @@ mod tests { not_before: Some(1234.into()), ..Default::default() }; - let expected_json = r#"{"iss":"https://www.acme.com/","aud":"htts://acme-customer.com/","nbf":1234}"#; + let expected_json = + r#"{"iss":"https://www.acme.com/","aud":"htts://acme-customer.com/","nbf":1234}"#; let serialized = not_err!(serde_json::to_string(&claim)); assert_eq!(expected_json, serialized); @@ -1579,7 +1619,9 @@ mod tests { } #[test] - #[should_panic(expected = "MissingRequiredClaims([\"exp\", \"nbf\", \"iat\", \"aud\", \"iss\", \"sub\", \"jti\"])")] + #[should_panic( + expected = "MissingRequiredClaims([\"exp\", \"nbf\", \"iat\", \"aud\", \"iss\", \"sub\", \"jti\"])" + )] fn validate_times_missing_all() { let registered_claims: RegisteredClaims = Default::default(); let options = ClaimPresenceOptions::strict(); @@ -1600,7 +1642,10 @@ mod tests { assert_eq!( Err(ValidationError::NotYetValid(Duration::seconds(10))), - registered_claims.validate_iat(Validation::Validate((Duration::seconds(0), temporal_options))) + registered_claims.validate_iat(Validation::Validate(( + Duration::seconds(0), + temporal_options + ))) ); } @@ -1618,7 +1663,10 @@ mod tests { assert_eq!( Err(ValidationError::TooOld(Duration::seconds(5))), - registered_claims.validate_iat(Validation::Validate((Duration::seconds(25), temporal_options))) + registered_claims.validate_iat(Validation::Validate(( + Duration::seconds(25), + temporal_options + ))) ); } @@ -1689,7 +1737,9 @@ mod tests { }; assert_eq!( - Err(ValidationError::InvalidIssuer(StringOrUri::String("issuer".into()))), + Err(ValidationError::InvalidIssuer(StringOrUri::String( + "issuer".into() + ))), registered_claims.validate_iss(Validation::Validate(StringOrUri::Uri( Url::parse("http://issuer").unwrap() ))) @@ -1714,12 +1764,15 @@ mod tests { assert_eq!( Err(ValidationError::InvalidAudience(aud.clone())), - registered_claims.validate_aud(Validation::Validate(StringOrUri::String("audience2".into()))) + registered_claims.validate_aud(Validation::Validate(StringOrUri::String( + "audience2".into() + ))) ); assert_eq!( Ok(()), - registered_claims.validate_aud(Validation::Validate(StringOrUri::String("audience".into()))) + registered_claims + .validate_aud(Validation::Validate(StringOrUri::String("audience".into()))) ); } @@ -1744,17 +1797,22 @@ mod tests { assert_eq!( Err(ValidationError::InvalidAudience(aud.clone())), - registered_claims.validate_aud(Validation::Validate(StringOrUri::String("audience2".into()))) + registered_claims.validate_aud(Validation::Validate(StringOrUri::String( + "audience2".into() + ))) ); assert_eq!( Err(ValidationError::InvalidAudience(aud.clone())), - registered_claims.validate_aud(Validation::Validate(StringOrUri::String("https://audience".into()))) + registered_claims.validate_aud(Validation::Validate(StringOrUri::String( + "https://audience".into() + ))) ); assert_eq!( Ok(()), - registered_claims.validate_aud(Validation::Validate(StringOrUri::String("audience".into()))) + registered_claims + .validate_aud(Validation::Validate(StringOrUri::String("audience".into()))) ); } diff --git a/src/serde_custom/base64_url_uint.rs b/src/serde_custom/base64_url_uint.rs index 351dcde5..3d18885e 100644 --- a/src/serde_custom/base64_url_uint.rs +++ b/src/serde_custom/base64_url_uint.rs @@ -36,7 +36,9 @@ where where E: de::Error, { - let bytes = BASE64URL_NOPAD.decode(value.as_bytes()).map_err(E::custom)?; + let bytes = BASE64URL_NOPAD + .decode(value.as_bytes()) + .map_err(E::custom)?; Ok(BigUint::from_bytes_be(&bytes)) } } diff --git a/src/serde_custom/byte_sequence.rs b/src/serde_custom/byte_sequence.rs index ba463094..850853a5 100644 --- a/src/serde_custom/byte_sequence.rs +++ b/src/serde_custom/byte_sequence.rs @@ -32,7 +32,9 @@ where where E: de::Error, { - let bytes = BASE64URL_NOPAD.decode(value.as_bytes()).map_err(E::custom)?; + let bytes = BASE64URL_NOPAD + .decode(value.as_bytes()) + .map_err(E::custom)?; Ok(bytes) } } diff --git a/src/serde_custom/flatten.rs b/src/serde_custom/flatten.rs index de4f30b3..cd940078 100644 --- a/src/serde_custom/flatten.rs +++ b/src/serde_custom/flatten.rs @@ -204,10 +204,14 @@ pub trait FlattenSerializable { .map(|child| child.to_json().map_err(|e| e.to_string())) .collect(); - let (value_maps, errors): (Vec<_>, Vec<_>) = value_maps.into_iter().partition(Result::is_ok); + let (value_maps, errors): (Vec<_>, Vec<_>) = + value_maps.into_iter().partition(Result::is_ok); if !errors.is_empty() { - let errors: Vec = errors.into_iter().map(std::result::Result::unwrap_err).collect(); + let errors: Vec = errors + .into_iter() + .map(std::result::Result::unwrap_err) + .collect(); Err(S::Error::custom(errors.join("; ")))?; } @@ -222,7 +226,10 @@ pub trait FlattenSerializable { if let DuplicateKeysBehaviour::RaiseError = self.duplicate_keys() { // We need to check for duplicate keys - let keys: Vec> = value_maps.iter().map(|k| k.keys().cloned().collect()).collect(); + let keys: Vec> = value_maps + .iter() + .map(|k| k.keys().cloned().collect()) + .collect(); if pairwise_intersection(keys.as_slice()) { Err(S::Error::custom("Structs have duplicate keys"))? } @@ -439,7 +446,13 @@ mod tests { three: InnerThree, } - impl_flatten_serde!(OuterNoDuplicates, DuplicateKeysBehaviour::RaiseError, one, two, three); + impl_flatten_serde!( + OuterNoDuplicates, + DuplicateKeysBehaviour::RaiseError, + one, + two, + three + ); /// Will not deserialize due to conflicting keys #[derive(Eq, PartialEq, Debug, Clone, Default)] @@ -449,7 +462,13 @@ mod tests { three: InnerThree, } - impl_flatten_serde!(OuterOverwrite, DuplicateKeysBehaviour::Overwrite, one, two, three); + impl_flatten_serde!( + OuterOverwrite, + DuplicateKeysBehaviour::Overwrite, + one, + two, + three + ); #[derive(Eq, PartialEq, Debug, Clone, Default)] struct Outer { @@ -465,7 +484,12 @@ mod tests { generic: T, } - impl_flatten_serde_generic!(OuterGeneric, DuplicateKeysBehaviour::RaiseError, one, generic); + impl_flatten_serde_generic!( + OuterGeneric, + DuplicateKeysBehaviour::RaiseError, + one, + generic + ); #[test] fn pairwise_intersection_for_one() { @@ -475,13 +499,19 @@ mod tests { #[test] fn pairwise_intersection_for_two_sets() { - let sets: Vec> = vec![[1, 2, 3].iter().cloned().collect(), [3].iter().cloned().collect()]; + let sets: Vec> = vec![ + [1, 2, 3].iter().cloned().collect(), + [3].iter().cloned().collect(), + ]; assert!(pairwise_intersection(sets.as_slice())) } #[test] fn pairwise_non_intersection_for_two_sets() { - let sets: Vec> = vec![[1, 2, 3].iter().cloned().collect(), [99, 101].iter().cloned().collect()]; + let sets: Vec> = vec![ + [1, 2, 3].iter().cloned().collect(), + [99, 101].iter().cloned().collect(), + ]; assert!(!pairwise_intersection(sets.as_slice())) } diff --git a/src/serde_custom/option_base64_url_uint.rs b/src/serde_custom/option_base64_url_uint.rs index 1aa36de8..e6fd6c9b 100644 --- a/src/serde_custom/option_base64_url_uint.rs +++ b/src/serde_custom/option_base64_url_uint.rs @@ -55,7 +55,9 @@ where where E: de::Error, { - let bytes = BASE64URL_NOPAD.decode(value.as_bytes()).map_err(E::custom)?; + let bytes = BASE64URL_NOPAD + .decode(value.as_bytes()) + .map_err(E::custom)?; Ok(Some(BigUint::from_bytes_be(&bytes))) } } diff --git a/src/serde_custom/option_byte_sequence.rs b/src/serde_custom/option_byte_sequence.rs index 06ec7816..d62cfec0 100644 --- a/src/serde_custom/option_byte_sequence.rs +++ b/src/serde_custom/option_byte_sequence.rs @@ -51,7 +51,9 @@ where where E: de::Error, { - let bytes = BASE64URL_NOPAD.decode(value.as_bytes()).map_err(E::custom)?; + let bytes = BASE64URL_NOPAD + .decode(value.as_bytes()) + .map_err(E::custom)?; Ok(Some(bytes)) } }