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