Finish work on v2 Signed-off-by: constantoine <cleo.rebert@gmail.com>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
diff --git a/.gitignore b/.gitignore
index 315330e..f427329 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+.idea
/target
Cargo.lock
.vscode/settings.json
diff --git a/Cargo.toml b/Cargo.toml
index d056daf..e150eee 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "totp-rs"
-version = "1.4.0"
+version = "2.0.0"
authors = ["Cleo Rebert <cleo.rebert@gmail.com>"]
edition = "2021"
readme = "README.md"
@@ -12,13 +12,12 @@ keywords = ["authentication", "2fa", "totp", "hmac", "otp"]
categories = ["authentication", "web-programming"]
[package.metadata.docs.rs]
-features = [ "qr", "serde_support", "otpauth" ]
+features = [ "qr", "serde_support" ]
[features]
-default = ["otpauth"]
+default = []
qr = ["qrcodegen", "image", "base64"]
serde_support = ["serde"]
-otpauth = ["url"]
[dependencies]
serde = { version = "1.0", features = ["derive"], optional = true }
@@ -26,8 +25,8 @@ sha2 = "~0.10.2"
sha-1 = "~0.10.0"
hmac = "~0.12.1"
base32 = "~0.4"
+url = "2.2.2"
constant_time_eq = "~0.2.1"
qrcodegen = { version = "~1.8", optional = true }
image = { version = "~0.24.2", features = ["png"], optional = true, default-features = false}
-base64 = { version = "~0.13", optional = true }
-url = { version = "2.2.2", optional = true }
\ No newline at end of file
+base64 = { version = "~0.13", optional = true }
\ No newline at end of file
diff --git a/README.md b/README.md
index 91abd4a..4f6ee51 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,9 @@
# totp-rs
![Build Status](https://github.com/constantoine/totp-rs/workflows/Rust/badge.svg) [![docs](https://docs.rs/totp-rs/badge.svg)](https://docs.rs/totp-rs) [![](https://img.shields.io/crates/v/totp-rs.svg)](https://crates.io/crates/totp-rs) [![codecov](https://codecov.io/gh/constantoine/totp-rs/branch/master/graph/badge.svg?token=Q50RAIFVWZ)](https://codecov.io/gh/constantoine/totp-rs) [![cargo-audit](https://github.com/constantoine/totp-rs/actions/workflows/security.yml/badge.svg)](https://github.com/constantoine/totp-rs/actions/workflows/security.yml)
-This library permits the creation of 2FA authentification tokens per TOTP, the verification of said tokens, with configurable time skew, validity time of each token, algorithm and number of digits! Default features are kept as lightweight as possible to ensure small binaries and short compilation time
+This library permits the creation of 2FA authentification tokens per TOTP, the verification of said tokens, with configurable time skew, validity time of each token, algorithm and number of digits! Default features are kept as lightweight as possible to ensure small binaries and short compilation time.
+
+It now supports parsing [otpauth URLs](https://github.com/google/google-authenticator/wiki/Key-Uri-Format) into a totp object, with sane default values.
Be aware that some authenticator apps will accept the `SHA256` and `SHA512` algorithms but silently fallback to `SHA1` which will make the `check()` function fail due to mismatched algorithms.
@@ -12,33 +14,33 @@ With optional feature "qr", you can use it to generate a base64 png qrcode
### serde_support
With optional feature "serde_support", library-defined types will be Deserialize-able and Serialize-able
-### otpauth
-
-With optional feature "otpauth", Support to parse the TOTP parameter from `otpauth` URL
-
## How to use
---
Add it to your `Cargo.toml`:
```toml
[dependencies]
-totp-rs = "~1.4"
+totp-rs = "^2.0"
```
You can then do something like:
```Rust
use std::time::SystemTime;
use totp_rs::{Algorithm, TOTP};
-let totp = TOTP::new(
- Algorithm::SHA1,
- 6,
- 1,
- 30,
- "supersecret",
-);
-let url = totp.get_url("user@example.com", "my-org.com");
-println!("{}", url);
-let token = totp.generate_current().unwrap();
-println!("{}", token);
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ "supersecret",
+ Some("Github".to_string()),
+ "constantoine@github.com".to_string(),
+ ).unwrap();
+ let url = totp.get_url();
+ println!("{}", url);
+ let token = totp.generate_current().unwrap();
+ println!("{}", token);
+}
```
### With qrcode generation
@@ -46,29 +48,33 @@ println!("{}", token);
Add it to your `Cargo.toml`:
```toml
[dependencies.totp-rs]
-version = "~1.4"
+version = "^2.0"
features = ["qr"]
```
You can then do something like:
```Rust
use totp_rs::{Algorithm, TOTP};
-let totp = TOTP::new(
- Algorithm::SHA1,
- 6,
- 1,
- 30,
- "supersecret",
-);
-let code = totp.get_qr("user@example.com", "my-org.com")?;
-println!("{}", code);
+fn main() {
+ let totp = TOTP::new(
+ Algorithm::SHA1,
+ 6,
+ 1,
+ 30,
+ "supersecret",
+ Some("Github".to_string()),
+ "constantoine@github.com".to_string(),
+ ).unwrap();
+ let code = totp.get_qr("user@example.com", "my-org.com")?;
+ println!("{}", code);
+}
```
### With serde support
Add it to your `Cargo.toml`:
```toml
[dependencies.totp-rs]
-version = "~1.4"
+version = "^2.0"
features = ["serde_support"]
```
@@ -76,15 +82,16 @@ features = ["serde_support"]
Add it to your `Cargo.toml`:
```toml
-[dependencies.totp-rs]
-version = "~1.4"
-features = ["otpauth"]
+[dependencies]
+totp-rs = "^2.0"
```
You can then do something like:
```Rust
use totp_rs::TOTP;
-let otpauth = "otpauth://totp/GitHub:test?secret=ABC&issuer=GitHub";
-let totp = TOTP::from_url(otpauth).unwrap();
-println!("{}", totp.generate_current().unwrap());
+fn main() {
+ let otpauth = "otpauth://totp/GitHub:constantoine@github.com?secret=ABC&issuer=GitHub";
+ let totp = TOTP::from_url(otpauth).unwrap();
+ println!("{}", totp.generate_current().unwrap());
+}
```
\ No newline at end of file
diff --git a/src/lib.rs b/src/lib.rs
index 0a388c1..4dd8d5d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -18,8 +18,10 @@
//! 1,
//! 30,
//! "supersecret",
-//! );
-//! let url = totp.get_url("user@example.com", "my-org.com");
+//! Some("Github".to_string()),
+//! "constantoine@github.com".to_string(),
+//! ).unwrap();
+//! let url = totp.get_url();
//! println!("{}", url);
//! let token = totp.generate_current().unwrap();
//! println!("{}", token);
@@ -35,8 +37,10 @@
//! 1,
//! 30,
//! "supersecret",
-//! );
-//! let code = totp.get_qr("user@example.com", "my-org.com").unwrap();
+//! Some("Github".to_string()),
+//! "constantoine@github.com".to_string(),
+//! ).unwrap();
+//! let code = totp.get_qr().unwrap();
//! println!("{}", code);
//! # }
//! ```
@@ -51,7 +55,6 @@ use core::fmt;
#[cfg(feature = "qr")]
use {base64, image::Luma, qrcodegen};
-#[cfg(feature = "otpauth")]
use url::{Host, ParseError, Url};
use hmac::Mac;
@@ -72,15 +75,15 @@ pub enum Algorithm {
impl fmt::Display for Algorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match *self {
+ return match *self {
Algorithm::SHA1 => {
- return f.write_str("SHA1");
+ f.write_str("SHA1")
}
Algorithm::SHA256 => {
- return f.write_str("SHA256");
+ f.write_str("SHA256")
}
Algorithm::SHA512 => {
- return f.write_str("SHA512");
+ f.write_str("SHA512")
}
}
}
@@ -89,7 +92,7 @@ impl fmt::Display for Algorithm {
impl Algorithm {
fn hash<D>(mut digest: D, data: &[u8]) -> Vec<u8>
where
- D: hmac::Mac,
+ D: Mac,
{
digest.update(data);
digest.finalize().into_bytes().to_vec()
@@ -111,7 +114,7 @@ fn system_time() -> Result<u64, SystemTimeError> {
Ok(t)
}
-#[derive(Debug)]
+#[derive(Debug, Eq, PartialEq)]
pub enum TotpUrlError {
Url(ParseError),
Scheme,
@@ -121,7 +124,7 @@ pub enum TotpUrlError {
Digits,
Step,
Issuer,
- Label,
+ AccountName,
}
/// 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
@@ -138,15 +141,18 @@ pub struct TOTP<T = Vec<u8>> {
pub step: u64,
/// As per [rfc-4226](https://tools.ietf.org/html/rfc4226#section-4) the secret should come from a strong source, most likely a CSPRNG. It should be at least 128 bits, but 160 are recommended
pub secret: T,
- /// The "Github" part of "Github:constantoine". Must not contain a color `:`
+ /// The "Github" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your service/website.
- pub issuer: String,
- /// The "alice@google.com" part of "Github:constantoine". Must not contain a color `:`
+ /// Not mandatory, but strongly recommended!
+ pub issuer: Option<String>,
+ /// The "constantoine@github.com" part of "Github:constantoine@github.com". Must not contain a colon `:`
/// For example, the name of your user's account.
- pub label: String
+ pub account_name: String
}
impl <T: AsRef<[u8]>> PartialEq for TOTP<T> {
+ /// Will not check for issuer and account_name equality
+ /// As they aren't taken in account for token generation/token checking
fn eq(&self, other: &Self) -> bool {
if self.algorithm != other.algorithm {
return false;
@@ -170,12 +176,12 @@ impl<T: AsRef<[u8]>> TOTP<T> {
/// # 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: String, label: String) -> Result<TOTP<T>, TotpUrlError> {
- if issuer.contains(':') {
+ pub fn new(algorithm: Algorithm, digits: usize, skew: u8, step: u64, secret: T, issuer: Option<String>, account_name: String) -> Result<TOTP<T>, TotpUrlError> {
+ if issuer.is_some() && issuer.as_ref().unwrap().contains(':') {
return Err(TotpUrlError::Issuer);
}
- if label.contains(':') {
- return Err(TotpUrlError::Label);
+ if account_name.contains(':') {
+ return Err(TotpUrlError::AccountName);
}
Ok(TOTP {
algorithm,
@@ -184,7 +190,7 @@ impl<T: AsRef<[u8]>> TOTP<T> {
step,
secret,
issuer,
- label,
+ account_name,
})
}
@@ -255,10 +261,17 @@ impl<T: AsRef<[u8]>> TOTP<T> {
let mut digits = 6;
let mut step = 30;
let mut secret = Vec::new();
- let issuer: String;
- let label: String;
-
-
+ let mut issuer: Option<String> = None;
+ let account_name: String;
+
+ let path = url.path();
+ if path.contains(':') {
+ let parts = path.split_once(':').unwrap();
+ issuer = Some(parts.0.to_owned());
+ account_name = parts.1.trim_start_matches(':').to_owned();
+ } else {
+ account_name = path.to_owned();
+ }
for (key, value) in url.query_pairs() {
match key.as_ref() {
@@ -282,23 +295,27 @@ impl<T: AsRef<[u8]>> TOTP<T> {
.ok_or(TotpUrlError::Secret)?;
}
"issuer" => {
- issuer = value.parse::<String>().map_err(|_| TotpUrlError::Issuer)?;
+ let param_issuer = value.parse::<String>().map_err(|_| TotpUrlError::Issuer)?;
+ if issuer.is_some() && param_issuer.as_str() != issuer.as_ref().unwrap() {
+ return Err(TotpUrlError::Issuer);
+ }
+ issuer = Some(param_issuer);
}
_ => {}
}
}
- if issuer.contains(':') {
+ if issuer.is_some() && issuer.as_ref().unwrap().contains(':') {
return Err(TotpUrlError::Issuer);
}
- if label.contains(':') {
- return Err(TotpUrlError::Label);
+ if account_name.contains(':') {
+ return Err(TotpUrlError::AccountName);
}
if secret.is_empty() {
return Err(TotpUrlError::Secret);
}
- Ok(TOTP::new(algorithm, digits, 1, step, secret))
+ TOTP::new(algorithm, digits, 1, step, secret, issuer, account_name)
}
/// Will generate a standard URL used to automatically add TOTP auths. Usually used with qr codes
@@ -306,13 +323,19 @@ impl<T: AsRef<[u8]>> TOTP<T> {
/// Label and issuer will be URL-encoded if needed be
/// Secret will be base 32'd without padding, as per RFC.
pub fn get_url(&self) -> String {
- let label: String = url::form_urlencoded::byte_serialize(self.label.as_bytes()).collect();
- let issuer: String = url::form_urlencoded::byte_serialize(self.issuer.as_bytes()).collect();
+ let label: String;
+ let account_name: String = url::form_urlencoded::byte_serialize(self.account_name.as_bytes()).collect();
+ if self.issuer.is_some() {
+ let issuer: String = url::form_urlencoded::byte_serialize(self.issuer.as_ref().unwrap().as_bytes()).collect();
+ label = format!("{0}:{1}?issuer={0}&", issuer, account_name);
+ } else {
+ label = format!("{}?", account_name);
+ }
+
format!(
- "otpauth://totp/{}?secret={}&issuer={}&digits={}&algorithm={}",
+ "otpauth://totp/{}secret={}&digits={}&algorithm={}",
label,
self.get_secret_base32(),
- issuer,
self.digits.to_string(),
self.algorithm,
)
@@ -330,10 +353,10 @@ impl<T: AsRef<[u8]>> TOTP<T> {
///
/// It will also return an error in case it can't encode the qr into a png. This shouldn't happen unless either the qrcode library returns malformed data, or the image library doesn't encode the data correctly
#[cfg(feature = "qr")]
- pub fn get_qr(&self, label: &str, issuer: &str) -> Result<String, Box<dyn std::error::Error>> {
+ pub fn get_qr(&self) -> Result<String, Box<dyn std::error::Error>> {
use image::ImageEncoder;
- let url = self.get_url(label, issuer);
+ let url = self.get_url();
let mut vec = Vec::new();
let qr = qrcodegen::QrCode::encode_text(&url, qrcodegen::QrCodeEcc::Medium)?;
let size = qr.size() as u32;
@@ -395,83 +418,111 @@ mod tests {
use super::*;
#[test]
+ fn new_wrong_issuer() {
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github:".to_string()), "constantoine@github.com".to_string());
+ assert_eq!(totp.is_err(), true);
+ assert_eq!(totp.unwrap_err(), TotpUrlError::Issuer);
+ }
+
+ #[test]
+ fn new_wrong_account_name() {
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine:github.com".to_string());
+ assert_eq!(totp.is_err(), true);
+ assert_eq!(totp.unwrap_err(), TotpUrlError::AccountName);
+ }
+
+ #[test]
+ fn new_wrong_account_name_no_issuer() {
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", None, "constantoine:github.com".to_string());
+ assert_eq!(totp.is_err(), true);
+ assert_eq!(totp.unwrap_err(), TotpUrlError::AccountName);
+ }
+
+ #[test]
fn comparison_ok() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_eq!(reference, test);
}
#[test]
fn comparison_different_algo() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_ne!(reference, test);
}
#[test]
fn comparison_different_digits() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA1, 8, 1, 1, "TestSecret");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 8, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_ne!(reference, test);
}
#[test]
fn comparison_different_skew() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_ne!(reference, test);
}
#[test]
fn comparison_different_step() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecret");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 1, 30, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_ne!(reference, test);
}
#[test]
fn comparison_different_secret() {
- let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretL");
+ let reference = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let test = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecretL", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_ne!(reference, test);
}
#[test]
+ fn url_for_secret_matches_sha1_without_issuer() {
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", None, "constantoine@github.com".to_string()).unwrap();
+ let url = totp.get_url();
+ assert_eq!(url.as_str(), "otpauth://totp/constantoine%40github.com?secret=KRSXG5CTMVRXEZLU&digits=6&algorithm=SHA1");
+ }
+
+ #[test]
fn url_for_secret_matches_sha1() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let url = totp.get_url("test_url", "totp-rs");
- assert_eq!(url.as_str(), "otpauth://totp/test_url?secret=KRSXG5CTMVRXEZLU&issuer=totp-rs&digits=6&algorithm=SHA1");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let url = totp.get_url();
+ assert_eq!(url.as_str(), "otpauth://totp/Github:constantoine%40github.com?issuer=Github&secret=KRSXG5CTMVRXEZLU&digits=6&algorithm=SHA1");
}
#[test]
fn url_for_secret_matches_sha256() {
- let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret");
- let url = totp.get_url("test_url", "totp-rs");
- assert_eq!(url.as_str(), "otpauth://totp/test_url?secret=KRSXG5CTMVRXEZLU&issuer=totp-rs&digits=6&algorithm=SHA256");
+ let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let url = totp.get_url();
+ assert_eq!(url.as_str(), "otpauth://totp/Github:constantoine%40github.com?issuer=Github&secret=KRSXG5CTMVRXEZLU&digits=6&algorithm=SHA256");
}
#[test]
fn url_for_secret_matches_sha512() {
- let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecret");
- let url = totp.get_url("test_url", "totp-rs");
- assert_eq!(url.as_str(), "otpauth://totp/test_url?secret=KRSXG5CTMVRXEZLU&issuer=totp-rs&digits=6&algorithm=SHA512");
+ let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let url = totp.get_url();
+ assert_eq!(url.as_str(), "otpauth://totp/Github:constantoine%40github.com?issuer=Github&secret=KRSXG5CTMVRXEZLU&digits=6&algorithm=SHA512");
}
#[test]
fn returns_base32() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_eq!(totp.get_secret_base32().as_str(), "KRSXG5CTMVRXEZLU");
}
#[test]
fn generate_token() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_eq!(totp.generate(1000).as_str(), "718996");
}
#[test]
fn generate_token_current() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
let time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH).unwrap()
.as_secs();
@@ -480,19 +531,19 @@ mod tests {
#[test]
fn generates_token_sha256() {
- let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA256, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_eq!(totp.generate(1000).as_str(), "480200");
}
#[test]
fn generates_token_sha512() {
- let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA512, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert_eq!(totp.generate(1000).as_str(), "850500");
}
#[test]
fn checks_token() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert!(totp.check("718996", 1000));
assert!(totp.check("712039", 2000));
assert!(!totp.check("527544", 2000));
@@ -501,28 +552,27 @@ mod tests {
#[test]
fn checks_token_current() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 0, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert!(totp.check_current(&totp.generate_current().unwrap()).unwrap());
assert!(!totp.check_current("bogus").unwrap());
}
#[test]
fn checks_token_with_skew() {
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
assert!(
totp.check("527544", 2000) && totp.check("712039", 2000) && totp.check("714250", 2000)
);
}
#[test]
- #[cfg(feature = "otpauth")]
fn from_url_err() {
assert!(TOTP::<Vec<u8>>::from_url("otpauth://hotp/123").is_err());
assert!(TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test").is_err());
+ assert!(TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test:?secret=ABC&digits=8&period=60&algorithm=SHA256").is_err());
}
#[test]
- #[cfg(feature = "otpauth")]
fn from_url_default() {
let totp = TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test?secret=ABC").unwrap();
assert_eq!(totp.secret, base32::decode(base32::Alphabet::RFC4648 { padding: false }, "ABC").unwrap());
@@ -533,7 +583,6 @@ mod tests {
}
#[test]
- #[cfg(feature = "otpauth")]
fn from_url_query() {
let totp = TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test?secret=ABC&digits=8&period=60&algorithm=SHA256").unwrap();
assert_eq!(totp.secret, base32::decode(base32::Alphabet::RFC4648 { padding: false }, "ABC").unwrap());
@@ -544,18 +593,25 @@ mod tests {
}
#[test]
+ fn from_url_query_different_issuers() {
+ let totp = TOTP::<Vec<u8>>::from_url("otpauth://totp/GitHub:test?issuer=Gitlab&secret=ABC&digits=8&period=60&algorithm=SHA256");
+ assert_eq!(totp.is_err(), true);
+ assert_eq!(totp.unwrap_err(), TotpUrlError::Issuer);
+ }
+
+ #[test]
#[cfg(feature = "qr")]
fn generates_qr() {
use sha1::{Digest, Sha1};
- let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret");
- let qr = totp.get_qr("test_url", "totp-rs").unwrap();
+ let totp = TOTP::new(Algorithm::SHA1, 6, 1, 1, "TestSecret", Some("Github".to_string()), "constantoine@github.com".to_string()).unwrap();
+ let qr = totp.get_qr().unwrap();
// Create hash from image
let hash_digest = Sha1::digest(qr.as_bytes());
assert_eq!(
format!("{:x}", hash_digest).as_str(),
- "f671a5a553227a9565c6132024808123f2c9e5e3"
+ "b21a9d4bbb5bd0800bb6bff83a92a2e3314266a5"
);
}
}