totp-rs 6.0.0

RFC-compliant TOTP implementation with ease of use as a goal and additional QoL features.
Documentation
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! 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 low-dependency as possible to ensure small binaries and short compilation time.
//!
//! 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.
//!
//! Use the `SHA1` algorithm to avoid this problem.
//!
//! # Examples
//!
//! ```rust
//! # #[cfg(all(feature = "otpauth", feature = "std"))] {
//! use totp_rs::{Algorithm, Builder, Totp};
//!
//! let secret: Vec<u8> = vec![0; 20]; // You want an actual 20bytes of randomness here.
//!
//! let totp: Totp = Builder::new().
//!     with_algorithm(Algorithm::SHA256).
//!     with_secret(secret).
//!     with_account_name("constantoine@github.com").
//!     with_issuer(Some("Github")).
//!     build().
//!     unwrap();
//!
//! let token = totp.generate_current();
//! println!("{}", token);
//! # }
//! ```
//!
//! ```rust
//! # #[cfg(all(feature = "gen_secret", feature = "std"))] {
//! use totp_rs::{Builder, Totp};
//!
//! let totp: Totp = Builder::new().
//!     build().
//!     unwrap();
//!
//! let token = totp.generate_current();
//! println!("{}", token);
//!
//! let secret = totp.secret().as_bytes();
//! # }
//! ```
//!
//! ```rust
//! # #[cfg(feature = "qr")] {
//! use totp_rs::{Algorithm, Builder, Totp};
//!
//! let secret: Vec<u8> = vec![0; 20]; // You want an actual 20bytes of randomness here.
//!
//! let totp: Totp = Builder::new().
//!     with_secret(secret).
//!     with_account_name("constantoine@github.com").
//!     with_issuer(Some("Github")).
//!     build().
//!     unwrap();
//!
//! let url = totp.to_url().unwrap();
//! println!("{}", url);
//! let code = totp.to_qr_base64().unwrap();
//! println!("{}", code);
//! # }
//! ```

// enable `doc_cfg` feature for `docs.rs`.
#![cfg_attr(docsrs, feature(doc_cfg))]
// Only allow implicit `use std::prelude::*;` during testing.
#![cfg_attr(not(test), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

mod algorithm;
mod builder;
mod custom_providers;
mod error;
mod rfc;
mod secret;
mod token;

#[cfg(feature = "otpauth")]
mod url;

#[cfg(feature = "migration")]
mod migration;

pub use algorithm::Algorithm;
pub use builder::Builder;
pub use error::TotpError;
pub use secret::{Secret, SecretParseError};
pub use token::Token;

#[cfg(feature = "migration")]
pub use migration::*;

use core::fmt;

#[cfg(feature = "std")]
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(feature = "std")]
fn system_time() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system time cannot be set before the unix epoch")
        .as_secs()
}

/// 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.
///
/// Comparison via [PartialEq] uses [Secret]'s constant-time equality for the secret field.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop))]
pub struct Totp {
    /// SHA-1 is the most widespread algorithm used, and for totp purposes, SHA-1 hash collisions are [not a problem](https://tools.ietf.org/html/rfc4226#appendix-B.2) as HMAC-SHA-1 is not impacted.
    /// It's also the main one cited in [rfc-6238](https://tools.ietf.org/html/rfc6238#section-3) even though the [reference implementation](https://tools.ietf.org/html/rfc6238#appendix-A) permits the use of SHA-1, SHA-256 and SHA-512.
    ///
    /// <div class="warning">Not all clients support other algorithms than SHA-1, and some will silently accept them and use SHA-1 under the hood.</div>
    #[cfg_attr(feature = "zeroize", zeroize(skip))]
    pub(crate) algorithm: Algorithm,
    /// The number of digits composing the auth code. Per [rfc-4226](https://tools.ietf.org/html/rfc4226#section-5.3), this can oscillate between 6 and 8 digits.
    pub(crate) digits: u8,
    /// Number of steps allowed as network delay. A value of 1 would mean a code valid for the step before or the step after current step would be accepted.
    /// The recommended value per [rfc-6238](https://tools.ietf.org/html/rfc6238#section-5.2) is 1.
    /// Anything more is sketchy, and anyone recommending more is, by definition, ugly and stupid.
    pub(crate) skew: u16,
    /// Duration in seconds of a step. The recommended value per [rfc-6238](https://tools.ietf.org/html/rfc6238#section-5.2) is 30 seconds.
    pub(crate) 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.
    ///
    /// non-encoded value.
    pub(crate) secret: Secret,
    #[cfg(feature = "otpauth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "otpauth")))]
    #[cfg_attr(feature = "serde", serde(default))]
    /// The "Github" part of "Github:constantoine@github.com". Must not contain a colon `:`
    /// For example, the name of your service/website.
    /// Not mandatory, but strongly recommended!
    pub(crate) issuer: Option<alloc::boxed::Box<str>>,
    #[cfg(feature = "otpauth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "otpauth")))]
    #[cfg_attr(feature = "serde", serde(default))]
    /// 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(crate) account_name: alloc::boxed::Box<str>,
}

impl Totp {
    /// Get currently used [Algorithm].
    /// See [Builder::with_algorithm] for more details on this value.
    pub const fn algorithm(&self) -> Algorithm {
        self.algorithm
    }

    /// Get how many digits the generated code will be made of.
    /// See [Builder::with_digits] for more details on this value.
    pub const fn digits(&self) -> u8 {
        self.digits
    }

    /// Get how many steps behind or forward are accepted to account for network skew.
    /// See [Builder::with_skew] for more details on this value.
    pub const fn skew(&self) -> u16 {
        self.skew
    }

    /// Get how many seconds a step lasts.
    /// See [Builder::with_step_duration] for more details on this value.
    pub const fn step(&self) -> u64 {
        self.step
    }

    #[cfg(feature = "otpauth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "otpauth")))]
    /// Get the name of the issuer who created this Totp.
    /// This value is not always provided.
    /// See [Builder::with_issuer] for more details on this value.
    pub fn issuer(&self) -> Option<&str> {
        self.issuer.as_deref()
    }

    #[cfg(feature = "otpauth")]
    #[cfg_attr(docsrs, doc(cfg(feature = "otpauth")))]
    /// Name of the account the Totp was issued for.
    /// See [Builder::with_account_name] for more details on this value.
    pub const fn account_name(&self) -> &str {
        &self.account_name
    }
}

impl core::fmt::Display for Totp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut succeeded = true;

        succeeded &= write!(
            f,
            "digits: {}; step: {}; alg: {}",
            self.digits, self.step, self.algorithm,
        )
        .is_ok();

        #[cfg(feature = "otpauth")]
        {
            succeeded &= write!(
                f,
                "; issuer: <{}>({})",
                self.issuer.as_deref().unwrap_or("None"),
                self.account_name
            )
            .is_ok();
        }

        succeeded.then_some(()).ok_or(fmt::Error)
    }
}

/// Default as set in [Builder::new].
/// This implementation shall remain, to avoid breaking compatibility.
/// Use [Self::secret] to retrieve the newly generated secret.
#[cfg(feature = "gen_secret")]
#[cfg_attr(docsrs, doc(cfg(feature = "gen_secret")))]
impl Default for Totp {
    fn default() -> Self {
        use crate::Builder;

        Builder::new().build_noncompliant()
    }
}

impl Totp {
    /// Will sign the given timestamp. Most users will want to interact with [Self::generate].
    pub fn sign(&self, time: u64) -> impl AsRef<[u8]> {
        self.algorithm.sign(self.secret.as_ref(), time / self.step)
    }

    /// Will generate a token given the provided timestamp in seconds.
    ///
    /// # Panics
    ///
    /// Panic if [Self::digits] is >= 10, or >= 7 if this [Self::algorithm] == [Algorithm::Steam].
    pub fn generate(&self, time: u64) -> Token {
        Token::from_signature(self.algorithm, self.digits, self.sign(time).as_ref())
    }

    /// Returns the timestamp of the first second for the next step
    /// given the provided timestamp in seconds.
    pub fn next_step(&self, time: u64) -> u64 {
        let step = time / self.step;

        (step + 1) * self.step
    }

    /// Returns the timestamp of the first second of the next step
    /// According to system time.
    ///
    /// # Panics
    ///
    /// Panics if system time is set before Unix Epoch.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn next_step_current(&self) -> u64 {
        self.next_step(system_time())
    }

    /// Give the ttl (in seconds) of the current token.
    ///
    /// # Panics
    ///
    /// Panics if system time is set before Unix Epoch.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn ttl(&self) -> u64 {
        self.step - (system_time() % self.step)
    }

    /// Generate a token from the current system time.
    ///
    /// # Panics
    ///
    /// Panics if system time is set before Unix Epoch.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn generate_current(&self) -> Token {
        self.generate(system_time())
    }

    /// Will check if token is valid given the provided timestamp in seconds, accounting [skew](struct.Totp.html#structfield.skew)
    /// If the token is valid, return the matched step.
    ///
    /// <div class="warning">
    /// As per <a href="https://datatracker.ietf.org/doc/html/rfc6238#section-5.2">rfc-6239</a>, a code should only be accepted once.
    /// If a user wants to log in several times in a row (maybe multiple device?) they have to wait for the next time-window.
    /// This library does NOT handle this, and it is the caller's responsibility to make sure a specific step only gets accepted once.
    /// This is the reason why check now returns an optional u64 step-number.
    /// </div>
    ///
    /// # Panics
    ///
    /// Panic if [Self::digits] is >= 10, or >= 7 if this [Self::algorithm] == [Algorithm::Steam].
    pub fn check(&self, token: &str, time: u64) -> Option<u64> {
        let token = Token::try_from_formatted_string(self.algorithm, self.digits, token)?;

        let origin = time / self.step;
        let mut window = origin.saturating_sub(self.skew as u64)..=(origin + self.skew as u64);
        window.find(|&counter| self.generate(counter * self.step) == token)
    }

    /// Will check if token is valid by current system time, accounting [skew](struct.Totp.html#structfield.skew)
    /// If the token is valid, return the matched step.
    ///
    /// <div class="warning">
    /// As per <a href="https://datatracker.ietf.org/doc/html/rfc6238#section-5.2">rfc-6239</a>, a code should only be accepted once.
    /// If a user wants to log in several times in a row (maybe multiple device?) they have to wait for the next time-window.
    /// This library does NOT handle this, and it is the caller's responsibility to make sure a specific step only gets accepted once.
    /// This is the reason why check now returns an optional u64 step-number.
    /// </div>
    ///
    /// # Panics
    ///
    /// Panics if system time is set before Unix Epoch.
    #[cfg(feature = "std")]
    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
    pub fn check_current(&self, token: &str) -> Option<u64> {
        self.check(token, system_time())
    }

    /// Provides access to the secret used by this [`Totp`] instance.
    pub const fn secret(&self) -> &Secret {
        &self.secret
    }
}

#[cfg(feature = "qr")]
#[cfg_attr(docsrs, doc(cfg(feature = "qr")))]
impl Totp {
    /// Will return a qrcode to automatically add a TOTP as a base64 string. Needs feature `qr` to be enabled!
    /// Result will be in the form of a string containing a base64-encoded png, which you can embed in HTML without needing
    /// To store the png as a file.
    ///
    /// # Errors
    ///
    /// This will return an error in case the URL gets too long to encode into a QR code.
    /// This would require the to_url method to generate an url bigger than 2000 characters,
    /// Which would be too long for some browsers anyway.
    ///
    /// 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.
    pub fn to_qr_base64(&self) -> Result<alloc::string::String, TotpError> {
        let url = self.to_url()?;
        qrcodegen_image::draw_base64(&url).map_err(|url| TotpError::UrlTooLong { url })
    }

    /// Will return a qrcode to automatically add a TOTP as a byte array. Needs feature `qr` to be enabled!
    /// Result will be in the form of a png file as bytes.
    ///
    /// # Errors
    ///
    /// This will return an error in case the URL gets too long to encode into a QR code.
    /// This would require the to_url method to generate an url bigger than 2000 characters,
    /// Which would be too long for some browsers anyway.
    ///
    /// 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.
    pub fn to_qr_png(&self) -> Result<alloc::vec::Vec<u8>, TotpError> {
        let url = self.to_url()?;
        qrcodegen_image::draw_png(&url).map_err(|url| TotpError::UrlTooLong { url })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "gen_secret")]
    fn default_values() {
        let totp = Totp::default();

        assert_eq!(totp.secret.len(), 20);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn generate_token() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert_eq!(&totp.generate(1000).to_string(), "659761");
    }

    #[test]
    #[cfg(feature = "std")]
    fn generate_token_current() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        let time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(totp.generate(time), totp.generate_current());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn generates_token_sha256() {
        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA256)
            .with_step_duration(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert_eq!(&totp.generate(1000).to_string(), "076417");
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn generates_token_sha512() {
        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA512)
            .with_step_duration(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert_eq!(&totp.generate(1000).to_string(), "473536");
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn checks_token() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_skew(0)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert!(totp.check("659761", 1000).is_some());
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn checks_token_big_skew() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_skew(1001)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert!(totp.check("659761", 1000).is_some());
    }

    #[test]
    #[cfg(feature = "std")]
    fn checks_token_current() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_skew(0)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        let current = totp.generate_current().to_string();
        assert!(totp.check_current(&current).is_some());
        assert!(totp.check_current("bogus").is_none());
    }

    #[test]
    #[cfg(feature = "std")]
    fn check_ttl() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_skew(0)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();

        let ttl = totp.ttl();
        assert!((0..=totp.step).contains(&ttl));
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn checks_token_with_skew() {
        let totp = Builder::new()
            .with_step_duration(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert!(
            totp.check("174269", 1000).is_some()
                && totp.check("659761", 1000).is_some()
                && totp.check("260393", 1000).is_some()
        );
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn next_step() {
        let totp = Builder::new()
            .with_step_duration(30)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert!(totp.next_step(0) == 30);
        assert!(totp.next_step(29) == 30);
        assert!(totp.next_step(30) == 60);
    }

    #[test]
    #[cfg(feature = "std")]
    fn next_step_current() {
        let totp = Builder::new()
            .with_step_duration(30)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build_noncompliant();
        assert!(totp.next_step_current() == totp.next_step(system_time()));
    }

    #[test]
    #[cfg(feature = "qr")]
    fn generates_qr() {
        use qrcodegen_image::qrcodegen;
        use sha2::{Digest, Sha512};

        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA1)
            .with_step_duration(30)
            .with_skew(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .with_issuer(Some("Github"))
            .with_account_name("constantoine@github.com")
            .build_noncompliant();

        let url = totp.to_url().expect("could not generate url");
        let qr = qrcodegen::QrCode::encode_text(&url, qrcodegen::QrCodeEcc::Medium)
            .expect("could not generate qr");
        let data = qrcodegen_image::draw_canvas(qr).into_raw();

        // Create hash from image
        let hash_digest = Sha512::digest(data);
        let hash_hex: String = hash_digest.iter().map(|b| format!("{b:02x}")).collect();
        assert_eq!(
            hash_hex.as_str(),
            "fbb0804f1e4f4c689d22292c52b95f0783b01b4319973c0c50dd28af23dbbbe663dce4eb05a7959086d9092341cb9f103ec5a9af4a973867944e34c063145328"
        );
    }

    #[test]
    #[cfg(feature = "qr")]
    fn generates_qr_base64_ok() {
        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA1)
            .with_step_duration(1)
            .with_skew(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .with_issuer(Some("Github"))
            .with_account_name("constantoine@github.com")
            .build_noncompliant();

        let qr = totp.to_qr_base64();
        assert!(qr.is_ok());
    }

    #[test]
    #[cfg(feature = "qr")]
    fn generates_qr_png_ok() {
        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA1)
            .with_step_duration(1)
            .with_skew(1)
            .with_secret("TestSecretSuperSecret".as_bytes())
            .with_issuer(Some("Github"))
            .with_account_name("constantoine@github.com")
            .build_noncompliant();

        let qr = totp.to_qr_png();
        assert!(qr.is_ok());
    }

    #[test]
    #[cfg(feature = "qr")]
    fn generates_qr_url_too_long() {
        let totp = Builder::new()
            .with_algorithm(Algorithm::SHA1)
            .with_step_duration(30)
            .with_skew(1)
            .with_secret(vec![0xAA; 2048])
            .with_issuer(Some("Github"))
            .with_account_name("constantoine@github.com")
            .build_noncompliant();

        assert!(totp.to_url().is_ok());

        let qr = totp.to_qr_base64();
        assert!(matches!(&qr, &Err(TotpError::UrlTooLong { .. })));
        let error_message = format!("{}", qr.unwrap_err());
        assert!(
            error_message.starts_with(
                "Could not generate a QR code: the generated URL is too long to encode"
            )
        );
    }

    /// Catch any egregious changes to the size of the [`Totp`] type to keep its
    /// stack size reasonably low.
    ///
    /// Sizes are pinned for 64-bit targets; 32-bit has narrower pointers.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn size_test() {
        if cfg!(feature = "otpauth") {
            assert_eq!(size_of::<Totp>(), 72);
        } else {
            assert_eq!(size_of::<Totp>(), 40);
        }
    }

    #[test]
    fn check_totp_display_implementation() {
        let totp = Builder::new().build_noncompliant();

        assert!(!totp.to_string().is_empty());
    }

    /// Pins the serde wire format of the whole [`Totp`] struct: field names,
    /// field order, and both [`Secret`] representations. A failure here means
    /// previously serialized state can no longer be read back.
    #[test]
    #[cfg(all(feature = "serde", feature = "otpauth"))]
    fn serde_totp_wire_format() {
        use serde_test::{Configure, Token, assert_tokens};

        let totp = Builder::new()
            .with_secret("TestSecretSuperSecret".as_bytes())
            .with_issuer(Some("Github"))
            .with_account_name("constantoine@github.com")
            .build()
            .unwrap();

        // Human-readable formats carry the secret as unpadded base32.
        assert_tokens(
            &totp.clone().readable(),
            &[
                Token::Struct {
                    name: "Totp",
                    len: 7,
                },
                Token::Str("algorithm"),
                Token::Str("SHA1"),
                Token::Str("digits"),
                Token::U8(6),
                Token::Str("skew"),
                Token::U16(1),
                Token::Str("step"),
                Token::U64(30),
                Token::Str("secret"),
                Token::Str("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ"),
                Token::Str("issuer"),
                Token::Some,
                Token::Str("Github"),
                Token::Str("account_name"),
                Token::Str("constantoine@github.com"),
                Token::StructEnd,
            ],
        );

        // Binary formats carry the secret as a raw byte string.
        assert_tokens(
            &totp.compact(),
            &[
                Token::Struct {
                    name: "Totp",
                    len: 7,
                },
                Token::Str("algorithm"),
                Token::Str("SHA1"),
                Token::Str("digits"),
                Token::U8(6),
                Token::Str("skew"),
                Token::U16(1),
                Token::Str("step"),
                Token::U64(30),
                Token::Str("secret"),
                Token::Bytes(b"TestSecretSuperSecret"),
                Token::Str("issuer"),
                Token::Some,
                Token::Str("Github"),
                Token::Str("account_name"),
                Token::Str("constantoine@github.com"),
                Token::StructEnd,
            ],
        );
    }

    /// Without `otpauth`, the `issuer` and `account_name` fields do not exist.
    #[test]
    #[cfg(all(feature = "serde", feature = "alloc", not(feature = "otpauth")))]
    fn serde_totp_wire_format_without_otpauth() {
        use serde_test::{Configure, Token, assert_tokens};

        let totp = Builder::new()
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build()
            .unwrap();

        assert_tokens(
            &totp.readable(),
            &[
                Token::Struct {
                    name: "Totp",
                    len: 5,
                },
                Token::Str("algorithm"),
                Token::Str("SHA1"),
                Token::Str("digits"),
                Token::U8(6),
                Token::Str("skew"),
                Token::U16(1),
                Token::Str("step"),
                Token::U64(30),
                Token::Str("secret"),
                Token::Str("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ"),
                Token::StructEnd,
            ],
        );
    }

    /// Data serialized without the `otpauth` feature carries no `issuer` or
    /// `account_name` field. With `otpauth` enabled, such data must still
    /// deserialize, with both fields taking their unset values (`None`, `""`).
    #[test]
    #[cfg(all(feature = "serde", feature = "otpauth"))]
    fn serde_totp_deserializes_data_without_otpauth_fields() {
        use serde_test::{Configure, Token, assert_de_tokens};

        let expected = Builder::new()
            .with_secret("TestSecretSuperSecret".as_bytes())
            .build()
            .unwrap();
        assert_eq!(expected.issuer(), None);
        assert_eq!(expected.account_name(), "");

        assert_de_tokens(
            &expected.readable(),
            &[
                Token::Struct {
                    name: "Totp",
                    len: 5,
                },
                Token::Str("algorithm"),
                Token::Str("SHA1"),
                Token::Str("digits"),
                Token::U8(6),
                Token::Str("skew"),
                Token::U16(1),
                Token::Str("step"),
                Token::U64(30),
                Token::Str("secret"),
                Token::Str("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ"),
                Token::StructEnd,
            ],
        );
    }

    /// A Steam [`Totp`] keeps its `STEAM` algorithm tag and 5 digits through
    /// the serde round-trip.
    #[test]
    #[cfg(all(feature = "serde", feature = "steam", feature = "otpauth"))]
    fn serde_totp_wire_format_steam() {
        use serde_test::{Configure, Token, assert_tokens};

        let totp = Builder::new_steam()
            .with_secret("TestSecretSuperSecret".as_bytes())
            .with_account_name("constantoine@github.com")
            .build()
            .unwrap();

        assert_tokens(
            &totp.readable(),
            &[
                Token::Struct {
                    name: "Totp",
                    len: 7,
                },
                Token::Str("algorithm"),
                Token::Str("STEAM"),
                Token::Str("digits"),
                Token::U8(5),
                Token::Str("skew"),
                Token::U16(1),
                Token::Str("step"),
                Token::U64(30),
                Token::Str("secret"),
                Token::Str("KRSXG5CTMVRXEZLUKN2XAZLSKNSWG4TFOQ"),
                Token::Str("issuer"),
                Token::Some,
                Token::Str("Steam"),
                Token::Str("account_name"),
                Token::Str("constantoine@github.com"),
                Token::StructEnd,
            ],
        );
    }
}