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