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