From fe2363c77bb05a480b9d836a3ac47e4a714a7362 Mon Sep 17 00:00:00 2001 From: Steven Salaun Date: Mon, 8 Aug 2022 17:30:27 +0200 Subject: [PATCH] TOTP::new checks digits value compliance to rfc --- src/lib.rs | 19 +++++++++++++------ src/rfc.rs | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 460dcf7..b768a0f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,6 +135,15 @@ pub enum TotpUrlError { AccountName, } +impl From for TotpUrlError { + fn from(e: Rfc6238Error) -> Self { + match e { + Rfc6238Error::InvalidDigits => TotpUrlError::Digits, + Rfc6238Error::SecretTooSmall => TotpUrlError::Secret, + } + } +} + /// TOTP holds informations as to how to generate an auth code and validate it. Its [secret](struct.TOTP.html#structfield.secret) field is sensitive data, treat it accordingly #[derive(Debug, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] @@ -181,10 +190,14 @@ impl > PartialEq for TOTP { impl> TOTP { /// Will create a new instance of TOTP with given parameters. See [the doc](struct.TOTP.html#fields) for reference as to how to choose those values /// + /// # Description + /// * `digits`: MUST be between 6 & 8 + /// /// # Errors /// /// Will return an error in case issuer or label contain the character ':' pub fn new(algorithm: Algorithm, digits: usize, skew: u8, step: u64, secret: T, issuer: Option, account_name: String) -> Result, TotpUrlError> { + crate::rfc::assert_digits(&digits)?; if issuer.is_some() && issuer.as_ref().unwrap().contains(':') { return Err(TotpUrlError::Issuer); } @@ -340,12 +353,6 @@ impl> TOTP { } } - if issuer.is_some() && issuer.as_ref().unwrap().contains(':') { - return Err(TotpUrlError::Issuer); - } - if account_name.contains(':') { - return Err(TotpUrlError::AccountName); - } if secret.is_empty() { return Err(TotpUrlError::Secret); } diff --git a/src/rfc.rs b/src/rfc.rs index 7d8c319..b34bdaa 100644 --- a/src/rfc.rs +++ b/src/rfc.rs @@ -29,7 +29,7 @@ impl std::fmt::Display for Rfc6238Error { } } -fn assert_digits(digits: &usize) -> Result<(), Rfc6238Error> { +pub fn assert_digits(digits: &usize) -> Result<(), Rfc6238Error> { if !(&6..=&8).contains(&digits) { Err(Rfc6238Error::InvalidDigits) } else {