Skip to main content

bitwarden_vault/
totp.rs

1use std::{
2    collections::HashMap,
3    fmt::{self},
4    str::FromStr,
5};
6
7use bitwarden_crypto::CryptoError;
8use bitwarden_crypto_primitives::hmac::{HashAlg, hmac};
9use bitwarden_error::bitwarden_error;
10use chrono::{DateTime, Utc};
11use data_encoding::BASE32_NOPAD;
12use percent_encoding::{NON_ALPHANUMERIC, percent_decode_str, percent_encode};
13use reqwest::Url;
14use serde::{Deserialize, Serialize};
15use thiserror::Error;
16
17use crate::CipherListView;
18
19const BASE32_CHARS: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
20const STEAM_CHARS: &str = "23456789BCDFGHJKMNPQRTVWXY";
21
22const DEFAULT_ALGORITHM: TotpAlgorithm = TotpAlgorithm::Sha1;
23const DEFAULT_DIGITS: u32 = 6;
24const DEFAULT_PERIOD: u32 = 30;
25
26#[allow(missing_docs)]
27#[bitwarden_error(flat)]
28#[derive(Debug, Error)]
29pub enum TotpError {
30    #[error("Invalid otpauth")]
31    InvalidOtpauth,
32    #[error("Missing secret")]
33    MissingSecret,
34
35    #[error(transparent)]
36    Crypto(#[from] CryptoError),
37}
38
39#[allow(missing_docs)]
40#[derive(Serialize, Deserialize, Debug)]
41#[serde(rename_all = "camelCase", deny_unknown_fields)]
42#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
43#[bitwarden_ffi::wasm_record]
44pub struct TotpResponse {
45    /// Generated TOTP code
46    pub code: String,
47    /// Time period
48    pub period: u32,
49}
50
51/// Generate a OATH or RFC 6238 TOTP code from a provided key.
52///
53/// <https://datatracker.ietf.org/doc/html/rfc6238>
54///
55/// Key can be either:
56/// - A base32 encoded string
57/// - OTP Auth URI
58/// - Steam URI
59///
60/// Supports providing an optional time, and defaults to current system time if none is provided.
61///
62/// Arguments:
63/// - `key` - The key to generate the TOTP code from
64/// - `time` - The time in UTC to generate the TOTP code for, defaults to current system time
65pub fn generate_totp(key: String, time: Option<DateTime<Utc>>) -> Result<TotpResponse, TotpError> {
66    let params: Totp = key.parse()?;
67
68    let time = time.unwrap_or_else(Utc::now);
69
70    let otp = params.derive_otp(time.timestamp());
71
72    Ok(TotpResponse {
73        code: otp,
74        period: params.period,
75    })
76}
77
78/// Generate a OATH or RFC 6238 TOTP code from a provided CipherListView.
79///
80/// See [generate_totp] for more information.
81pub fn generate_totp_cipher_view(
82    view: CipherListView,
83    time: Option<DateTime<Utc>>,
84) -> Result<TotpResponse, TotpError> {
85    let key = view
86        .get_totp_key()?
87        .filter(|s| !s.is_empty())
88        .ok_or(TotpError::MissingSecret)?;
89
90    generate_totp(key, time)
91}
92
93#[allow(missing_docs)]
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95pub enum TotpAlgorithm {
96    Sha1,
97    Sha256,
98    Sha512,
99    Steam,
100}
101
102impl TotpAlgorithm {
103    // Derive the HMAC hash for the given algorithm
104    fn derive_hash(&self, key: &[u8], time: &[u8]) -> Vec<u8> {
105        // Steam codes are HMAC-SHA1 with a custom alphabet.
106        let alg = match self {
107            TotpAlgorithm::Sha1 | TotpAlgorithm::Steam => HashAlg::Sha1,
108            TotpAlgorithm::Sha256 => HashAlg::Sha256,
109            TotpAlgorithm::Sha512 => HashAlg::Sha512,
110        };
111        hmac(alg, key, time)
112    }
113}
114
115impl fmt::Display for TotpAlgorithm {
116    /// Display the algorithm as a string
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(match self {
119            TotpAlgorithm::Sha1 => "SHA1",
120            TotpAlgorithm::Sha256 => "SHA256",
121            TotpAlgorithm::Sha512 => "SHA512",
122            TotpAlgorithm::Steam => "SHA1",
123        })
124    }
125}
126
127/// TOTP representation broken down into its components.
128///
129/// Should generally be considered internal to the bitwarden-vault crate. Consumers should use one
130/// of the generate functions if they want to generate a TOTP code. Credential Exchange requires
131/// access to the individual components.
132#[allow(missing_docs)]
133#[derive(Debug)]
134pub struct Totp {
135    pub account: Option<String>,
136    pub algorithm: TotpAlgorithm,
137    pub digits: u32,
138    pub issuer: Option<String>,
139    pub period: u32,
140    pub secret: Vec<u8>,
141}
142
143impl Totp {
144    fn derive_otp(&self, time: i64) -> String {
145        let time = time / self.period as i64;
146
147        let hash = self
148            .algorithm
149            .derive_hash(&self.secret, time.to_be_bytes().as_ref());
150        let binary = derive_binary(hash);
151
152        if let TotpAlgorithm::Steam = self.algorithm {
153            derive_steam_otp(binary, self.digits)
154        } else {
155            let otp = binary % 10_u32.pow(self.digits);
156            format!("{1:00$}", self.digits as usize, otp)
157        }
158    }
159}
160
161impl FromStr for Totp {
162    type Err = TotpError;
163
164    /// Parses the provided key and returns the corresponding `Totp`.
165    ///
166    /// Key can be either:
167    /// - A base32 encoded string
168    /// - OTP Auth URI
169    /// - Steam URI
170    fn from_str(key: &str) -> Result<Self, Self::Err> {
171        let key = key.to_lowercase();
172
173        let params = if key.starts_with("otpauth://") {
174            let url = Url::parse(&key).map_err(|_| TotpError::InvalidOtpauth)?;
175            let decoded_path = percent_decode_str(url.path()).decode_utf8_lossy();
176            let label = decoded_path.strip_prefix("/");
177            let (issuer, account) = match label.and_then(|v| v.split_once(':')) {
178                Some((issuer, account)) => (Some(issuer.trim()), Some(account.trim())),
179                None => (None, label),
180            };
181
182            let parts: HashMap<_, _> = url.query_pairs().collect();
183
184            Totp {
185                account: account.map(|s| s.to_string()),
186                algorithm: parts
187                    .get("algorithm")
188                    .and_then(|v| match v.as_ref() {
189                        "sha1" => Some(TotpAlgorithm::Sha1),
190                        "sha256" => Some(TotpAlgorithm::Sha256),
191                        "sha512" => Some(TotpAlgorithm::Sha512),
192                        _ => None,
193                    })
194                    .unwrap_or(DEFAULT_ALGORITHM),
195                digits: parts
196                    .get("digits")
197                    .and_then(|v| v.parse().ok())
198                    .map(|v: u32| v.clamp(0, 10))
199                    .unwrap_or(DEFAULT_DIGITS),
200                issuer: parts
201                    .get("issuer")
202                    .map(|v| v.to_string())
203                    .or(issuer.map(|s| s.to_string())),
204                period: parts
205                    .get("period")
206                    .and_then(|v| v.parse().ok())
207                    .map(|v: u32| v.max(1))
208                    .unwrap_or(DEFAULT_PERIOD),
209                secret: decode_b32(
210                    &parts
211                        .get("secret")
212                        .map(|v| v.to_string())
213                        .ok_or(TotpError::MissingSecret)?,
214                ),
215            }
216        } else if let Some(secret) = key.strip_prefix("steam://") {
217            Totp {
218                account: None,
219                algorithm: TotpAlgorithm::Steam,
220                digits: 5,
221                issuer: None,
222                period: DEFAULT_PERIOD,
223                secret: decode_b32(secret),
224            }
225        } else {
226            Totp {
227                account: None,
228                algorithm: DEFAULT_ALGORITHM,
229                digits: DEFAULT_DIGITS,
230                issuer: None,
231                period: DEFAULT_PERIOD,
232                secret: decode_b32(&key),
233            }
234        };
235
236        Ok(params)
237    }
238}
239
240impl fmt::Display for Totp {
241    /// Formats the TOTP as an OTP Auth URI.
242    ///
243    /// Returns a steam::// URI if the algorithm is Steam.
244    /// Otherwise returns an otpauth:// URI according to the Key Uri Format Specification:
245    /// <https://docs.yubico.com/yesdk/users-manual/application-oath/uri-string-format.html>
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        let secret_b32 = BASE32_NOPAD.encode(&self.secret);
248
249        if let TotpAlgorithm::Steam = self.algorithm {
250            return write!(f, "steam://{secret_b32}");
251        }
252
253        let mut url = Url::parse("otpauth://totp").map_err(|_| fmt::Error)?;
254
255        // Strip out colons from issuer and account
256        let issuer = self.issuer.as_ref().map(|issuer| issuer.replace(":", ""));
257        let account = self
258            .account
259            .as_ref()
260            .map(|account| account.replace(":", ""));
261
262        let encoded_issuer = issuer
263            .as_ref()
264            .map(|issuer| percent_encode(issuer.as_bytes(), NON_ALPHANUMERIC));
265
266        let encoded_account = account
267            .as_ref()
268            .map(|account| percent_encode(account.as_bytes(), NON_ALPHANUMERIC));
269
270        let label = match (&encoded_issuer, &encoded_account) {
271            (Some(issuer), Some(account)) => format!("{issuer}:{account}"),
272            (None, Some(account)) => account.to_string(),
273            _ => String::new(),
274        };
275
276        url.set_path(&label);
277
278        let mut query_params = Vec::new();
279        query_params.push(format!("secret={secret_b32}"));
280
281        if let Some(issuer) = &encoded_issuer {
282            query_params.push(format!("issuer={issuer}"));
283        }
284
285        if self.period != DEFAULT_PERIOD {
286            query_params.push(format!("period={}", self.period));
287        }
288
289        if self.algorithm != DEFAULT_ALGORITHM {
290            query_params.push(format!("algorithm={}", self.algorithm));
291        }
292
293        if self.digits != DEFAULT_DIGITS {
294            query_params.push(format!("digits={}", self.digits));
295        }
296
297        url.set_query(Some(&query_params.join("&")));
298        url.fmt(f)
299    }
300}
301
302/// Derive the Steam OTP from the hash with the given number of digits.
303fn derive_steam_otp(binary: u32, digits: u32) -> String {
304    let mut full_code = binary & 0x7fffffff;
305
306    (0..digits)
307        .map(|_| {
308            let index = full_code as usize % STEAM_CHARS.len();
309            let char = STEAM_CHARS
310                .chars()
311                .nth(index)
312                .expect("Should always be within range");
313            full_code /= STEAM_CHARS.len() as u32;
314            char
315        })
316        .collect()
317}
318
319/// Derive the OTP from the hash with the given number of digits.
320fn derive_binary(hash: Vec<u8>) -> u32 {
321    let offset = (hash.last().unwrap_or(&0) & 15) as usize;
322
323    (((hash[offset] & 127) as u32) << 24)
324        | ((hash[offset + 1] as u32) << 16)
325        | ((hash[offset + 2] as u32) << 8)
326        | (hash[offset + 3] as u32)
327}
328
329/// This code is migrated from our javascript implementation and is not technically a correct base32
330/// decoder since we filter out various characters, and use exact chunking.
331fn decode_b32(s: &str) -> Vec<u8> {
332    let s = s.to_uppercase();
333
334    let mut bits = String::new();
335    for c in s.chars() {
336        if let Some(i) = BASE32_CHARS.find(c) {
337            bits.push_str(&format!("{i:05b}"));
338        }
339    }
340    let mut bytes = Vec::new();
341
342    for chunk in bits.as_bytes().chunks_exact(8) {
343        let byte_str = std::str::from_utf8(chunk).expect("The value is a valid string");
344        let byte = u8::from_str_radix(byte_str, 2).expect("The value is a valid binary string");
345        bytes.push(byte);
346    }
347
348    bytes
349}
350
351#[cfg(test)]
352mod tests {
353    use chrono::Utc;
354
355    use super::*;
356    use crate::{
357        CipherRepromptType,
358        cipher::cipher::{CipherListViewType, CopyableCipherFields},
359        login::LoginListView,
360    };
361
362    #[test]
363    fn test_decode_b32() {
364        let res = decode_b32("WQIQ25BRKZYCJVYP");
365        assert_eq!(res, vec![180, 17, 13, 116, 49, 86, 112, 36, 215, 15]);
366
367        let res = decode_b32("ABCD123");
368        assert_eq!(res, vec![0, 68, 61]);
369    }
370
371    #[test]
372    fn test_generate_totp() {
373        let cases = vec![
374            ("WQIQ25BRKZYCJVYP", "194506"), // valid base32
375            ("wqiq25brkzycjvyp", "194506"), // lowercase
376            ("PIUDISEQYA", "829846"),       // non padded
377            ("PIUDISEQYA======", "829846"), // padded
378            ("PIUD1IS!EQYA=", "829846"),    // sanitized
379            // Steam
380            ("steam://HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", "7W6CJ"),
381            ("StEam://HXDMVJECJJWSRB3HWIZR4IFUGFTMXBOZ", "7W6CJ"),
382            ("steam://ABCD123", "N26DF"),
383            // Various weird lengths
384            ("ddfdf", "932653"),
385            ("HJSGFJHDFDJDJKSDFD", "000034"),
386            ("xvdsfasdfasdasdghsgsdfg", "403786"),
387            ("KAKFJWOSFJ12NWL", "093430"),
388        ];
389
390        let time = Some(
391            DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
392                .unwrap()
393                .with_timezone(&Utc),
394        );
395
396        for (key, expected_code) in cases {
397            let response = generate_totp(key.to_string(), time).unwrap();
398
399            assert_eq!(response.code, expected_code, "wrong code for key: {key}");
400            assert_eq!(response.period, 30);
401        }
402    }
403
404    #[test]
405    fn test_generate_otpauth() {
406        let key = "otpauth://totp/test-account?secret=WQIQ25BRKZYCJVYP".to_string();
407        let time = Some(
408            DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
409                .unwrap()
410                .with_timezone(&Utc),
411        );
412        let response = generate_totp(key, time).unwrap();
413
414        assert_eq!(response.code, "194506".to_string());
415        assert_eq!(response.period, 30);
416    }
417
418    #[test]
419    fn test_generate_otpauth_no_label() {
420        let key = "otpauth://totp/?secret=WQIQ25BRKZYCJVYP";
421        let totp = Totp::from_str(key).unwrap();
422
423        assert_eq!(totp.account, Some("".to_string()));
424        assert_eq!(totp.issuer, None);
425    }
426
427    #[test]
428    fn test_generate_otpauth_uppercase() {
429        let key = "OTPauth://totp/test-account?secret=WQIQ25BRKZYCJVYP".to_string();
430        let time = Some(
431            DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
432                .unwrap()
433                .with_timezone(&Utc),
434        );
435        let response = generate_totp(key, time).unwrap();
436
437        assert_eq!(response.code, "194506".to_string());
438        assert_eq!(response.period, 30);
439    }
440
441    #[test]
442    fn test_generate_otpauth_period() {
443        let key = "otpauth://totp/test-account?secret=WQIQ25BRKZYCJVYP&period=60".to_string();
444        let time = Some(
445            DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
446                .unwrap()
447                .with_timezone(&Utc),
448        );
449        let response = generate_totp(key, time).unwrap();
450
451        assert_eq!(response.code, "730364".to_string());
452        assert_eq!(response.period, 60);
453    }
454
455    #[test]
456    fn test_generate_otpauth_algorithm_sha256() {
457        let key =
458            "otpauth://totp/test-account?secret=WQIQ25BRKZYCJVYP&algorithm=SHA256".to_string();
459        let time = Some(
460            DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
461                .unwrap()
462                .with_timezone(&Utc),
463        );
464        let response = generate_totp(key, time).unwrap();
465
466        assert_eq!(response.code, "842615".to_string());
467        assert_eq!(response.period, 30);
468    }
469
470    #[test]
471    fn test_parse_totp_label_no_issuer() {
472        // If there is only one value in the label, it is the account
473        let key = "otpauth://totp/[email protected]?secret=WQIQ25BRKZYCJVYP";
474        let totp = Totp::from_str(key).unwrap();
475
476        assert_eq!(totp.account, Some("[email protected]".to_string()));
477        assert_eq!(totp.issuer, None);
478    }
479
480    #[test]
481    fn test_parse_totp_label_with_issuer() {
482        // If there are two values in the label, the first is the issuer, the second is the account
483        let key = "otpauth://totp/test-issuer:[email protected]?secret=WQIQ25BRKZYCJVYP";
484        let totp = Totp::from_str(key).unwrap();
485
486        assert_eq!(totp.account, Some("[email protected]".to_string()));
487        assert_eq!(totp.issuer, Some("test-issuer".to_string()));
488    }
489
490    #[test]
491    fn test_parse_totp_label_two_issuers() {
492        // If the label has an issuer and there is an issuer parameter, the parameter is chosen as
493        // the issuer
494        let key = "otpauth://totp/test-issuer:[email protected]?secret=WQIQ25BRKZYCJVYP&issuer=other-test-issuer";
495        let totp = Totp::from_str(key).unwrap();
496
497        assert_eq!(totp.account, Some("[email protected]".to_string()));
498        assert_eq!(totp.issuer, Some("other-test-issuer".to_string()));
499    }
500
501    #[test]
502    fn test_parse_totp_label_encoded_colon() {
503        // A url-encoded colon is a valid separator
504        let key = "otpauth://totp/test-issuer%[email protected]?secret=WQIQ25BRKZYCJVYP&issuer=test-issuer";
505        let totp = Totp::from_str(key).unwrap();
506
507        assert_eq!(totp.account, Some("[email protected]".to_string()));
508        assert_eq!(totp.issuer, Some("test-issuer".to_string()));
509    }
510
511    #[test]
512    fn test_parse_totp_label_encoded_characters() {
513        // The account and issuer can both be URL-encoded
514        let key = "otpauth://totp/test%20issuer:test-account%40example%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=test%20issuer";
515        let totp = Totp::from_str(key).unwrap();
516
517        assert_eq!(totp.account, Some("[email protected]".to_string()));
518        assert_eq!(totp.issuer, Some("test issuer".to_string()));
519    }
520
521    #[test]
522    fn test_parse_totp_label_account_spaces() {
523        // The account can have spaces before it
524        let key = "otpauth://totp/test-issuer:   [email protected]?secret=WQIQ25BRKZYCJVYP&issuer=test-issuer";
525        let totp = Totp::from_str(key).unwrap();
526
527        assert_eq!(totp.account, Some("[email protected]".to_string()));
528        assert_eq!(totp.issuer, Some("test-issuer".to_string()));
529    }
530
531    #[test]
532    fn test_totp_to_string_strips_colons() {
533        let totp = Totp {
534            account: Some("test:[email protected]".to_string()),
535            algorithm: DEFAULT_ALGORITHM,
536            digits: DEFAULT_DIGITS,
537            issuer: Some("Acme:Inc".to_string()),
538            period: DEFAULT_PERIOD,
539            secret: decode_b32("WQIQ25BRKZYCJVYP"),
540        };
541
542        let uri = totp.to_string();
543
544        // Verify colons are stripped from both issuer and account in the URI
545        assert!(!uri.contains("Acme:Inc"));
546        assert!(!uri.contains("test:account"));
547
548        // Verify that the stripped colons are replaced
549        assert!(uri.contains("AcmeInc"));
550        assert!(uri.contains("testaccount"));
551
552        let parsed = Totp::from_str(&uri).unwrap();
553        // Verify parsed values have colon removed
554        assert_eq!(parsed.issuer.unwrap(), "acmeinc");
555        assert_eq!(parsed.account.unwrap(), "[email protected]");
556    }
557
558    #[test]
559    fn test_totp_to_string_with_defaults() {
560        let totp = Totp {
561            account: Some("[email protected]".to_string()),
562            algorithm: DEFAULT_ALGORITHM,
563            digits: DEFAULT_DIGITS,
564            issuer: Some("Example".to_string()),
565            period: DEFAULT_PERIOD,
566            secret: decode_b32("WQIQ25BRKZYCJVYP"),
567        };
568
569        assert_eq!(
570            totp.to_string(),
571            "otpauth://totp/Example:test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=Example"
572        );
573    }
574
575    #[test]
576    fn test_totp_to_string_with_custom_period() {
577        let totp = Totp {
578            account: Some("[email protected]".to_string()),
579            algorithm: DEFAULT_ALGORITHM,
580            digits: DEFAULT_DIGITS,
581            issuer: Some("Example".to_string()),
582            period: 60,
583            secret: decode_b32("WQIQ25BRKZYCJVYP"),
584        };
585
586        assert_eq!(
587            totp.to_string(),
588            "otpauth://totp/Example:test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=Example&period=60"
589        );
590    }
591
592    #[test]
593    fn test_totp_to_string_sha256() {
594        let totp = Totp {
595            account: Some("[email protected]".to_string()),
596            algorithm: TotpAlgorithm::Sha256,
597            digits: DEFAULT_DIGITS,
598            issuer: Some("Example".to_string()),
599            period: DEFAULT_PERIOD,
600            secret: decode_b32("WQIQ25BRKZYCJVYP"),
601        };
602
603        assert_eq!(
604            totp.to_string(),
605            "otpauth://totp/Example:test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=Example&algorithm=SHA256"
606        );
607    }
608
609    #[test]
610    fn test_totp_to_string_encodes_spaces_in_issuer() {
611        let totp = Totp {
612            account: Some("[email protected]".to_string()),
613            algorithm: DEFAULT_ALGORITHM,
614            digits: DEFAULT_DIGITS,
615            issuer: Some("Acme Inc".to_string()),
616            period: DEFAULT_PERIOD,
617            secret: decode_b32("WQIQ25BRKZYCJVYP"),
618        };
619
620        assert_eq!(
621            totp.to_string(),
622            "otpauth://totp/Acme%20Inc:test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=Acme%20Inc"
623        );
624    }
625
626    #[test]
627    fn test_totp_to_string_encodes_special_characters_in_issuer() {
628        let totp = Totp {
629            account: Some("[email protected]".to_string()),
630            algorithm: DEFAULT_ALGORITHM,
631            digits: DEFAULT_DIGITS,
632            issuer: Some("Acme & Inc".to_string()),
633            period: DEFAULT_PERIOD,
634            secret: decode_b32("WQIQ25BRKZYCJVYP"),
635        };
636
637        assert_eq!(
638            totp.to_string(),
639            "otpauth://totp/Acme%20%26%20Inc:test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP&issuer=Acme%20%26%20Inc"
640        );
641    }
642
643    #[test]
644    fn test_totp_to_string_no_issuer() {
645        let totp = Totp {
646            account: Some("[email protected]".to_string()),
647            algorithm: DEFAULT_ALGORITHM,
648            digits: DEFAULT_DIGITS,
649            issuer: None,
650            period: DEFAULT_PERIOD,
651            secret: decode_b32("WQIQ25BRKZYCJVYP"),
652        };
653
654        assert_eq!(
655            totp.to_string(),
656            "otpauth://totp/test%40bitwarden%2Ecom?secret=WQIQ25BRKZYCJVYP"
657        )
658    }
659
660    #[test]
661    fn test_totp_to_string_parse_roundtrip_with_special_chars() {
662        let original = Totp {
663            account: Some("[email protected]".to_string()),
664            algorithm: DEFAULT_ALGORITHM,
665            digits: DEFAULT_DIGITS,
666            issuer: Some("Acme & Inc".to_string()),
667            period: DEFAULT_PERIOD,
668            secret: decode_b32("WQIQ25BRKZYCJVYP"),
669        };
670
671        let uri = original.to_string();
672        let parsed = Totp::from_str(&uri).unwrap();
673
674        assert!(
675            parsed
676                .account
677                .unwrap()
678                .eq_ignore_ascii_case(&original.account.unwrap())
679        );
680        assert!(
681            parsed
682                .issuer
683                .unwrap()
684                .eq_ignore_ascii_case(&original.issuer.unwrap())
685        );
686        assert_eq!(parsed.algorithm, original.algorithm);
687        assert_eq!(parsed.digits, original.digits);
688        assert_eq!(parsed.period, original.period);
689        assert_eq!(parsed.secret, original.secret);
690    }
691
692    #[test]
693    fn test_display_steam() {
694        let totp = Totp {
695            account: None,
696            algorithm: TotpAlgorithm::Steam,
697            digits: 5,
698            issuer: None,
699            period: DEFAULT_PERIOD,
700            secret: vec![1, 2, 3, 4],
701        };
702        let secret_b32 = BASE32_NOPAD.encode(&totp.secret);
703        assert_eq!(totp.to_string(), format!("steam://{secret_b32}"));
704    }
705
706    #[test]
707    fn test_generate_totp_cipher_view() {
708        let view = CipherListView {
709            partial: false,
710            id: Some("090c19ea-a61a-4df6-8963-262b97bc6266".parse().unwrap()),
711            organization_id: None,
712            folder_id: None,
713            collection_ids: vec![],
714            name: "My test login".to_string(),
715            subtitle: "test_username".to_string(),
716            r#type: CipherListViewType::Login(LoginListView {
717                fido2_credentials: None,
718                has_fido2: true,
719                username: None,
720                totp: Some("DKWOW4PCP3MYFWLN53BLYAMYQEQJU4MJ".to_string()),
721                uris: None,
722            }),
723            favorite: false,
724            reprompt: CipherRepromptType::None,
725            organization_use_totp: true,
726            edit: true,
727            permissions: None,
728            view_password: true,
729            attachments: 0,
730            has_old_attachments: false,
731            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
732            deleted_date: None,
733            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
734            copyable_fields: vec![CopyableCipherFields::LoginTotp],
735            local_data: None,
736            archived_date: None,
737            #[cfg(feature = "wasm")]
738            notes: None,
739            #[cfg(feature = "wasm")]
740            fields: None,
741            #[cfg(feature = "wasm")]
742            attachment_names: None,
743        };
744
745        let time = DateTime::parse_from_rfc3339("2023-01-01T00:00:00.000Z")
746            .unwrap()
747            .with_timezone(&Utc);
748
749        let response = generate_totp_cipher_view(view, Some(time)).unwrap();
750        assert_eq!(response.code, "559388".to_string());
751        assert_eq!(response.period, 30);
752    }
753}