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 _;
19
20#[derive(Serialize)]
25pub struct MfaSetupResponse {
26 pub qr_code: String,
28 pub secret: String,
30 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#[derive(Deserialize)]
49pub struct MfaVerifyRequest {
50 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#[derive(Deserialize)]
67pub struct MfaDisableRequest {
68 pub password: String,
70 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#[derive(Debug, Serialize)]
88pub struct MfaStatusResponse {
89 pub enabled: bool,
91 pub methods: Vec<String>,
93 pub backup_codes_remaining: u32,
95}
96
97fn generate_backup_codes() -> (Vec<String>, Vec<String>) {
104 const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; 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
121fn hash_backup_code(code: &str) -> String {
123 hex::encode(Sha256::digest(code.as_bytes()))
124}
125
126fn 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 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 let eq: bool = expected.as_bytes().ct_eq(provided.as_bytes()).into();
144 matched |= eq;
145 }
146 matched
147}
148
149pub 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 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 let (plaintext_codes, hashed_codes) = generate_backup_codes();
176
177 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 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
224pub 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 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 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 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 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 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 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
342pub 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 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 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 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
447pub 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
478pub 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 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#[derive(Deserialize)]
538pub struct BackupCodeVerifyRequest {
539 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
554pub 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 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 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 found_idx = Some(i);
598 }
599 }
600
601 match found_idx {
602 Some(idx) => {
603 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
632pub 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
646async 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
652async 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}