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(Debug, Serialize)]
26pub struct MfaSetupResponse {
27 pub qr_code: String,
29 pub secret: Zeroizing<String>,
31 pub backup_codes: Vec<String>,
33}
34
35#[derive(Debug, Deserialize)]
37pub struct MfaVerifyRequest {
38 pub totp_code: String,
40}
41
42#[derive(Debug, Deserialize)]
44pub struct MfaDisableRequest {
45 pub password: String,
47 pub totp_code: String,
49}
50
51#[derive(Debug, Serialize)]
53pub struct MfaStatusResponse {
54 pub enabled: bool,
56 pub methods: Vec<String>,
58 pub backup_codes_remaining: u32,
60}
61
62fn generate_backup_codes() -> (Vec<String>, Vec<String>) {
69 const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; let mut plaintext = Vec::with_capacity(10);
71 let mut hashed = Vec::with_capacity(10);
72 let mut buf = [0u8; 8];
73 for _ in 0..10 {
74 rand::rng().fill_bytes(&mut buf);
75 let code: String = buf
76 .iter()
77 .map(|b| ALPHABET[(*b as usize) % ALPHABET.len()] as char)
78 .collect();
79 let hash = hex::encode(Sha256::digest(code.as_bytes()));
80 plaintext.push(code);
81 hashed.push(hash);
82 }
83 (plaintext, hashed)
84}
85
86fn hash_backup_code(code: &str) -> String {
88 hex::encode(Sha256::digest(code.as_bytes()))
89}
90
91fn verify_totp_code(provided: &str, secret_bytes: &[u8], now: u64) -> bool {
95 use subtle::ConstantTimeEq as _;
96 use totp_lite::{Sha1, totp_custom};
97 const STEP: u64 = 30;
98 const DIGITS: u32 = 6;
99
100 let mut matched = false;
104 for offset in [0u64, STEP, STEP.wrapping_neg()] {
105 let t = now.wrapping_add(offset);
106 let expected = totp_custom::<Sha1>(STEP, DIGITS, secret_bytes, t);
107 let eq: bool = expected.as_bytes().ct_eq(provided.as_bytes()).into();
109 matched |= eq;
110 }
111 matched
112}
113
114pub async fn setup_mfa(
126 State(state): State<ApiState>,
127 headers: HeaderMap,
128) -> ApiResponse<MfaSetupResponse> {
129 match extract_bearer_token(&headers) {
130 Some(token) => {
131 match validate_api_token(&state.auth_framework, &token).await {
132 Ok(auth_token) => {
133 let mut secret_bytes = [0u8; 20];
135 rand::rng().fill_bytes(&mut secret_bytes);
136 let secret_b32 =
137 base32::encode(Alphabet::Rfc4648 { padding: false }, &secret_bytes);
138
139 let (plaintext_codes, hashed_codes) = generate_backup_codes();
141
142 let storage = state.auth_framework.storage();
145 let pending_secret_key = format!("mfa_pending_secret:{}", auth_token.user_id);
146 let pending_backup_key =
147 format!("mfa_pending_backup_codes:{}", auth_token.user_id);
148 let ttl = std::time::Duration::from_secs(600);
149
150 if let Err(e) = storage
151 .store_kv(&pending_secret_key, secret_b32.as_bytes(), Some(ttl))
152 .await
153 {
154 tracing::error!("Failed to store pending MFA secret: {}", e);
155 return ApiResponse::error_typed(
156 "MFA_ERROR",
157 "Failed to initiate MFA setup",
158 );
159 }
160
161 let hashed_json =
162 serde_json::to_string(&hashed_codes).unwrap_or_else(|_| "[]".to_string());
163 let _ = storage
164 .store_kv(&pending_backup_key, hashed_json.as_bytes(), Some(ttl))
165 .await;
166
167 let issuer = "AuthFramework";
170 let account = urlencoding::encode(&auth_token.user_id);
171 let qr_code = format!(
172 "otpauth://totp/{issuer}:{account}?secret={secret_b32}&issuer={issuer}&digits=6&period=30"
173 );
174
175 tracing::info!("MFA setup initiated for user: {}", auth_token.user_id);
176 ApiResponse::success(MfaSetupResponse {
177 qr_code,
178 secret: secret_b32.into(),
179 backup_codes: plaintext_codes,
180 })
181 }
182 Err(_e) => ApiResponse::error_typed("MFA_ERROR", "MFA setup failed"),
183 }
184 }
185 None => ApiResponse::<MfaSetupResponse>::unauthorized_typed(),
186 }
187}
188
189pub async fn verify_mfa(
196 State(state): State<ApiState>,
197 headers: HeaderMap,
198 Json(req): Json<MfaVerifyRequest>,
199) -> ApiResponse<()> {
200 if req.totp_code.is_empty() {
201 return ApiResponse::validation_error("TOTP code is required");
202 }
203
204 if req.totp_code.len() != 6 || !req.totp_code.chars().all(|c| c.is_ascii_digit()) {
205 return ApiResponse::validation_error("TOTP code must be 6 digits");
206 }
207
208 match extract_bearer_token(&headers) {
209 Some(token) => {
210 match validate_api_token(&state.auth_framework, &token).await {
211 Ok(auth_token) => {
212 let storage = state.auth_framework.storage();
213 let pending_key = format!("mfa_pending_secret:{}", auth_token.user_id);
214
215 let secret_b32 = match storage.get_kv(&pending_key).await {
217 Ok(Some(data)) => String::from_utf8_lossy(&data).to_string(),
218 _ => {
219 return ApiResponse::error_typed(
220 "MFA_NOT_PENDING",
221 "No pending MFA setup found. Call /mfa/setup first.",
222 );
223 }
224 };
225
226 let secret_bytes =
227 match base32::decode(Alphabet::Rfc4648 { padding: false }, &secret_b32) {
228 Some(b) => b,
229 None => {
230 return ApiResponse::error_typed(
231 "MFA_ERROR",
232 "Invalid stored secret",
233 );
234 }
235 };
236
237 let now = chrono::Utc::now().timestamp() as u64;
239 if !verify_totp_code(&req.totp_code, &secret_bytes, now) {
240 return ApiResponse::error_typed("MFA_INVALID_CODE", "Invalid TOTP code");
241 }
242
243 let active_key = format!("mfa_secret:{}", auth_token.user_id);
245 if let Err(e) = storage
246 .store_kv(&active_key, secret_b32.as_bytes(), None)
247 .await
248 {
249 tracing::error!(
250 "Failed to persist MFA secret for user {}: {}",
251 auth_token.user_id,
252 e
253 );
254 return ApiResponse::error_typed("MFA_ERROR", "Failed to activate MFA");
255 }
256
257 let pending_backup_key =
259 format!("mfa_pending_backup_codes:{}", auth_token.user_id);
260 if let Ok(Some(data)) = storage.get_kv(&pending_backup_key).await {
261 let active_backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
262 if let Err(e) = storage.store_kv(&active_backup_key, &data, None).await {
263 tracing::warn!(
264 "Failed to promote MFA backup codes for user {}: {}",
265 auth_token.user_id,
266 e
267 );
268 }
269 if let Err(e) = storage.delete_kv(&pending_backup_key).await {
270 tracing::warn!(
271 "Failed to clean up pending MFA backup codes for user {}: {}",
272 auth_token.user_id,
273 e
274 );
275 }
276 }
277
278 if let Err(e) = storage.delete_kv(&pending_key).await {
280 tracing::warn!(
281 "Failed to clean up pending MFA secret for user {}: {}",
282 auth_token.user_id,
283 e
284 );
285 }
286
287 let flag_key = format!("mfa_enabled:{}", auth_token.user_id);
289 if let Err(e) = storage.store_kv(&flag_key, b"true", None).await {
290 tracing::warn!(
291 "Failed to set MFA enabled flag for user {}: {}",
292 auth_token.user_id,
293 e
294 );
295 }
296
297 tracing::info!("MFA enabled for user: {}", auth_token.user_id);
298 ApiResponse::<()>::ok_with_message("MFA enabled successfully")
299 }
300 Err(e) => ApiResponse::<()>::from(e),
301 }
302 }
303 None => ApiResponse::<()>::unauthorized(),
304 }
305}
306
307pub async fn disable_mfa(
312 State(state): State<ApiState>,
313 headers: HeaderMap,
314 Json(req): Json<MfaDisableRequest>,
315) -> ApiResponse<()> {
316 if req.password.is_empty() || req.totp_code.is_empty() {
317 return ApiResponse::validation_error("Password and TOTP code are required");
318 }
319
320 match extract_bearer_token(&headers) {
321 Some(token) => {
322 match validate_api_token(&state.auth_framework, &token).await {
323 Ok(auth_token) => {
324 match state
327 .auth_framework
328 .verify_user_password(&auth_token.user_id, &req.password)
329 .await
330 {
331 Ok(true) => {}
332 Ok(false) => {
333 return ApiResponse::error_typed(
334 "MFA_UNAUTHORIZED",
335 "Incorrect password",
336 );
337 }
338 Err(_) => {
339 return ApiResponse::error_typed(
340 "MFA_UNAUTHORIZED",
341 "Password verification failed",
342 );
343 }
344 }
345
346 let storage = state.auth_framework.storage();
347 let active_key = format!("mfa_secret:{}", auth_token.user_id);
348
349 let secret_b32 = match storage.get_kv(&active_key).await {
351 Ok(Some(data)) => String::from_utf8_lossy(&data).to_string(),
352 _ => {
353 return ApiResponse::error_typed(
354 "MFA_NOT_ENABLED",
355 "MFA is not enabled for this account",
356 );
357 }
358 };
359
360 let secret_bytes =
361 match base32::decode(Alphabet::Rfc4648 { padding: false }, &secret_b32) {
362 Some(b) => b,
363 None => {
364 return ApiResponse::error_typed(
365 "MFA_ERROR",
366 "Invalid stored secret",
367 );
368 }
369 };
370
371 let now = chrono::Utc::now().timestamp() as u64;
372 if !verify_totp_code(&req.totp_code, &secret_bytes, now) {
373 return ApiResponse::error_typed("MFA_INVALID_CODE", "Invalid TOTP code");
374 }
375
376 let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
378 let flag_key = format!("mfa_enabled:{}", auth_token.user_id);
379
380 if let Err(e) = storage.delete_kv(&active_key).await {
381 tracing::warn!(
382 "Failed to delete MFA secret for user {}: {}",
383 auth_token.user_id,
384 e
385 );
386 }
387 if let Err(e) = storage.delete_kv(&backup_key).await {
388 tracing::warn!(
389 "Failed to delete MFA backup codes for user {}: {}",
390 auth_token.user_id,
391 e
392 );
393 }
394 if let Err(e) = storage.delete_kv(&flag_key).await {
395 tracing::warn!(
396 "Failed to delete MFA enabled flag for user {}: {}",
397 auth_token.user_id,
398 e
399 );
400 }
401
402 tracing::info!("MFA disabled for user: {}", auth_token.user_id);
403 ApiResponse::<()>::ok_with_message("MFA disabled successfully")
404 }
405 Err(e) => ApiResponse::<()>::from(e),
406 }
407 }
408 None => ApiResponse::<()>::unauthorized(),
409 }
410}
411
412pub async fn get_mfa_status(
414 State(state): State<ApiState>,
415 headers: HeaderMap,
416) -> ApiResponse<MfaStatusResponse> {
417 match extract_bearer_token(&headers) {
418 Some(token) => match validate_api_token(&state.auth_framework, &token).await {
419 Ok(auth_token) => {
420 let storage = state.auth_framework.storage();
421 let mfa_enabled = check_mfa_enabled(storage.as_ref(), &auth_token.user_id).await;
422 let backup_codes_remaining =
423 count_backup_codes(storage.as_ref(), &auth_token.user_id).await;
424
425 let status = MfaStatusResponse {
426 enabled: mfa_enabled,
427 methods: if mfa_enabled {
428 vec!["totp".to_string()]
429 } else {
430 vec![]
431 },
432 backup_codes_remaining,
433 };
434
435 ApiResponse::success(status)
436 }
437 Err(_e) => ApiResponse::error_typed("MFA_ERROR", "MFA status check failed"),
438 },
439 None => ApiResponse::<MfaStatusResponse>::unauthorized_typed(),
440 }
441}
442
443pub async fn regenerate_backup_codes(
448 State(state): State<ApiState>,
449 headers: HeaderMap,
450) -> ApiResponse<Vec<String>> {
451 match extract_bearer_token(&headers) {
452 Some(token) => {
453 match validate_api_token(&state.auth_framework, &token).await {
454 Ok(auth_token) => {
455 let storage = state.auth_framework.storage();
456
457 if !check_mfa_enabled(storage.as_ref(), &auth_token.user_id).await {
459 return ApiResponse::error_typed(
460 "MFA_NOT_ENABLED",
461 "MFA is not enabled for this account",
462 );
463 }
464
465 let (plaintext, hashed) = generate_backup_codes();
466 let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
467 let hashed_json =
468 serde_json::to_string(&hashed).unwrap_or_else(|_| "[]".to_string());
469
470 if let Err(e) = storage
471 .store_kv(&backup_key, hashed_json.as_bytes(), None)
472 .await
473 {
474 tracing::error!(
475 "Failed to store backup codes for user {}: {}",
476 auth_token.user_id,
477 e
478 );
479 return ApiResponse::error_typed(
480 "MFA_ERROR",
481 "Failed to regenerate backup codes",
482 );
483 }
484
485 tracing::info!("Backup codes regenerated for user: {}", auth_token.user_id);
486 ApiResponse::success(plaintext)
487 }
488 Err(_e) => {
489 ApiResponse::error_typed("MFA_ERROR", "MFA backup codes generation failed")
490 }
491 }
492 }
493 None => ApiResponse::<Vec<String>>::unauthorized_typed(),
494 }
495}
496
497#[derive(Debug, Deserialize)]
503pub struct BackupCodeVerifyRequest {
504 pub backup_code: String,
506}
507
508pub async fn verify_backup_code(
510 State(state): State<ApiState>,
511 headers: HeaderMap,
512 Json(req): Json<BackupCodeVerifyRequest>,
513) -> ApiResponse<()> {
514 if req.backup_code.is_empty() {
515 return ApiResponse::validation_error("Backup code is required");
516 }
517
518 match extract_bearer_token(&headers) {
519 Some(token) => {
520 match validate_api_token(&state.auth_framework, &token).await {
521 Ok(auth_token) => {
522 let storage = state.auth_framework.storage();
523 let backup_key = format!("mfa_backup_codes:{}", auth_token.user_id);
524
525 let codes: Vec<String> = match storage.get_kv(&backup_key).await {
527 Ok(Some(data)) => serde_json::from_slice(&data).unwrap_or_default(),
528 _ => {
529 return ApiResponse::error_typed(
530 "MFA_ERROR",
531 "No backup codes found for this account",
532 );
533 }
534 };
535
536 let provided_hash_hex = hash_backup_code(req.backup_code.trim());
541 let provided_bytes = hex::decode(&provided_hash_hex).unwrap_or_default();
542
543 let mut found_idx: Option<usize> = None;
544 for (i, stored_hex) in codes.iter().enumerate() {
545 let stored_bytes = hex::decode(stored_hex).unwrap_or_default();
546 if stored_bytes.len() == provided_bytes.len()
547 && bool::from(stored_bytes.ct_eq(&provided_bytes))
548 {
549 found_idx = Some(i);
552 }
553 }
554
555 match found_idx {
556 Some(idx) => {
557 let mut remaining = codes;
559 remaining.remove(idx);
560 let updated = serde_json::to_string(&remaining)
561 .unwrap_or_else(|_| "[]".to_string());
562 let _ = storage
563 .store_kv(&backup_key, updated.as_bytes(), None)
564 .await;
565
566 tracing::info!(
567 "Backup code used for user: {}. {} codes remaining.",
568 auth_token.user_id,
569 remaining.len()
570 );
571 ApiResponse::<()>::ok_with_message("Backup code verified")
572 }
573 None => ApiResponse::error_typed(
574 "MFA_INVALID_CODE",
575 "Invalid or already-used backup code",
576 ),
577 }
578 }
579 Err(e) => ApiResponse::<()>::from(e),
580 }
581 }
582 None => ApiResponse::<()>::unauthorized(),
583 }
584}
585
586pub async fn check_user_mfa_status(
594 auth_framework: &std::sync::Arc<crate::AuthFramework>,
595 user_id: &str,
596) -> bool {
597 check_mfa_enabled(auth_framework.storage().as_ref(), user_id).await
598}
599
600async fn check_mfa_enabled(storage: &dyn crate::storage::AuthStorage, user_id: &str) -> bool {
602 let flag_key = format!("mfa_enabled:{}", user_id);
603 matches!(storage.get_kv(&flag_key).await, Ok(Some(_)))
604}
605
606async fn count_backup_codes(storage: &dyn crate::storage::AuthStorage, user_id: &str) -> u32 {
608 let backup_key = format!("mfa_backup_codes:{}", user_id);
609 match storage.get_kv(&backup_key).await {
610 Ok(Some(data)) => serde_json::from_slice::<Vec<String>>(&data)
611 .map(|v| v.len() as u32)
612 .unwrap_or(0),
613 _ => 0,
614 }
615}