Skip to main content

auth_framework/api/
mfa.rs

1//! Multi-Factor Authentication API Endpoints
2//!
3//! Handles TOTP setup, verification, backup codes, and MFA management.
4//!
5//! ## Storage keys
6//! - `mfa_pending_secret:{user_id}` — base32 TOTP secret, TTL 10 min (before verification)
7//! - `mfa_pending_backup_codes:{user_id}` — JSON array of hex-encoded SHA-256 hashes, TTL 10 min
8//! - `mfa_secret:{user_id}` — active base32 TOTP secret (no TTL)
9//! - `mfa_backup_codes:{user_id}` — JSON array of hex-encoded SHA-256 hashes (no TTL)
10//! - `mfa_enabled:{user_id}` — b"true" when MFA is active (no TTL)
11
12use crate::api::{ApiResponse, ApiState, extract_bearer_token, validate_api_token};
13use axum::{Json, extract::State, http::HeaderMap};
14use base32::Alphabet;
15use rand::Rng as _;
16use serde::{Deserialize, Serialize};
17use sha2::{Digest as _, Sha256};
18use subtle::ConstantTimeEq as _;
19use zeroize::Zeroizing;
20
21/// Response returned after initiating MFA setup.
22///
23/// The client must render the `qr_code` (or display `secret`) to the user and
24/// prompt for a TOTP code to complete enrollment via the verify endpoint.
25#[derive(Debug, Serialize)]
26pub struct MfaSetupResponse {
27    /// `otpauth://` URI suitable for a QR code.
28    pub qr_code: String,
29    /// Base32-encoded TOTP shared secret (for manual entry).
30    pub secret: Zeroizing<String>,
31    /// One-time recovery codes — store securely; shown only once.
32    pub backup_codes: Vec<String>,
33}
34
35/// Request payload for the TOTP verification step.
36#[derive(Debug, Deserialize)]
37pub struct MfaVerifyRequest {
38    /// Six-digit TOTP code from the authenticator app.
39    pub totp_code: String,
40}
41
42/// Request payload to disable MFA (requires proof of identity).
43#[derive(Debug, Deserialize)]
44pub struct MfaDisableRequest {
45    /// Account password for re-authentication.
46    pub password: String,
47    /// A valid TOTP code confirming the user still controls the authenticator.
48    pub totp_code: String,
49}
50
51/// Current MFA enrollment status for the authenticated user.
52#[derive(Debug, Serialize)]
53pub struct MfaStatusResponse {
54    /// `true` when MFA is fully enrolled and enforced.
55    pub enabled: bool,
56    /// Active MFA methods (e.g. `["totp"]`).
57    pub methods: Vec<String>,
58    /// Number of unused one-time backup codes remaining.
59    pub backup_codes_remaining: u32,
60}
61
62// ---------------------------------------------------------------------------
63// Internal helpers
64// ---------------------------------------------------------------------------
65
66/// Generate a cryptographically-secure TOTP secret and ten single-use backup
67/// codes.  Returns `(plaintext_codes, sha256_hex_hashes)`.
68fn generate_backup_codes() -> (Vec<String>, Vec<String>) {
69    const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // Crockford-like, unambiguous
70    let mut plaintext = Vec::with_capacity(10);
71    let mut hashed = Vec::with_capacity(10);
72    let mut buf = [0u8; 8];
73    for _ in 0..10 {
74        rand::rng().fill_bytes(&mut buf);
75        let code: String = buf
76            .iter()
77            .map(|b| ALPHABET[(*b as usize) % ALPHABET.len()] as char)
78            .collect();
79        let hash = hex::encode(Sha256::digest(code.as_bytes()));
80        plaintext.push(code);
81        hashed.push(hash);
82    }
83    (plaintext, hashed)
84}
85
86/// Hash a backup code for constant-time comparison.
87fn hash_backup_code(code: &str) -> String {
88    hex::encode(Sha256::digest(code.as_bytes()))
89}
90
91/// Verify a 6-digit TOTP code against a raw secret with ±1 window tolerance.
92/// Always checks all three time windows regardless of whether an earlier window
93/// matched, preventing timing side-channels that reveal which window matched.
94fn verify_totp_code(provided: &str, secret_bytes: &[u8], now: u64) -> bool {
95    use subtle::ConstantTimeEq as _;
96    use totp_lite::{Sha1, totp_custom};
97    const STEP: u64 = 30;
98    const DIGITS: u32 = 6;
99
100    // Allow the previous window, the current window, and the next window to
101    // account for clock skew between the server and the user's device.
102    // Do NOT return early on a match so all three comparisons always execute.
103    let mut matched = false;
104    for offset in [0u64, STEP, STEP.wrapping_neg()] {
105        let t = now.wrapping_add(offset);
106        let expected = totp_custom::<Sha1>(STEP, DIGITS, secret_bytes, t);
107        // Constant-time byte-level comparison prevents timing side-channels.
108        let eq: bool = expected.as_bytes().ct_eq(provided.as_bytes()).into();
109        matched |= eq;
110    }
111    matched
112}
113
114// ---------------------------------------------------------------------------
115// Endpoint handlers
116// ---------------------------------------------------------------------------
117
118/// `POST /mfa/setup` — initiate MFA enrollment.
119///
120/// Generates a new TOTP secret and ten backup codes, stores them as *pending*
121/// (TTL 10 min), and returns:
122/// - `secret` – base32-encoded secret for manual entry into an authenticator
123/// - `qr_code` – `otpauth://` URI that can be converted to a QR code
124/// - `backup_codes` – **shown once**; user must save these before calling `/mfa/verify`
125pub async fn setup_mfa(
126    State(state): State<ApiState>,
127    headers: HeaderMap,
128) -> ApiResponse<MfaSetupResponse> {
129    match extract_bearer_token(&headers) {
130        Some(token) => {
131            match validate_api_token(&state.auth_framework, &token).await {
132                Ok(auth_token) => {
133                    // Generate a 20-byte (160-bit) random TOTP secret.
134                    let mut secret_bytes = [0u8; 20];
135                    rand::rng().fill_bytes(&mut secret_bytes);
136                    let secret_b32 =
137                        base32::encode(Alphabet::Rfc4648 { padding: false }, &secret_bytes);
138
139                    // Generate backup codes (shown once, hashes stored).
140                    let (plaintext_codes, hashed_codes) = generate_backup_codes();
141
142                    // Store both as pending with a 10-minute TTL so they are
143                    // discarded if the user never completes verification.
144                    let storage = state.auth_framework.storage();
145                    let pending_secret_key = format!("mfa_pending_secret:{}", auth_token.user_id);
146                    let pending_backup_key =
147                        format!("mfa_pending_backup_codes:{}", auth_token.user_id);
148                    let ttl = std::time::Duration::from_secs(600);
149
150                    if let Err(e) = storage
151                        .store_kv(&pending_secret_key, secret_b32.as_bytes(), Some(ttl))
152                        .await
153                    {
154                        tracing::error!("Failed to store pending MFA secret: {}", e);
155                        return ApiResponse::error_typed(
156                            "MFA_ERROR",
157                            "Failed to initiate MFA setup",
158                        );
159                    }
160
161                    let hashed_json =
162                        serde_json::to_string(&hashed_codes).unwrap_or_else(|_| "[]".to_string());
163                    let _ = storage
164                        .store_kv(&pending_backup_key, hashed_json.as_bytes(), Some(ttl))
165                        .await;
166
167                    // Build the standard otpauth:// URI understood by all
168                    // major authenticator apps (Google Authenticator, Authy, …).
169                    let issuer = "AuthFramework";
170                    let account = urlencoding::encode(&auth_token.user_id);
171                    let qr_code = format!(
172                        "otpauth://totp/{issuer}:{account}?secret={secret_b32}&issuer={issuer}&digits=6&period=30"
173                    );
174
175                    tracing::info!("MFA setup initiated for user: {}", auth_token.user_id);
176                    ApiResponse::success(MfaSetupResponse {
177                        qr_code,
178                        secret: secret_b32.into(),
179                        backup_codes: plaintext_codes,
180                    })
181                }
182                Err(_e) => ApiResponse::error_typed("MFA_ERROR", "MFA setup failed"),
183            }
184        }
185        None => ApiResponse::<MfaSetupResponse>::unauthorized_typed(),
186    }
187}
188
189/// `POST /mfa/verify` — complete MFA enrollment.
190///
191/// Verifies a TOTP code against the *pending* secret created by `/mfa/setup`.
192/// On success the pending secret is promoted to the active secret, backup-code
193/// hashes are committed to permanent storage, and the user's MFA-enabled flag
194/// is set.
195pub async fn verify_mfa(
196    State(state): State<ApiState>,
197    headers: HeaderMap,
198    Json(req): Json<MfaVerifyRequest>,
199) -> ApiResponse<()> {
200    if req.totp_code.is_empty() {
201        return ApiResponse::validation_error("TOTP code is required");
202    }
203
204    if req.totp_code.len() != 6 || !req.totp_code.chars().all(|c| c.is_ascii_digit()) {
205        return ApiResponse::validation_error("TOTP code must be 6 digits");
206    }
207
208    match extract_bearer_token(&headers) {
209        Some(token) => {
210            match validate_api_token(&state.auth_framework, &token).await {
211                Ok(auth_token) => {
212                    let storage = state.auth_framework.storage();
213                    let pending_key = format!("mfa_pending_secret:{}", auth_token.user_id);
214
215                    // Retrieve the pending (not-yet-activated) secret.
216                    let secret_b32 = match storage.get_kv(&pending_key).await {
217                        Ok(Some(data)) => String::from_utf8_lossy(&data).to_string(),
218                        _ => {
219                            return ApiResponse::error_typed(
220                                "MFA_NOT_PENDING",
221                                "No pending MFA setup found. Call /mfa/setup first.",
222                            );
223                        }
224                    };
225
226                    let secret_bytes =
227                        match base32::decode(Alphabet::Rfc4648 { padding: false }, &secret_b32) {
228                            Some(b) => b,
229                            None => {
230                                return ApiResponse::error_typed(
231                                    "MFA_ERROR",
232                                    "Invalid stored secret",
233                                );
234                            }
235                        };
236
237                    // Verify the supplied code (±1 window for clock skew).
238                    let now = chrono::Utc::now().timestamp() as u64;
239                    if !verify_totp_code(&req.totp_code, &secret_bytes, now) {
240                        return ApiResponse::error_typed("MFA_INVALID_CODE", "Invalid TOTP code");
241                    }
242
243                    // Activate: persist the secret permanently.
244                    let active_key = format!("mfa_secret:{}", auth_token.user_id);
245                    if let Err(e) = storage
246                        .store_kv(&active_key, secret_b32.as_bytes(), None)
247                        .await
248                    {
249                        tracing::error!(
250                            "Failed to persist MFA secret for user {}: {}",
251                            auth_token.user_id,
252                            e
253                        );
254                        return ApiResponse::error_typed("MFA_ERROR", "Failed to activate MFA");
255                    }
256
257                    // Promote backed-up codes.
258                    let pending_backup_key =
259                        format!("mfa_pending_backup_codes:{}", auth_token.user_id);
260                    if let Ok(Some(data)) = storage.get_kv(&pending_backup_key).await {
261                        let active_backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
262                        if let Err(e) = storage.store_kv(&active_backup_key, &data, None).await {
263                            tracing::warn!(
264                                "Failed to promote MFA backup codes for user {}: {}",
265                                auth_token.user_id,
266                                e
267                            );
268                        }
269                        if let Err(e) = storage.delete_kv(&pending_backup_key).await {
270                            tracing::warn!(
271                                "Failed to clean up pending MFA backup codes for user {}: {}",
272                                auth_token.user_id,
273                                e
274                            );
275                        }
276                    }
277
278                    // Clean up pending secret.
279                    if let Err(e) = storage.delete_kv(&pending_key).await {
280                        tracing::warn!(
281                            "Failed to clean up pending MFA secret for user {}: {}",
282                            auth_token.user_id,
283                            e
284                        );
285                    }
286
287                    // Set the enabled flag.
288                    let flag_key = format!("mfa_enabled:{}", auth_token.user_id);
289                    if let Err(e) = storage.store_kv(&flag_key, b"true", None).await {
290                        tracing::warn!(
291                            "Failed to set MFA enabled flag for user {}: {}",
292                            auth_token.user_id,
293                            e
294                        );
295                    }
296
297                    tracing::info!("MFA enabled for user: {}", auth_token.user_id);
298                    ApiResponse::<()>::ok_with_message("MFA enabled successfully")
299                }
300                Err(e) => ApiResponse::<()>::from(e),
301            }
302        }
303        None => ApiResponse::<()>::unauthorized(),
304    }
305}
306
307/// `POST /mfa/disable` — remove MFA from the authenticated account.
308///
309/// Disables MFA for the authenticated user after verifying their password and
310/// a valid TOTP code.  All MFA storage keys are deleted.
311pub async fn disable_mfa(
312    State(state): State<ApiState>,
313    headers: HeaderMap,
314    Json(req): Json<MfaDisableRequest>,
315) -> ApiResponse<()> {
316    if req.password.is_empty() || req.totp_code.is_empty() {
317        return ApiResponse::validation_error("Password and TOTP code are required");
318    }
319
320    match extract_bearer_token(&headers) {
321        Some(token) => {
322            match validate_api_token(&state.auth_framework, &token).await {
323                Ok(auth_token) => {
324                    // Verify the user's password before allowing MFA to be
325                    // disabled; this protects against token-theft attacks.
326                    match state
327                        .auth_framework
328                        .verify_user_password(&auth_token.user_id, &req.password)
329                        .await
330                    {
331                        Ok(true) => {}
332                        Ok(false) => {
333                            return ApiResponse::error_typed(
334                                "MFA_UNAUTHORIZED",
335                                "Incorrect password",
336                            );
337                        }
338                        Err(_) => {
339                            return ApiResponse::error_typed(
340                                "MFA_UNAUTHORIZED",
341                                "Password verification failed",
342                            );
343                        }
344                    }
345
346                    let storage = state.auth_framework.storage();
347                    let active_key = format!("mfa_secret:{}", auth_token.user_id);
348
349                    // Fetch the active TOTP secret to verify the code.
350                    let secret_b32 = match storage.get_kv(&active_key).await {
351                        Ok(Some(data)) => String::from_utf8_lossy(&data).to_string(),
352                        _ => {
353                            return ApiResponse::error_typed(
354                                "MFA_NOT_ENABLED",
355                                "MFA is not enabled for this account",
356                            );
357                        }
358                    };
359
360                    let secret_bytes =
361                        match base32::decode(Alphabet::Rfc4648 { padding: false }, &secret_b32) {
362                            Some(b) => b,
363                            None => {
364                                return ApiResponse::error_typed(
365                                    "MFA_ERROR",
366                                    "Invalid stored secret",
367                                );
368                            }
369                        };
370
371                    let now = chrono::Utc::now().timestamp() as u64;
372                    if !verify_totp_code(&req.totp_code, &secret_bytes, now) {
373                        return ApiResponse::error_typed("MFA_INVALID_CODE", "Invalid TOTP code");
374                    }
375
376                    // Remove all MFA-related keys.
377                    let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
378                    let flag_key = format!("mfa_enabled:{}", auth_token.user_id);
379
380                    if let Err(e) = storage.delete_kv(&active_key).await {
381                        tracing::warn!(
382                            "Failed to delete MFA secret for user {}: {}",
383                            auth_token.user_id,
384                            e
385                        );
386                    }
387                    if let Err(e) = storage.delete_kv(&backup_key).await {
388                        tracing::warn!(
389                            "Failed to delete MFA backup codes for user {}: {}",
390                            auth_token.user_id,
391                            e
392                        );
393                    }
394                    if let Err(e) = storage.delete_kv(&flag_key).await {
395                        tracing::warn!(
396                            "Failed to delete MFA enabled flag for user {}: {}",
397                            auth_token.user_id,
398                            e
399                        );
400                    }
401
402                    tracing::info!("MFA disabled for user: {}", auth_token.user_id);
403                    ApiResponse::<()>::ok_with_message("MFA disabled successfully")
404                }
405                Err(e) => ApiResponse::<()>::from(e),
406            }
407        }
408        None => ApiResponse::<()>::unauthorized(),
409    }
410}
411
412/// `GET /mfa/status` — query the current MFA enrollment state.
413pub async fn get_mfa_status(
414    State(state): State<ApiState>,
415    headers: HeaderMap,
416) -> ApiResponse<MfaStatusResponse> {
417    match extract_bearer_token(&headers) {
418        Some(token) => match validate_api_token(&state.auth_framework, &token).await {
419            Ok(auth_token) => {
420                let storage = state.auth_framework.storage();
421                let mfa_enabled = check_mfa_enabled(storage.as_ref(), &auth_token.user_id).await;
422                let backup_codes_remaining =
423                    count_backup_codes(storage.as_ref(), &auth_token.user_id).await;
424
425                let status = MfaStatusResponse {
426                    enabled: mfa_enabled,
427                    methods: if mfa_enabled {
428                        vec!["totp".to_string()]
429                    } else {
430                        vec![]
431                    },
432                    backup_codes_remaining,
433                };
434
435                ApiResponse::success(status)
436            }
437            Err(_e) => ApiResponse::error_typed("MFA_ERROR", "MFA status check failed"),
438        },
439        None => ApiResponse::<MfaStatusResponse>::unauthorized_typed(),
440    }
441}
442
443/// `POST /mfa/regenerate-backup-codes` — replace all backup codes.
444///
445/// Replaces all existing backup codes with a fresh set.  MFA must be enabled.
446/// The new plaintext codes are returned **once** and are not stored.
447pub async fn regenerate_backup_codes(
448    State(state): State<ApiState>,
449    headers: HeaderMap,
450) -> ApiResponse<Vec<String>> {
451    match extract_bearer_token(&headers) {
452        Some(token) => {
453            match validate_api_token(&state.auth_framework, &token).await {
454                Ok(auth_token) => {
455                    let storage = state.auth_framework.storage();
456
457                    // Only allow regeneration if MFA is active.
458                    if !check_mfa_enabled(storage.as_ref(), &auth_token.user_id).await {
459                        return ApiResponse::error_typed(
460                            "MFA_NOT_ENABLED",
461                            "MFA is not enabled for this account",
462                        );
463                    }
464
465                    let (plaintext, hashed) = generate_backup_codes();
466                    let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
467                    let hashed_json =
468                        serde_json::to_string(&hashed).unwrap_or_else(|_| "[]".to_string());
469
470                    if let Err(e) = storage
471                        .store_kv(&backup_key, hashed_json.as_bytes(), None)
472                        .await
473                    {
474                        tracing::error!(
475                            "Failed to store backup codes for user {}: {}",
476                            auth_token.user_id,
477                            e
478                        );
479                        return ApiResponse::error_typed(
480                            "MFA_ERROR",
481                            "Failed to regenerate backup codes",
482                        );
483                    }
484
485                    tracing::info!("Backup codes regenerated for user: {}", auth_token.user_id);
486                    ApiResponse::success(plaintext)
487                }
488                Err(_e) => {
489                    ApiResponse::error_typed("MFA_ERROR", "MFA backup codes generation failed")
490                }
491            }
492        }
493        None => ApiResponse::<Vec<String>>::unauthorized_typed(),
494    }
495}
496
497/// `POST /mfa/verify-backup-code` — authenticate with a one-time backup code.
498///
499/// Verifies a backup code for the authenticated user and consumes it (one-time
500/// use).  This can be used in lieu of a TOTP code when the user has lost
501/// access to their authenticator app.
502#[derive(Debug, Deserialize)]
503pub struct BackupCodeVerifyRequest {
504    /// The plaintext backup code to verify.
505    pub backup_code: String,
506}
507
508/// Handler for `POST /mfa/verify-backup-code`.
509pub async fn verify_backup_code(
510    State(state): State<ApiState>,
511    headers: HeaderMap,
512    Json(req): Json<BackupCodeVerifyRequest>,
513) -> ApiResponse<()> {
514    if req.backup_code.is_empty() {
515        return ApiResponse::validation_error("Backup code is required");
516    }
517
518    match extract_bearer_token(&headers) {
519        Some(token) => {
520            match validate_api_token(&state.auth_framework, &token).await {
521                Ok(auth_token) => {
522                    let storage = state.auth_framework.storage();
523                    let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
524
525                    // Load stored hashes.
526                    let codes: Vec<String> = match storage.get_kv(&backup_key).await {
527                        Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
528                        _ => {
529                            return ApiResponse::error_typed(
530                                "MFA_ERROR",
531                                "No backup codes found for this account",
532                            );
533                        }
534                    };
535
536                    // Hash the provided code and compare against each stored
537                    // hash using constant-time equality to prevent timing attacks.
538                    // All stored hashes are always checked (no early break) so
539                    // the response time does not reveal which index matched.
540                    let provided_hash_hex = hash_backup_code(req.backup_code.trim());
541                    let provided_bytes = hex::decode(&provided_hash_hex).unwrap_or_default();
542
543                    let mut found_idx: Option<usize> = None;
544                    for (i, stored_hex) in codes.iter().enumerate() {
545                        let stored_bytes = hex::decode(stored_hex).unwrap_or_default();
546                        if stored_bytes.len() == provided_bytes.len()
547                            && bool::from(stored_bytes.ct_eq(&provided_bytes))
548                        {
549                            // Record the index but continue iterating all codes
550                            // so the loop runs in constant time.
551                            found_idx = Some(i);
552                        }
553                    }
554
555                    match found_idx {
556                        Some(idx) => {
557                            // Consume the code (one-time use).
558                            let mut remaining = codes;
559                            remaining.remove(idx);
560                            let updated = serde_json::to_string(&remaining)
561                                .unwrap_or_else(|_| "[]".to_string());
562                            let _ = storage
563                                .store_kv(&backup_key, updated.as_bytes(), None)
564                                .await;
565
566                            tracing::info!(
567                                "Backup code used for user: {}. {} codes remaining.",
568                                auth_token.user_id,
569                                remaining.len()
570                            );
571                            ApiResponse::<()>::ok_with_message("Backup code verified")
572                        }
573                        None => ApiResponse::error_typed(
574                            "MFA_INVALID_CODE",
575                            "Invalid or already-used backup code",
576                        ),
577                    }
578                }
579                Err(e) => ApiResponse::<()>::from(e),
580            }
581        }
582        None => ApiResponse::<()>::unauthorized(),
583    }
584}
585
586// ---------------------------------------------------------------------------
587// Shared helper functions used by other API modules
588// ---------------------------------------------------------------------------
589
590/// Returns `true` if MFA is currently active for `user_id`.
591///
592/// Uses the `mfa_enabled:{user_id}` KV key set by [`verify_mfa`].
593pub async fn check_user_mfa_status(
594    auth_framework: &std::sync::Arc<crate::AuthFramework>,
595    user_id: &str,
596) -> bool {
597    check_mfa_enabled(auth_framework.storage().as_ref(), user_id).await
598}
599
600/// Low-level helper that works directly with an `AuthStorage` reference.
601async fn check_mfa_enabled(storage: &dyn crate::storage::AuthStorage, user_id: &str) -> bool {
602    let flag_key = format!("mfa_enabled:{}", user_id);
603    matches!(storage.get_kv(&flag_key).await, Ok(Some(_)))
604}
605
606/// Returns the number of remaining backup codes for `user_id`.
607async fn count_backup_codes(storage: &dyn crate::storage::AuthStorage, user_id: &str) -> u32 {
608    let backup_key = format!("mfa_backup_codes:{}", user_id);
609    match storage.get_kv(&backup_key).await {
610        Ok(Some(data)) => serde_json::from_slice::<Vec<String>>(&data)
611            .map(|v| v.len() as u32)
612            .unwrap_or(0),
613        _ => 0,
614    }
615}