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