1use 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#[derive(Serialize)]
26pub struct MfaSetupResponse {
27 pub qr_code: String,
29 pub secret: Zeroizing<String>,
31 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#[derive(Deserialize)]
50pub struct MfaVerifyRequest {
51 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#[derive(Deserialize)]
68pub struct MfaDisableRequest {
69 pub password: String,
71 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#[derive(Debug, Serialize)]
89pub struct MfaStatusResponse {
90 pub enabled: bool,
92 pub methods: Vec<String>,
94 pub backup_codes_remaining: u32,
96}
97
98fn generate_backup_codes() -> (Vec<String>, Vec<String>) {
105 const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; 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
122fn hash_backup_code(code: &str) -> String {
124 hex::encode(Sha256::digest(code.as_bytes()))
125}
126
127fn 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 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 let eq: bool = expected.as_bytes().ct_eq(provided.as_bytes()).into();
145 matched |= eq;
146 }
147 matched
148}
149
150pub 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 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 let (plaintext_codes, hashed_codes) = generate_backup_codes();
177
178 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 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
225pub 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 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 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 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 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 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 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
343pub 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 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 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 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
448pub 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
479pub 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 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#[derive(Deserialize)]
539pub struct BackupCodeVerifyRequest {
540 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
555pub 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 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 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 found_idx = Some(i);
599 }
600 }
601
602 match found_idx {
603 Some(idx) => {
604 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
633pub 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
647async 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
653async 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}