Skip to main content

ch_auth/auth/two_factor/
api.rs

1use base64::Engine;
2use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
3use getrandom::fill;
4use otpauth::TOTP;
5use qrcode::{QrCode, render::svg};
6use std::time::{SystemTime, UNIX_EPOCH};
7use thiserror::Error;
8use zeroize::Zeroizing;
9
10use crate::accounts::{RandomCodeSpec, generate_random_code};
11
12use super::{BACKUP_CODE_COUNT, BACKUP_CODE_LENGTH, TOTP_PERIOD_SECONDS};
13
14const TOTP_SECRET_LENGTH: usize = 20;
15const BACKUP_CODE_ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
16
17/// Error states returned by server-side two-factor helpers.
18#[derive(Debug, Clone, Copy, Error, PartialEq, Eq)]
19pub enum TwoFactorServerError {
20    /// The operating system could not provide cryptographically secure randomness.
21    #[error("secure randomness is unavailable")]
22    Random,
23    /// The supplied TOTP secret was empty.
24    #[error("the TOTP secret is missing")]
25    TotpSecretMissing,
26    /// The supplied Base32 TOTP secret could not be decoded.
27    #[error("the TOTP secret is invalid")]
28    TotpDecode,
29    /// The OTPAUTH URI could not be encoded as a QR code.
30    #[error("the OTPAUTH URI could not be encoded as a QR code")]
31    QrCode,
32    /// The system clock is earlier than the Unix epoch.
33    #[error("the system clock predates the Unix epoch")]
34    SystemTime,
35}
36
37/// Generates a new TOTP secret and OTPAUTH URI for the account identifier.
38pub fn build_totp_secret(
39    issuer: &str,
40    account_identifier: &str,
41) -> Result<(String, String), TwoFactorServerError> {
42    let mut secret_bytes = Zeroizing::new(vec![0u8; TOTP_SECRET_LENGTH]);
43    fill(secret_bytes.as_mut_slice()).map_err(|_| TwoFactorServerError::Random)?;
44
45    let totp = TOTP::from_bytes(&secret_bytes);
46    let secret = totp.base32_secret();
47    let label = format!("{issuer}:{account_identifier}");
48    let otpauth_uri = totp.to_uri(label, issuer.to_string());
49
50    Ok((secret, otpauth_uri))
51}
52
53/// Builds an OTPAUTH URI for an existing Base32 TOTP secret.
54pub fn build_totp_uri_from_secret(
55    secret: &str,
56    issuer: &str,
57    account_identifier: &str,
58) -> Result<String, TwoFactorServerError> {
59    let secret = secret.trim();
60    if secret.is_empty() {
61        return Err(TwoFactorServerError::TotpSecretMissing);
62    }
63
64    let totp = TOTP::from_base32(secret).ok_or(TwoFactorServerError::TotpDecode)?;
65    let label = format!("{issuer}:{account_identifier}");
66    Ok(totp.to_uri(label, issuer.to_string()))
67}
68
69/// Renders QR code artifacts for the provided OTPAUTH URI.
70pub fn render_qr_artifacts(otpauth_uri: &str) -> Result<(String, String), TwoFactorServerError> {
71    let qr_code = QrCode::new(otpauth_uri.as_bytes()).map_err(|_| TwoFactorServerError::QrCode)?;
72
73    let qr_svg = qr_code
74        .render::<svg::Color>()
75        .min_dimensions(256, 256)
76        .dark_color(svg::Color("#0f172a"))
77        .light_color(svg::Color("#ffffff"))
78        .build();
79
80    let qr_png_data_uri = format!(
81        "data:image/svg+xml;base64,{}",
82        BASE64_STANDARD.encode(qr_svg.as_bytes())
83    );
84
85    Ok((qr_svg, qr_png_data_uri))
86}
87
88/// Generates a batch of randomized backup codes.
89pub fn build_backup_codes() -> Result<Vec<String>, TwoFactorServerError> {
90    let mut codes = Vec::with_capacity(BACKUP_CODE_COUNT);
91
92    while codes.len() < BACKUP_CODE_COUNT {
93        let code = random_backup_code()?;
94
95        if codes.iter().any(|existing| existing == &code) {
96            continue;
97        }
98
99        codes.push(code);
100    }
101
102    Ok(codes)
103}
104
105fn random_backup_code() -> Result<String, TwoFactorServerError> {
106    let spec = RandomCodeSpec::new(BACKUP_CODE_LENGTH, BACKUP_CODE_ALPHABET)
107        .expect("the static backup-code format is valid");
108    generate_random_code(spec).map_err(|_| TwoFactorServerError::Random)
109}
110
111/// Returns the matching TOTP timestep at the current system time.
112/// The application must consume this step durably before granting access.
113pub fn verify_totp_step(secret: &str, code: u32) -> Result<Option<u64>, TwoFactorServerError> {
114    let timestamp = SystemTime::now()
115        .duration_since(UNIX_EPOCH)
116        .map_err(|_| TwoFactorServerError::SystemTime)?
117        .as_secs();
118    verify_totp_step_at(secret, code, timestamp)
119}
120
121/// Returns the matching timestep for a supplied timestamp.
122/// Only the current 30-second step is accepted. No drift window is added.
123pub fn verify_totp_step_at(
124    secret: &str,
125    code: u32,
126    timestamp: u64,
127) -> Result<Option<u64>, TwoFactorServerError> {
128    let secret = secret.trim();
129    if secret.is_empty() {
130        return Err(TwoFactorServerError::TotpSecretMissing);
131    }
132    let totp = TOTP::from_base32(secret).ok_or(TwoFactorServerError::TotpDecode)?;
133    Ok(totp
134        .verify(code, TOTP_PERIOD_SECONDS, timestamp)
135        .then_some(timestamp / TOTP_PERIOD_SECONDS))
136}
137
138#[cfg(test)]
139mod tests {
140    use super::{
141        BACKUP_CODE_ALPHABET, BACKUP_CODE_COUNT, BACKUP_CODE_LENGTH, build_backup_codes,
142        build_totp_secret, build_totp_uri_from_secret, render_qr_artifacts,
143    };
144    use otpauth::TOTP;
145
146    #[test]
147    fn verified_step_uses_the_same_clock_sample_and_rejects_adjacent_windows() {
148        let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
149        assert_eq!(super::verify_totp_step_at(secret, 287082, 59), Ok(Some(1)));
150        assert_eq!(super::verify_totp_step_at(secret, 287082, 60), Ok(None));
151        assert_eq!(super::verify_totp_step_at(secret, 287082, 29), Ok(None));
152        assert_eq!(
153            super::verify_totp_step_at("", 287082, 59),
154            Err(super::TwoFactorServerError::TotpSecretMissing)
155        );
156        assert_eq!(
157            super::verify_totp_step_at("invalid!", 287082, 59),
158            Err(super::TwoFactorServerError::TotpDecode)
159        );
160    }
161
162    #[test]
163    fn backup_codes_are_unique_and_well_formed() {
164        let codes = build_backup_codes().expect("backup codes should generate");
165        assert_eq!(codes.len(), BACKUP_CODE_COUNT);
166        for code in &codes {
167            assert_eq!(code.len(), BACKUP_CODE_LENGTH);
168            assert!(
169                code.bytes()
170                    .all(|byte| BACKUP_CODE_ALPHABET.as_bytes().contains(&byte))
171            );
172        }
173    }
174
175    #[test]
176    fn rejection_sampling_maps_every_symbol_equally() {
177        let acceptance_bound = 256 - (256 % BACKUP_CODE_ALPHABET.len());
178        let mut counts = vec![0_usize; BACKUP_CODE_ALPHABET.len()];
179        for byte in 0_u8..=u8::MAX {
180            if usize::from(byte) < acceptance_bound {
181                counts[usize::from(byte) % BACKUP_CODE_ALPHABET.len()] += 1;
182            }
183        }
184        assert!(counts.windows(2).all(|window| window[0] == window[1]));
185    }
186
187    #[test]
188    fn totp_secret_and_uri_include_issuer_and_identifier() {
189        let (secret, uri) =
190            build_totp_secret("TestIssuer", "test@example.com").expect("secret should generate");
191        assert!(!secret.is_empty());
192        assert!(uri.contains("TestIssuer"));
193        assert!(uri.contains("test@example.com"));
194    }
195
196    #[test]
197    fn totp_uri_from_secret_includes_issuer() {
198        let totp = TOTP::from_bytes(&[0u8; 20]);
199        let secret = totp.base32_secret();
200        let uri = build_totp_uri_from_secret(&secret, "TestIssuer", "test@example.com")
201            .expect("uri should build");
202        assert!(uri.contains("TestIssuer"));
203        assert!(uri.contains("test@example.com"));
204    }
205
206    #[test]
207    fn qr_artifacts_are_rendered() {
208        let uri = "otpauth://totp/TestIssuer:test@example.com?secret=ABC&issuer=TestIssuer";
209        let (svg, png) = render_qr_artifacts(uri).expect("qr should render");
210        assert!(!svg.is_empty());
211        assert!(png.starts_with("data:image/svg+xml;base64,"));
212    }
213}