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