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(Debug, Serialize)]
25pub struct MfaSetupResponse {
26 pub qr_code: String,
28 pub secret: String,
30 pub backup_codes: Vec<String>,
32}
33
34#[derive(Debug, Deserialize)]
36pub struct MfaVerifyRequest {
37 pub totp_code: String,
39}
40
41#[derive(Debug, Deserialize)]
43pub struct MfaDisableRequest {
44 pub password: String,
46 pub totp_code: String,
48}
49
50#[derive(Debug, Serialize)]
52pub struct MfaStatusResponse {
53 pub enabled: bool,
55 pub methods: Vec<String>,
57 pub backup_codes_remaining: u32,
59}
60
61fn generate_backup_codes() -> (Vec<String>, Vec<String>) {
68 const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; 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
85fn hash_backup_code(code: &str) -> String {
87 hex::encode(Sha256::digest(code.as_bytes()))
88}
89
90fn 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 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 let eq: bool = expected.as_bytes().ct_eq(provided.as_bytes()).into();
108 matched |= eq;
109 }
110 matched
111}
112
113pub 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 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 let (plaintext_codes, hashed_codes) = generate_backup_codes();
140
141 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 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
188pub 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 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 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 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 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 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 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
306pub 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 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 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 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
411pub 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
442pub 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 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#[derive(Debug, Deserialize)]
502pub struct BackupCodeVerifyRequest {
503 pub backup_code: String,
505}
506
507pub 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 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 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 found_idx = Some(i);
551 }
552 }
553
554 match found_idx {
555 Some(idx) => {
556 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
585pub 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
599async 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
605async 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}