Skip to content

Commit

Permalink
chore: Clippy fixes (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
LucFauvel authored Apr 25, 2024
1 parent d5b4542 commit aa59686
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 49 deletions.
12 changes: 10 additions & 2 deletions examples/web-server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,15 +75,17 @@ impl TestController {
}

#[post("/register")]
async fn complete_register(&self, cred: Json<PublicKeyCredential>) -> () {
async fn complete_register(&self, cred: Json<PublicKeyCredential>) -> Result<(), TestError> {
let cred = cred.into_inner();
let uuid = base64::encode("e1aea4d6-d2ee-4218-9f1c-5ccddadaa1a7");
if let Some(context) = self.reg_contexts.read().expect("should be ok").get(&uuid) {
let mut verifier = CredentialCreationVerifier::new(cred.clone(), context.clone(), "http://localhost");
if let Ok(result) = verifier.verify() {
self.creds.write().unwrap().insert(cred.id, (result.public_key, result.sign_count));
self.creds.write().unwrap().insert(cred.id, (result.public_key, result.sign_count));
}
}

Ok(())
}

#[get("/sign")]
Expand Down Expand Up @@ -150,6 +152,12 @@ impl CorsMiddleware {
}
}

impl Default for CorsMiddleware {
fn default() -> Self {
Self::new()
}
}

#[middleware]
impl CorsMiddleware {
// fn resolve(&self, req: &mut SyncRequest, res: &mut SyncResponse) -> RequestContinuation {
Expand Down
2 changes: 1 addition & 1 deletion src/oath/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ pub(crate) fn dt(hmac_res: &[u8]) -> u32 {
let offset_val = (hmac_res[hmac_res.len() - 1] & 0x0F) as usize;
let h = &hmac_res[offset_val..offset_val + 4];

((h[0] as u32 & 0x7f) << 24) | ((h[1] as u32 & 0xff) << 16) | ((h[2] as u32 & 0xff) << 8) | (h[3] as u32 & 0xff) as u32
((h[0] as u32 & 0x7f) << 24) | ((h[1] as u32 & 0xff) << 16) | ((h[2] as u32 & 0xff) << 8) | (h[3] as u32 & 0xff)
}

#[inline]
Expand Down
14 changes: 7 additions & 7 deletions src/oath/totp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,11 @@ impl TOTPContext {

/// Generate a TOTP code in a given time
fn gen_time_diff(&self, time: u64) -> String {
let mut counter = (time - self.initial_time) / self.period as u64;
let mut counter = (time - self.initial_time) / self.period;

match self.clock_drift {
d if d > 0 => counter += d.unsigned_abs() as u64,
d if d < 0 => counter -= d.unsigned_abs() as u64,
d if d > 0 => counter += d.unsigned_abs(),
d if d < 0 => counter -= d.unsigned_abs(),
_ => {}
}

Expand All @@ -153,11 +153,11 @@ impl TOTPContext {
return false;
}

let mut counter = (get_time() - self.initial_time) / self.period as u64;
let mut counter = (get_time() - self.initial_time) / self.period;

match self.clock_drift {
d if d > 0 => counter += d.unsigned_abs() as u64,
d if d < 0 => counter -= d.unsigned_abs() as u64,
d if d > 0 => counter += d.unsigned_abs(),
d if d < 0 => counter -= d.unsigned_abs(),
_ => {}
}

Expand Down Expand Up @@ -357,7 +357,7 @@ mod native_bindings {
#[no_mangle]
pub unsafe extern "C" fn totp_gen_with(totp: *mut TOTPContext, elapsed: c_ulong) -> *mut c_char {
let totp = &*totp;
strings::string_to_c_char(totp.gen_with(elapsed as u64))
strings::string_to_c_char(totp.gen_with(elapsed))
}

#[no_mangle]
Expand Down
2 changes: 1 addition & 1 deletion src/u2f/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl U2fRequestBuilder {
}

pub fn challenge(mut self, challenge: String) -> Self {
self.challenge = Some(base64::encode(&challenge));
self.challenge = Some(base64::encode(challenge));
self
}

Expand Down
22 changes: 11 additions & 11 deletions src/webauthn/authenticator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ impl WebauthnAuthenticator {
let bytes = keypair.verifying_key().to_bytes();
let private_key = PrivateKeyResponse {
private_key: keypair.to_bytes().to_vec(),
key_alg: alg.clone(),
key_alg: alg,
};
(
CoseKeyInfo::OKP(OKP {
Expand All @@ -165,7 +165,7 @@ impl WebauthnAuthenticator {
let x = points.x().ok_or(WebauthnCredentialRequestError::CouldNotGenerateKey)?;
let private_key = PrivateKeyResponse {
private_key: secret_key.to_bytes().to_vec(),
key_alg: alg.clone(),
key_alg: alg,
};
(
CoseKeyInfo::EC2(EC2 {
Expand All @@ -184,7 +184,7 @@ impl WebauthnAuthenticator {
let key = rsa::RsaPrivateKey::new(&mut OsRng, 2048).map_err(|_| WebauthnCredentialRequestError::CouldNotGenerateKey)?;
let private_key = PrivateKeyResponse {
private_key: key.to_pkcs1_der()?.to_bytes().to_vec(),
key_alg: alg.clone(),
key_alg: alg,
};
(
CoseKeyInfo::RSA(Rsa {
Expand Down Expand Up @@ -237,7 +237,7 @@ impl WebauthnAuthenticator {
let collected_client_data = CollectedClientData {
request_type: WEBAUTHN_REQUEST_TYPE_CREATE.to_owned(),
challenge: base64::encode_config(challenge, URL_SAFE_NO_PAD),
origin: origin.as_ref().unwrap_or_else(|| &rp_id).clone(),
origin: origin.as_ref().unwrap_or(rp_id).clone(),
cross_origin: false,
token_binding: None,
};
Expand Down Expand Up @@ -309,7 +309,7 @@ impl WebauthnAuthenticator {
let collected_client_data = CollectedClientData {
request_type: WEBAUTHN_REQUEST_TYPE_GET.to_owned(),
challenge: base64::encode_config(challenge, URL_SAFE_NO_PAD),
origin: origin.as_ref().unwrap_or_else(|| &rp_id).clone(),
origin: origin.as_ref().unwrap_or(rp_id).clone(),
cross_origin: false,
token_binding: None,
};
Expand Down Expand Up @@ -355,7 +355,7 @@ impl WebauthnAuthenticator {
}

fn find_best_supported_algorithm(
pub_key_cred_params: &Vec<PublicKeyCredentialParameters>,
pub_key_cred_params: &[PublicKeyCredentialParameters],
) -> Result<CoseAlgorithmIdentifier, WebauthnCredentialRequestError> {
//Order of preference for credential type is: Ed25519 > EC2 > RSA > RS1
let mut possible_credential_types = vec![
Expand All @@ -365,8 +365,8 @@ impl WebauthnAuthenticator {
];

let mut best_alg_index = None;
let mut iterator = pub_key_cred_params.iter();
while let Some(param) = iterator.next() {
let iterator = pub_key_cred_params.iter();
for param in iterator {
if let Some(alg_index) = possible_credential_types
.iter()
.position(|r| *r == CoseAlgorithmIdentifier::from(param.alg))
Expand Down Expand Up @@ -466,7 +466,7 @@ fn test_credential_generation() {
let cred_uuid = Uuid::new_v4().into_bytes().to_vec();
let credential = WebauthnAuthenticator::generate_credential_creation_response(
option.clone(),
Uuid::from_u128(0xDE503f9c_21a4_4f76_b4b7_558eb55c6f89),
Uuid::from_u128(0xde503f9c_21a4_4f76_b4b7_558eb55c6f89),
cred_uuid.clone(),
Some("http://localhost".to_owned()),
AttestationFlags::AttestedCredentialDataIncluded as u8 + AttestationFlags::UserPresent as u8,
Expand All @@ -476,7 +476,7 @@ fn test_credential_generation() {
Ok(cred) => {
let mut verifier = CredentialCreationVerifier::new(cred.credential_response.into(), option, "http://localhost");
let verif_res = verifier.verify();
assert_eq!(verif_res.is_ok(), true);
assert!(verif_res.is_ok());

let req_option = PublicKeyCredentialRequestOptions {
challenge: "test".to_owned(),
Expand Down Expand Up @@ -509,7 +509,7 @@ fn test_credential_generation() {
user_uuid.as_bytes().as_slice(),
0,
);
assert_eq!(req_verifier.verify().is_ok(), true)
assert!(req_verifier.verify().is_ok())
}
Err(e) => {
panic!("{e:?}")
Expand Down
25 changes: 10 additions & 15 deletions src/webauthn/proto/raw_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl AttestationStatement {
AttestationStatement::TPM(value) => serde_cbor::value::to_value(&value).map_err(Error::CborError),
AttestationStatement::FidoU2F(value) => serde_cbor::value::to_value(&value).map_err(Error::CborError),
AttestationStatement::AndroidKey(value) => serde_cbor::value::to_value(&value).map_err(Error::CborError),
AttestationStatement::AndroidSafetynet(value) => serde_cbor::value::to_value(&value).map_err(Error::CborError),
AttestationStatement::AndroidSafetynet(value) => serde_cbor::value::to_value(value).map_err(Error::CborError),
AttestationStatement::None => Ok(Value::Map(BTreeMap::new())),
}
}
Expand Down Expand Up @@ -147,7 +147,7 @@ impl AuthenticatorData {
remaining_cbor = serde_cbor::from_slice::<serde_cbor::Value>(&remaining[offset..])?;
serde_cbor::from_slice::<serde_cbor::Value>(&remaining[..offset])?
}
Err(e) => return Err(Error::CborError(e).into()),
Err(e) => return Err(Error::CborError(e)),
};

let credential_public_key = CredentialPublicKey::from_value(&public_key_cbor)?;
Expand Down Expand Up @@ -183,15 +183,15 @@ impl AuthenticatorData {

pub fn to_vec(self) -> Result<Vec<u8>, Error> {
let mut vec = vec![];
vec.write(&self.rp_id_hash)?;
let _ = vec.write(&self.rp_id_hash)?;
vec.push(self.flags);
vec.write(&self.sign_count.to_be_bytes())?;
let _ = vec.write(&self.sign_count.to_be_bytes())?;

if let Some(att_cred_data) = self.attested_credential_data {
vec.write(&att_cred_data.aaguid)?;
vec.write(&(att_cred_data.credential_id.len() as u16).to_be_bytes())?;
vec.write(&att_cred_data.credential_id)?;
vec.write(&att_cred_data.credential_public_key.to_bytes()?)?;
let _ = vec.write(&att_cred_data.aaguid)?;
let _ = vec.write(&(att_cred_data.credential_id.len() as u16).to_be_bytes())?;
let _ = vec.write(&att_cred_data.credential_id)?;
let _ = vec.write(&att_cred_data.credential_public_key.to_bytes()?)?;
}

Ok(vec)
Expand Down Expand Up @@ -669,21 +669,16 @@ impl FromStr for Coordinates {
}
}

#[derive(PartialEq, Debug, Serialize, Deserialize, Clone, Copy)]
#[derive(PartialEq, Debug, Default, Serialize, Deserialize, Clone, Copy)]
pub enum CoseAlgorithmIdentifier {
Ed25519 = -8,
EC2 = -7,
RSA = -257,
RS1 = -65535,
#[default]
NotSupported,
}

impl Default for CoseAlgorithmIdentifier {
fn default() -> Self {
CoseAlgorithmIdentifier::NotSupported
}
}

impl From<i64> for CoseAlgorithmIdentifier {
fn from(value: i64) -> Self {
match value {
Expand Down
8 changes: 4 additions & 4 deletions src/webauthn/proto/web_message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,11 +154,11 @@ impl From<PublicKeyCredentialRaw> for PublicKeyCredential {
PublicKeyCredential {
id: raw.id,
response: raw.response.map(|response| AuthenticatorAttestationResponse {
attestation_object: response.attestation_object.map(|a| base64::encode(&a)),
attestation_object: response.attestation_object.map(base64::encode),
client_data_json: base64::encode(&response.client_data_json),
authenticator_data: response.authenticator_data.map(|a| base64::encode(&a)),
signature: response.signature.map(|s| base64::encode(&s)),
user_handle: response.user_handle.map(|u| base64::encode(&u)),
authenticator_data: response.authenticator_data.map(base64::encode),
signature: response.signature.map(base64::encode),
user_handle: response.user_handle.map(base64::encode),
}),
}
}
Expand Down
11 changes: 3 additions & 8 deletions src/webauthn/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ impl CredentialRequestBuilder {

pub fn prf_credential<T: Into<Option<Vec<u8>>>>(mut self, credential_id: Vec<u8>, first: Vec<u8>, second: T) -> Self {
if let Some(prf) = self.prf.as_mut() {
let encoded_credential_id = base64::encode_config(&credential_id, base64::URL_SAFE_NO_PAD);
let encoded_credential_id = base64::encode_config(credential_id, base64::URL_SAFE_NO_PAD);
prf.eval_by_credential.insert(
encoded_credential_id,
AuthenticationExtensionsPRFValues {
Expand Down Expand Up @@ -465,13 +465,8 @@ impl CredentialRequestBuilder {

for (credential_id, first, second) in credentials {
let encoded_credential_id = base64::encode_config(&credential_id, base64::URL_SAFE_NO_PAD);
prf.eval_by_credential.insert(
encoded_credential_id,
AuthenticationExtensionsPRFValues {
first,
second: second.into(),
},
);
prf.eval_by_credential
.insert(encoded_credential_id, AuthenticationExtensionsPRFValues { first, second });
}

self
Expand Down

0 comments on commit aa59686

Please sign in to comment.