Skip to main content

auth_framework/auth_modular/
user_manager.rs

1//! User management module
2
3use crate::config::PasswordHashAlgorithm;
4use crate::errors::{AuthError, Result};
5use crate::storage::AuthStorage;
6use std::collections::HashMap;
7use std::sync::Arc;
8use tracing::{debug, info, warn};
9
10/// Canonical user information type shared with [`crate::auth::UserInfo`].
11pub type UserInfo = crate::auth::UserInfo;
12
13// Test-only call counters, used to prove the unknown-user path in
14// UserManager::verify_login_credentials performs exactly one
15// verification and zero hashing operations -- a plain "does the result
16// stay the same" test on `dummy_password_hash` cannot catch a regression
17// that reintroduces hashing *in addition to* that field, since the field
18// itself would be untouched by such a mutation. Thread-local, not a
19// shared global: #[tokio::test] uses a single-threaded runtime by
20// default, so one test's counts cannot be polluted by another test
21// running concurrently on a different OS thread.
22#[cfg(test)]
23thread_local! {
24    static HASH_CALL_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
25    static VERIFY_CALL_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
26}
27
28#[cfg(test)]
29fn reset_call_counters() {
30    HASH_CALL_COUNT.set(0);
31    VERIFY_CALL_COUNT.set(0);
32}
33
34#[cfg(test)]
35fn call_counts() -> (usize, usize) {
36    (HASH_CALL_COUNT.get(), VERIFY_CALL_COUNT.get())
37}
38
39/// Verify `password` against `hash`, detecting the hash's own format
40/// (bcrypt or Argon2id PHC string) rather than assuming one. Used so that
41/// changing [`PasswordHashAlgorithm`] doesn't break verification for users
42/// whose password was hashed before the change.
43fn verify_password_any_format(password: &str, hash: &str) -> Result<bool> {
44    #[cfg(test)]
45    VERIFY_CALL_COUNT.set(VERIFY_CALL_COUNT.get() + 1);
46    if hash.starts_with("$argon2") {
47        crate::utils::password::verify_password_argon2id(password, hash)
48    } else {
49        crate::security::secure_utils::verify_password_bcrypt(password, hash)
50    }
51}
52
53/// Result of a successful credential verification via [`UserManager::verify_login_credentials`].
54///
55/// # Example
56/// ```rust,ignore
57/// if let Some(result) = mgr.verify_login_credentials("alice", "pass").await? {
58///     println!("user_id={}, mfa={}", result.user_id, result.mfa_enabled);
59/// }
60/// ```
61pub struct CredentialCheckResult {
62    /// The verified user's ID.
63    pub user_id: String,
64    /// Whether the user has MFA enabled.
65    pub mfa_enabled: bool,
66}
67
68/// User manager for handling user operations.
69///
70/// # Example
71/// ```rust,ignore
72/// use auth_framework::auth_modular::UserManager;
73/// use auth_framework::config::PasswordHashAlgorithm;
74/// let um = UserManager::new(storage.clone(), PasswordHashAlgorithm::Argon2);
75/// let uid = um.register_user("alice", "alice@example.com", "Str0ng!Pass").await?;
76/// ```
77pub struct UserManager {
78    storage: Arc<dyn AuthStorage>,
79    password_hash_algorithm: PasswordHashAlgorithm,
80    /// A hash of a fixed dummy password, computed once under the configured
81    /// algorithm at construction time. Used by the unknown-user path in
82    /// [`Self::verify_login_credentials`] so that path costs exactly one
83    /// verification, the same as a known user with a wrong password --
84    /// computing a fresh hash on every lookup (one hash + one verify)
85    /// would cost roughly double, which is itself a username-enumeration
86    /// timing oracle. `None` only when `password_hash_algorithm` has no
87    /// working hasher (currently just `Scrypt`, constructed directly
88    /// rather than through a validated `AuthConfig`); the unknown-user
89    /// path degrades to doing no dummy work at all in that case, which is
90    /// a known, narrow limitation rather than a silent regression.
91    dummy_password_hash: Option<String>,
92}
93
94impl UserManager {
95    /// Create a new user manager that hashes new/changed passwords with
96    /// `password_hash_algorithm`. Verification is unaffected by this
97    /// setting -- it detects the stored hash's own format, so existing
98    /// users keep verifying correctly across an algorithm change.
99    ///
100    /// Computes a dummy password hash under `password_hash_algorithm` once,
101    /// synchronously, before returning -- this blocks the calling thread
102    /// for roughly the same time as one real hash operation (measured:
103    /// ~39ms for Argon2id with this crate's parameters, ~366ms for
104    /// bcrypt's default cost; `Scrypt` returns immediately since it has
105    /// no implementation and the dummy hash is simply absent in that
106    /// case). This is a one-time, per-instance cost, not per-request.
107    ///
108    /// # Example
109    /// ```rust,ignore
110    /// let um = UserManager::new(storage.clone(), PasswordHashAlgorithm::Argon2);
111    /// ```
112    pub fn new(
113        storage: Arc<dyn AuthStorage>,
114        password_hash_algorithm: PasswordHashAlgorithm,
115    ) -> Self {
116        let dummy_password_hash =
117            Self::hash_with_algorithm(&password_hash_algorithm, "dummy-password-for-timing").ok();
118        Self {
119            storage,
120            password_hash_algorithm,
121            dummy_password_hash,
122        }
123    }
124
125    /// Hash `password` using the configured algorithm.
126    fn hash_password(&self, password: &str) -> Result<String> {
127        Self::hash_with_algorithm(&self.password_hash_algorithm, password)
128    }
129
130    fn hash_with_algorithm(algorithm: &PasswordHashAlgorithm, password: &str) -> Result<String> {
131        #[cfg(test)]
132        HASH_CALL_COUNT.set(HASH_CALL_COUNT.get() + 1);
133        match algorithm {
134            PasswordHashAlgorithm::Argon2 => {
135                crate::utils::password::hash_password_argon2id(password)
136            }
137            PasswordHashAlgorithm::Bcrypt => {
138                crate::security::secure_utils::hash_password_bcrypt(password)
139            }
140            PasswordHashAlgorithm::Scrypt => Err(AuthError::internal(
141                "PasswordHashAlgorithm::Scrypt is not yet implemented; configure Argon2 or \
142                 Bcrypt instead of silently hashing with a different algorithm"
143                    .to_string(),
144            )),
145        }
146    }
147
148    /// Create API key for a user.
149    ///
150    /// # Example
151    /// ```rust,ignore
152    /// let key = um.create_api_key("user-1", Some(Duration::from_secs(86400))).await?;
153    /// ```
154    pub async fn create_api_key(
155        &self,
156        user_id: &str,
157        expires_in: Option<std::time::Duration>,
158    ) -> Result<String> {
159        debug!("Creating API key for user '{}'", user_id);
160
161        // Generate a secure API key
162        let api_key = format!("ak_{}", crate::utils::crypto::generate_token(32));
163
164        // Store API key metadata
165        let key_data = serde_json::json!({
166            "user_id": user_id,
167            "created_at": chrono::Utc::now(),
168            "expires_at": expires_in.map(|d| chrono::Utc::now() + chrono::Duration::from_std(d).unwrap_or(chrono::Duration::days(365 * 10)))
169        });
170
171        let storage_key = format!("api_key:{}", api_key);
172        self.storage
173            .store_kv(&storage_key, key_data.to_string().as_bytes(), expires_in)
174            .await?;
175
176        info!("API key created for user '{}'", user_id);
177        Ok(api_key)
178    }
179
180    /// Validate API key and return user information.
181    ///
182    /// # Example
183    /// ```rust,ignore
184    /// let info = um.validate_api_key("ak_abc123").await?;
185    /// println!("user: {}", info.username);
186    /// ```
187    pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
188        debug!("Validating API key");
189
190        let storage_key = format!("api_key:{}", api_key);
191        if let Some(key_data) = self.storage.get_kv(&storage_key).await? {
192            let key_info: serde_json::Value = serde_json::from_slice(&key_data)?;
193
194            if let Some(user_id) = key_info["user_id"].as_str() {
195                // Check expiration
196                if let Some(expires_at_str) = key_info["expires_at"].as_str() {
197                    let expires_at: chrono::DateTime<chrono::Utc> = expires_at_str
198                        .parse()
199                        .map_err(|_| AuthError::token("Invalid API key expiration"))?;
200
201                    if chrono::Utc::now() > expires_at {
202                        return Err(AuthError::token("API key expired"));
203                    }
204                }
205
206                // Return user information
207                Ok(UserInfo {
208                    id: user_id.to_string(),
209                    username: format!("api_user_{}", user_id),
210                    email: None,
211                    name: None,
212                    roles: vec!["api_user".to_string()].into(),
213                    active: true,
214                    email_verified: false,
215                    attributes: crate::types::UserAttributes::empty(),
216                })
217            } else {
218                Err(AuthError::token("Invalid API key format"))
219            }
220        } else {
221            Err(AuthError::token("Invalid API key"))
222        }
223    }
224
225    /// Revoke API key.
226    ///
227    /// # Example
228    /// ```rust,ignore
229    /// um.revoke_api_key("ak_abc123").await?;
230    /// ```
231    pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
232        debug!("Revoking API key");
233
234        let storage_key = format!("api_key:{}", api_key);
235        if self.storage.get_kv(&storage_key).await?.is_some() {
236            self.storage.delete_kv(&storage_key).await?;
237            info!("API key revoked");
238            Ok(())
239        } else {
240            Err(AuthError::token("API key not found"))
241        }
242    }
243
244    /// Validate username format.
245    ///
246    /// # Example
247    /// ```rust,ignore
248    /// assert!(um.validate_username("alice").await?);
249    /// assert!(!um.validate_username("").await?);
250    /// ```
251    pub async fn validate_username(&self, username: &str) -> Result<bool> {
252        debug!("Validating username format: '{}'", username);
253
254        let is_valid = username.len() >= 3
255            && username.len() <= 32
256            && username
257                .chars()
258                .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
259
260        Ok(is_valid)
261    }
262
263    /// Validate display name format.
264    ///
265    /// # Example
266    /// ```rust,ignore
267    /// assert!(um.validate_display_name("Alice B.").await?);
268    /// ```
269    pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
270        debug!("Validating display name format");
271
272        let is_valid = !display_name.is_empty()
273            && display_name.len() <= 100
274            && !display_name.trim().is_empty();
275
276        Ok(is_valid)
277    }
278
279    /// Validate password strength using security policy.
280    ///
281    /// Requires Strong or VeryStrong to protect production deployments.
282    ///
283    /// # Example
284    /// ```rust,ignore
285    /// assert!(um.validate_password_strength("C0mpl3x!Pa$$word").await?);
286    /// assert!(!um.validate_password_strength("weak").await?);
287    /// ```
288    pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
289        debug!("Validating password strength");
290        let strength = crate::utils::password::check_password_strength(password);
291        let is_valid = crate::utils::password::meets_production_strength(strength.level);
292        if !is_valid {
293            warn!(
294                "Password validation failed - Actual: {:?}, Feedback: {}",
295                strength.level,
296                strength.feedback.join(", ")
297            );
298        }
299        Ok(is_valid)
300    }
301
302    /// Validate user input for security.
303    ///
304    /// Combines a character whitelist with pattern checks for common injection
305    /// vectors. Rejects HTML tags, null bytes, path traversal sequences,
306    /// template injection markers, and dangerous URI schemes.
307    ///
308    /// # Example
309    /// ```rust,ignore
310    /// assert!(um.validate_user_input("hello world").await?);
311    /// assert!(!um.validate_user_input("<script>alert(1)</script>").await?);
312    /// ```
313    pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
314        debug!("Validating user input");
315
316        if input.is_empty() || input.len() > 1000 {
317            return Ok(false);
318        }
319
320        // Character whitelist: reject control characters and angle brackets.
321        if !input.chars().all(|c| {
322            if c.is_control() {
323                matches!(c, ' ' | '\t' | '\n' | '\r')
324            } else {
325                !matches!(c, '<' | '>')
326            }
327        }) {
328            return Ok(false);
329        }
330
331        let lower = input.to_ascii_lowercase();
332        if lower.contains("%3c") || lower.contains("%3e") || lower.contains("%00") {
333            return Ok(false);
334        }
335        if lower.contains("javascript:")
336            || lower.contains("data:")
337            || lower.contains("file:")
338            || lower.contains("jndi:")
339        {
340            return Ok(false);
341        }
342        if input.contains("${") || input.contains("{{") {
343            return Ok(false);
344        }
345        if input.contains("../") || input.contains("..\\") {
346            return Ok(false);
347        }
348        if input.contains('\0') {
349            return Ok(false);
350        }
351        if lower.contains("; drop")
352            || lower.contains(";drop")
353            || lower.contains("' drop")
354            || lower.contains("'; drop")
355            || lower.contains("--")
356        {
357            return Ok(false);
358        }
359
360        Ok(true)
361    }
362
363    /// Get user information by ID.
364    ///
365    /// # Example
366    /// ```rust,ignore
367    /// let info = um.get_user_info("user-1").await?;
368    /// println!("username: {}", info.username);
369    /// ```
370    pub async fn get_user_info(&self, user_id: &str) -> Result<UserInfo> {
371        debug!("Getting user info for '{}'", user_id);
372
373        let key = format!("user:{}", user_id);
374        if let Some(data) = self.storage.get_kv(&key).await? {
375            let user_data: serde_json::Value = serde_json::from_slice(&data)
376                .map_err(|e| AuthError::internal(format!("Failed to parse user data: {e}")))?;
377
378            Ok(UserInfo {
379                id: user_data["user_id"].as_str().unwrap_or(user_id).to_string(),
380                username: user_data["username"].as_str().unwrap_or("").to_string(),
381                email: user_data["email"].as_str().map(String::from),
382                name: user_data["name"].as_str().map(String::from),
383                roles: user_data["roles"]
384                    .as_array()
385                    .map(|arr| {
386                        arr.iter()
387                            .filter_map(|v| v.as_str().map(String::from))
388                            .collect::<Vec<_>>()
389                    })
390                    .unwrap_or_else(|| vec!["user".to_string()])
391                    .into(),
392                active: user_data["active"].as_bool().unwrap_or(true),
393                email_verified: user_data["email_verified"].as_bool().unwrap_or(false),
394                attributes: crate::types::UserAttributes::empty(),
395            })
396        } else {
397            Err(AuthError::validation(format!("User '{user_id}' not found")))
398        }
399    }
400
401    /// List users from the canonical user index.
402    ///
403    /// # Example
404    /// ```rust,ignore
405    /// let users = um.list_users(Some(10), Some(0), true).await?;
406    /// for u in &users { println!("{}", u.username); }
407    /// ```
408    pub async fn list_users(
409        &self,
410        limit: Option<usize>,
411        offset: Option<usize>,
412        active_only: bool,
413    ) -> Result<Vec<UserInfo>> {
414        let bytes = self.storage.get_kv("users:index").await?;
415        let user_ids: Vec<String> = match bytes {
416            Some(bytes) => serde_json::from_slice(&bytes)
417                .map_err(|e| AuthError::internal(format!("Failed to parse user index: {e}")))?,
418            None => return Ok(Vec::new()),
419        };
420
421        let skip = offset.unwrap_or(0);
422        let take = limit.unwrap_or(usize::MAX);
423        let mut users = Vec::new();
424
425        for user_id in user_ids.into_iter().skip(skip) {
426            let user = self.get_user_info(&user_id).await?;
427            if active_only && !user.active {
428                continue;
429            }
430            users.push(user);
431            if users.len() >= take {
432                break;
433            }
434        }
435
436        Ok(users)
437    }
438
439    /// Check if user exists.
440    ///
441    /// # Example
442    /// ```rust,ignore
443    /// if um.user_exists("user-1").await? {
444    ///     println!("user found");
445    /// }
446    /// ```
447    pub async fn user_exists(&self, user_id: &str) -> Result<bool> {
448        debug!("Checking if user '{}' exists", user_id);
449
450        if user_id.is_empty() {
451            return Ok(false);
452        }
453
454        let key = format!("user:{}", user_id);
455        Ok(self.storage.get_kv(&key).await?.is_some())
456    }
457
458    // ────────────────────────────────────────────────────────────────────────
459    // Full user lifecycle management (migrated from auth.rs::AuthFramework)
460    // ────────────────────────────────────────────────────────────────────────
461
462    /// Register a new user, creating all required storage records.
463    ///
464    /// # Example
465    /// ```rust,ignore
466    /// let uid = um.register_user("alice", "alice@example.com", "Str0ng!Pass").await?;
467    /// println!("registered user: {}", uid);
468    /// ```
469    pub async fn register_user(
470        &self,
471        username: &str,
472        email: &str,
473        password: &str,
474    ) -> Result<String> {
475        debug!("Registering new user: {}", username);
476
477        let username_key = format!("user:username:{}", username);
478        if self.storage.get_kv(&username_key).await?.is_some() {
479            return Err(AuthError::validation("Username already exists".to_string()));
480        }
481
482        let email_key = format!("user:email:{}", email);
483        if self.storage.get_kv(&email_key).await?.is_some() {
484            return Err(AuthError::validation("Email already exists".to_string()));
485        }
486
487        let user_id = crate::utils::string::generate_id(Some("user"));
488
489        let password_hash = self.hash_password(password)?;
490
491        let user_data = serde_json::json!({
492            "user_id": user_id,
493            "username": username,
494            "email": email,
495            "password_hash": password_hash,
496            "roles": ["user"],
497            "active": true,
498            "email_verified": false,
499            "created_at": chrono::Utc::now().to_rfc3339(),
500        });
501
502        let user_key = format!("user:{}", user_id);
503        self.storage
504            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
505            .await?;
506
507        self.storage
508            .store_kv(&username_key, user_id.as_bytes(), None)
509            .await?;
510        self.storage
511            .store_kv(&email_key, user_id.as_bytes(), None)
512            .await?;
513
514        // Maintain global user index for admin listing.
515        let index_key = "users:index";
516        let mut ids: Vec<String> = match self.storage.get_kv(index_key).await? {
517            Some(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
518            None => vec![],
519        };
520        ids.push(user_id.clone());
521        if let Ok(idx_json) = serde_json::to_vec(&ids)
522            && let Err(e) = self.storage.store_kv(index_key, &idx_json, None).await
523        {
524            warn!("Failed to update user index during registration: {}", e);
525        }
526
527        // Store the credentials record for verify_login_credentials, hashed
528        // with the same configured algorithm as the user:{id} record above.
529        let creds_key = format!("user:credentials:{}", username);
530        let creds_hash = match self.hash_password(password) {
531            Ok(h) => h,
532            Err(e) => {
533                warn!("Failed to hash credentials for user '{}': {}", username, e);
534                return Ok(user_id);
535            }
536        };
537        let creds_data = serde_json::json!({
538            "user_id": user_id,
539            "username": username,
540            "email": email,
541            "password_hash": creds_hash,
542            "created_at": chrono::Utc::now().to_rfc3339(),
543        });
544        if let Err(e) = self
545            .storage
546            .store_kv(&creds_key, creds_data.to_string().as_bytes(), None)
547            .await
548        {
549            warn!("Failed to store credentials for user '{}': {}", username, e);
550        }
551
552        info!("User '{}' registered successfully", username);
553        Ok(user_id)
554    }
555
556    /// Delete a user and all associated storage records.
557    ///
558    /// # Example
559    /// ```rust,ignore
560    /// um.delete_user("alice").await?;
561    /// ```
562    pub async fn delete_user(&self, username: &str) -> Result<()> {
563        debug!("Deleting user: {}", username);
564
565        let username_key = format!("user:username:{}", username);
566        let user_id_data = self
567            .storage
568            .get_kv(&username_key)
569            .await?
570            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
571
572        let user_id = String::from_utf8(user_id_data)
573            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
574
575        // Remove email reverse-lookup.
576        let user_key = format!("user:{}", user_id);
577        if let Some(user_data_bytes) = self.storage.get_kv(&user_key).await?
578            && let Ok(user_json_str) = String::from_utf8(user_data_bytes)
579            && let Ok(user_data) = serde_json::from_str::<serde_json::Value>(&user_json_str)
580            && let Some(email) = user_data.get("email").and_then(|v| v.as_str())
581            && let Err(e) = self
582                .storage
583                .delete_kv(&format!("user:email:{}", email))
584                .await
585        {
586            warn!(
587                "Failed to delete email index for user '{}': {}",
588                username, e
589            );
590        }
591
592        // Remove from global index.
593        let index_key = "users:index";
594        if let Ok(Some(bytes)) = self.storage.get_kv(index_key).await {
595            let mut ids: Vec<String> = serde_json::from_slice(&bytes).unwrap_or_default();
596            ids.retain(|id| id != &user_id);
597            if let Ok(idx_json) = serde_json::to_vec(&ids)
598                && let Err(e) = self.storage.store_kv(index_key, &idx_json, None).await
599            {
600                warn!(
601                    "Failed to update user index during deletion of '{}': {}",
602                    username, e
603                );
604            }
605        }
606
607        if let Err(e) = self.storage.delete_kv(&user_key).await {
608            warn!("Failed to delete user record for '{}': {}", username, e);
609        }
610        if let Err(e) = self.storage.delete_kv(&username_key).await {
611            warn!("Failed to delete username index for '{}': {}", username, e);
612        }
613        if let Err(e) = self
614            .storage
615            .delete_kv(&format!("user:credentials:{}", username))
616            .await
617        {
618            warn!("Failed to delete credentials for '{}': {}", username, e);
619        }
620        if let Err(e) = self
621            .storage
622            .delete_kv(&format!("user:{}:totp_secret", user_id))
623            .await
624        {
625            warn!("Failed to delete TOTP secret for '{}': {}", username, e);
626        }
627        if let Err(e) = self
628            .storage
629            .delete_kv(&format!("user:{}:backup_codes", user_id))
630            .await
631        {
632            warn!("Failed to delete backup codes for '{}': {}", username, e);
633        }
634
635        info!("User '{}' deleted successfully", username);
636        Ok(())
637    }
638
639    /// Delete a user by canonical user ID.
640    ///
641    /// # Example
642    /// ```rust,ignore
643    /// um.delete_user_by_id("user-1").await?;
644    /// ```
645    pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
646        let username = self.get_username_by_id(user_id).await?;
647        self.delete_user(&username).await
648    }
649
650    /// Update the roles assigned to a user.
651    ///
652    /// # Example
653    /// ```rust,ignore
654    /// um.update_user_roles("user-1", &["admin".into(), "editor".into()]).await?;
655    /// ```
656    pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
657        let user_key = format!("user:{}", user_id);
658        let bytes = self
659            .storage
660            .get_kv(&user_key)
661            .await?
662            .ok_or(AuthError::UserNotFound)?;
663        let mut user_data: serde_json::Value =
664            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
665        user_data["roles"] = serde_json::json!(roles);
666        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
667        self.storage
668            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
669            .await?;
670        info!("Roles updated for user '{}'", user_id);
671        Ok(())
672    }
673
674    /// Enable or disable a user account.
675    ///
676    /// # Example
677    /// ```rust,ignore
678    /// um.set_user_active("user-1", false).await?; // disable
679    /// ```
680    pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
681        let user_key = format!("user:{}", user_id);
682        let bytes = self
683            .storage
684            .get_kv(&user_key)
685            .await?
686            .ok_or(AuthError::UserNotFound)?;
687        let mut user_data: serde_json::Value =
688            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
689        user_data["active"] = serde_json::json!(active);
690        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
691        self.storage
692            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
693            .await?;
694        info!("User '{}' active status set to {}", user_id, active);
695        Ok(())
696    }
697
698    /// Update the email address stored on a user.
699    ///
700    /// # Example
701    /// ```rust,ignore
702    /// um.update_user_email("user-1", "new@example.com").await?;
703    /// ```
704    pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
705        let user_key = format!("user:{}", user_id);
706        let bytes = self
707            .storage
708            .get_kv(&user_key)
709            .await?
710            .ok_or(AuthError::UserNotFound)?;
711        let mut user_data: serde_json::Value =
712            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
713
714        let new_email_key = format!("user:email:{}", email);
715        if let Some(existing_user_id) = self.storage.get_kv(&new_email_key).await? {
716            let existing_user_id = String::from_utf8(existing_user_id)
717                .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {e}")))?;
718            if existing_user_id != user_id {
719                return Err(AuthError::validation("Email already exists".to_string()));
720            }
721        }
722
723        if let Some(old_email) = user_data.get("email").and_then(|value| value.as_str())
724            && old_email != email
725        {
726            self.storage
727                .delete_kv(&format!("user:email:{}", old_email))
728                .await?;
729        }
730
731        user_data["email"] = serde_json::json!(email);
732        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
733
734        self.storage
735            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
736            .await?;
737        self.storage
738            .store_kv(&new_email_key, user_id.as_bytes(), None)
739            .await?;
740
741        Ok(())
742    }
743
744    /// Verify a user's password against the stored hash.
745    ///
746    /// Detects whether the stored hash is bcrypt or Argon2id from its own
747    /// prefix and verifies against that format, independent of the
748    /// currently configured [`PasswordHashAlgorithm`]. This is deliberate:
749    /// changing the configured algorithm must not break verification for
750    /// users whose password was hashed under the old one.
751    ///
752    /// # Example
753    /// ```rust,ignore
754    /// let ok = um.verify_user_password("user-1", "secret").await?;
755    /// assert!(ok);
756    /// ```
757    pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
758        let user_key = format!("user:{}", user_id);
759        let bytes = self
760            .storage
761            .get_kv(&user_key)
762            .await?
763            .ok_or(AuthError::UserNotFound)?;
764        let user_data: serde_json::Value =
765            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
766        let hash = user_data["password_hash"]
767            .as_str()
768            .ok_or_else(|| AuthError::internal("User has no password hash".to_string()))?;
769        verify_password_any_format(password, hash)
770    }
771
772    /// Resolve a user_id to its username.
773    ///
774    /// # Example
775    /// ```rust,ignore
776    /// let name = um.get_username_by_id("user-1").await?;
777    /// ```
778    pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
779        let user_key = format!("user:{}", user_id);
780        let bytes = self
781            .storage
782            .get_kv(&user_key)
783            .await?
784            .ok_or(AuthError::UserNotFound)?;
785        let user_data: serde_json::Value =
786            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
787        user_data["username"]
788            .as_str()
789            .map(|s| s.to_string())
790            .ok_or_else(|| AuthError::internal("User has no username field".to_string()))
791    }
792
793    /// Check whether a username is already taken.
794    ///
795    /// # Example
796    /// ```rust,ignore
797    /// if um.username_exists("alice").await? {
798    ///     println!("taken");
799    /// }
800    /// ```
801    pub async fn username_exists(&self, username: &str) -> Result<bool> {
802        Ok(self
803            .storage
804            .get_kv(&format!("user:username:{}", username))
805            .await?
806            .is_some())
807    }
808
809    /// Check whether an email address is already registered.
810    ///
811    /// # Example
812    /// ```rust,ignore
813    /// if um.email_exists("a@b.com").await? {
814    ///     println!("already registered");
815    /// }
816    /// ```
817    pub async fn email_exists(&self, email: &str) -> Result<bool> {
818        Ok(self
819            .storage
820            .get_kv(&format!("user:email:{}", email))
821            .await?
822            .is_some())
823    }
824
825    /// Fetch raw user data by username.
826    ///
827    /// # Example
828    /// ```rust,ignore
829    /// let data = um.get_user_by_username("alice").await?;
830    /// println!("email: {:?}", data.get("email"));
831    /// ```
832    pub async fn get_user_by_username(
833        &self,
834        username: &str,
835    ) -> Result<HashMap<String, serde_json::Value>> {
836        let username_key = format!("user:username:{}", username);
837        let user_id_data = self
838            .storage
839            .get_kv(&username_key)
840            .await?
841            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
842        let user_id = String::from_utf8(user_id_data)
843            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
844        let user_key = format!("user:{}", user_id);
845        let user_data = self
846            .storage
847            .get_kv(&user_key)
848            .await?
849            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
850        let user_obj: serde_json::Value = serde_json::from_slice(&user_data)
851            .map_err(|e| AuthError::crypto(format!("Failed to parse user data: {}", e)))?;
852        if let Some(obj) = user_obj.as_object() {
853            Ok(obj
854                .into_iter()
855                .map(|(k, v)| (k.clone(), v.clone()))
856                .collect())
857        } else {
858            Err(AuthError::validation(
859                "Invalid user data structure".to_string(),
860            ))
861        }
862    }
863
864    /// Get a sanitised user profile (no password hash) for display/API.
865    ///
866    /// # Example
867    /// ```rust,ignore
868    /// let profile = um.get_user_profile("user-1").await?;
869    /// println!("email: {:?}", profile.email);
870    /// ```
871    pub async fn get_user_profile(
872        &self,
873        user_id: &str,
874    ) -> Result<crate::providers::ProviderProfile> {
875        let user_key = format!("user:{}", user_id);
876        if let Ok(Some(bytes)) = self.storage.get_kv(&user_key).await
877            && let Ok(user_data) = serde_json::from_slice::<serde_json::Value>(&bytes)
878        {
879            let username = user_data["username"].as_str().map(|s| s.to_string());
880            let email = user_data["email"].as_str().map(|s| s.to_string());
881            let name = user_data["name"].as_str().map(|s| s.to_string());
882            let email_verified = user_data["email_verified"].as_bool();
883
884            let mut additional_data = std::collections::HashMap::new();
885            if let Some(obj) = user_data.as_object() {
886                for (k, v) in obj {
887                    match k.as_str() {
888                        "user_id" | "username" | "email" | "name" | "email_verified"
889                        | "password_hash" | "created_at" | "updated_at" => {}
890                        _ => {
891                            additional_data.insert(k.clone(), v.clone());
892                        }
893                    }
894                }
895            }
896
897            return Ok(crate::providers::ProviderProfile {
898                id: Some(user_id.to_string()),
899                provider: Some("local".to_string()),
900                username,
901                name,
902                email,
903                email_verified,
904                picture: None,
905                locale: None,
906                additional_data,
907            });
908        }
909        Err(AuthError::UserNotFound)
910    }
911
912    /// Get a user's roles/scopes from storage, returning `["user"]` as fallback.
913    ///
914    /// # Example
915    /// ```rust,ignore
916    /// let roles = um.get_user_roles("user-1").await?;
917    /// assert!(roles.contains(&"user".to_string()));
918    /// ```
919    pub async fn get_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
920        let user_key = format!("user:{}", user_id);
921        if let Ok(Some(data)) = self.storage.get_kv(&user_key).await
922            && let Ok(v) = serde_json::from_slice::<serde_json::Value>(&data)
923            && let Some(arr) = v.get("roles").and_then(|r| r.as_array())
924        {
925            let roles: Vec<String> = arr
926                .iter()
927                .filter_map(|v| v.as_str().map(String::from))
928                .collect();
929            if !roles.is_empty() {
930                return Ok(roles);
931            }
932        }
933        Ok(vec!["user".to_string()])
934    }
935
936    /// Verify username/password credentials in a timing-safe manner.
937    ///
938    /// Returns `Ok(None)` when the credentials are invalid — a dummy
939    /// verification (under the configured algorithm, against a hash
940    /// precomputed once at construction) is always executed when the
941    /// username is not found, so callers cannot distinguish missing users
942    /// from wrong passwords via timing **for a manager whose stored users
943    /// all hash under the currently configured algorithm**. Returns
944    /// `Ok(Some(result))` on success.
945    ///
946    /// **Known gap: mid-migration timing oracle.** The dummy hash always
947    /// follows the *configured* algorithm, while a real existing user
948    /// verifies under whatever algorithm their own stored hash actually
949    /// is. If a deployment changes its configured algorithm without
950    /// rehashing existing users (this crate never rehashes on login), a
951    /// legacy user's wrong-password check costs their *old* algorithm's
952    /// verify time while an unknown username costs the *new* one's --
953    /// e.g. a Bcrypt-configured manager with legacy Argon2id users shows
954    /// ~39ms for a real wrong-password check vs. ~390ms for an unknown
955    /// username (and the reverse, Argon2-configured with legacy Bcrypt
956    /// users). This is not fixed by this crate and is not fixable without
957    /// rehashing on login (a separate, larger change): the oracle this
958    /// function closes is closed only once every stored user's hash
959    /// matches the currently configured algorithm.
960    ///
961    /// # Example
962    /// ```rust,ignore
963    /// match um.verify_login_credentials("alice", "password123").await? {
964    ///     Some(cred) => println!("user_id={}, mfa={}", cred.user_id, cred.mfa_enabled),
965    ///     None => println!("invalid credentials"),
966    /// }
967    /// ```
968    pub async fn verify_login_credentials(
969        &self,
970        username: &str,
971        password: &str,
972    ) -> Result<Option<CredentialCheckResult>> {
973        if username.is_empty() || password.is_empty() {
974            return Ok(None);
975        }
976
977        let user_key = format!("user:credentials:{username}");
978        let stored_bytes = match self.storage.get_kv(&user_key).await? {
979            Some(bytes) => bytes,
980            None => {
981                // Constant-time defense: perform exactly one verification
982                // under the configured algorithm even for a nonexistent
983                // user, costing the same as a known user with a wrong
984                // password (one verify, below). Verifying against a hash
985                // computed ONCE at construction time (dummy_password_hash),
986                // rather than hashing a fresh password on every lookup, is
987                // the point: hashing here too would cost one hash + one
988                // verify -- roughly double a real wrong-password check --
989                // which is itself a username-enumeration timing oracle.
990                if let Some(dummy_hash) = &self.dummy_password_hash {
991                    let _ = verify_password_any_format(password, dummy_hash);
992                }
993                return Ok(None);
994            }
995        };
996
997        let user_data_str = String::from_utf8(stored_bytes)
998            .map_err(|e| AuthError::internal(format!("Failed to parse user data: {e}")))?;
999        let user_data: serde_json::Value = serde_json::from_str(&user_data_str)
1000            .map_err(|e| AuthError::internal(format!("Failed to parse user JSON: {e}")))?;
1001
1002        let password_hash = user_data["password_hash"].as_str().ok_or_else(|| {
1003            AuthError::internal("Missing password hash in user record".to_string())
1004        })?;
1005
1006        if !verify_password_any_format(password, password_hash).unwrap_or(false) {
1007            return Ok(None);
1008        }
1009
1010        let user_id = user_data["user_id"]
1011            .as_str()
1012            .ok_or_else(|| AuthError::internal("Missing user_id in user record".to_string()))?
1013            .to_string();
1014
1015        // Check whether the account has been deactivated.
1016        let canonical_key = format!("user:{}", user_id);
1017        if let Ok(Some(canonical_bytes)) = self.storage.get_kv(&canonical_key).await
1018            && let Ok(canonical_str) = String::from_utf8(canonical_bytes)
1019            && let Ok(canonical_data) = serde_json::from_str::<serde_json::Value>(&canonical_str)
1020            && !canonical_data["active"].as_bool().unwrap_or(true)
1021        {
1022            return Ok(None);
1023        }
1024
1025        let mfa_enabled = matches!(
1026            self.storage
1027                .get_kv(&format!("mfa_enabled:{}", user_id))
1028                .await,
1029            Ok(Some(_))
1030        );
1031
1032        Ok(Some(CredentialCheckResult {
1033            user_id,
1034            mfa_enabled,
1035        }))
1036    }
1037
1038    /// Update a user's password by username.
1039    ///
1040    /// # Example
1041    /// ```rust,ignore
1042    /// um.update_user_password("alice", "N3wStr0ng!Pass").await?;
1043    /// ```
1044    pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
1045        debug!("Updating password for user: {}", username);
1046
1047        crate::utils::validation::validate_password(new_password)
1048            .map_err(|e| AuthError::validation(format!("Password validation failed: {e}")))?;
1049
1050        let username_key = format!("user:username:{}", username);
1051        let user_id_data = self
1052            .storage
1053            .get_kv(&username_key)
1054            .await?
1055            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
1056        let user_id = String::from_utf8(user_id_data)
1057            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
1058
1059        let user_key = format!("user:{}", user_id);
1060        let user_bytes = self
1061            .storage
1062            .get_kv(&user_key)
1063            .await?
1064            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
1065        let mut user_data: serde_json::Value = serde_json::from_slice(&user_bytes)
1066            .map_err(|e| AuthError::crypto(format!("Failed to parse user data: {}", e)))?;
1067
1068        let password_hash = self.hash_password(new_password)?;
1069        user_data["password_hash"] = serde_json::json!(password_hash);
1070        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
1071        self.storage
1072            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
1073            .await?;
1074
1075        // Update the credentials record used by verify_login_credentials,
1076        // hashed with the same configured algorithm as above.
1077        let creds_key = format!("user:credentials:{}", username);
1078        let creds_hash = self.hash_password(new_password)?;
1079        let creds_bytes =
1080            self.storage.get_kv(&creds_key).await?.ok_or_else(|| {
1081                AuthError::internal("Login credentials record not found".to_string())
1082            })?;
1083        let mut creds: serde_json::Value = serde_json::from_slice(&creds_bytes)
1084            .map_err(|e| AuthError::internal(format!("Failed to parse credentials record: {e}")))?;
1085        creds["password_hash"] = serde_json::json!(creds_hash);
1086        creds["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
1087        self.storage
1088            .store_kv(&creds_key, creds.to_string().as_bytes(), None)
1089            .await?;
1090
1091        info!("Password updated for user: {}", username);
1092        Ok(())
1093    }
1094
1095    /// Update a user password by canonical user ID.
1096    ///
1097    /// # Example
1098    /// ```rust,ignore
1099    /// um.update_user_password_by_id("user-1", "N3wStr0ng!Pass").await?;
1100    /// ```
1101    pub async fn update_user_password_by_id(
1102        &self,
1103        user_id: &str,
1104        new_password: &str,
1105    ) -> Result<()> {
1106        let username = self.get_username_by_id(user_id).await?;
1107        self.update_user_password(&username, new_password).await
1108    }
1109}
1110
1111#[cfg(test)]
1112mod tests {
1113    use super::*;
1114    use crate::storage::MemoryStorage;
1115
1116    fn make_manager() -> UserManager {
1117        UserManager::new(
1118            Arc::new(MemoryStorage::new()),
1119            PasswordHashAlgorithm::Bcrypt,
1120        )
1121    }
1122
1123    fn make_manager_with_algorithm(algorithm: PasswordHashAlgorithm) -> UserManager {
1124        UserManager::new(Arc::new(MemoryStorage::new()), algorithm)
1125    }
1126
1127    // ── register_user ───────────────────────────────────────────────────
1128
1129    #[tokio::test]
1130    async fn test_register_user_success() {
1131        let mgr = make_manager();
1132        let id = mgr
1133            .register_user("alice", "alice@example.com", "StrongP@ss1!")
1134            .await
1135            .unwrap();
1136        assert!(id.starts_with("user"));
1137    }
1138
1139    #[tokio::test]
1140    async fn test_register_user_duplicate_username() {
1141        let mgr = make_manager();
1142        mgr.register_user("bob", "bob@example.com", "StrongP@ss1!")
1143            .await
1144            .unwrap();
1145        let err = mgr
1146            .register_user("bob", "bob2@example.com", "StrongP@ss1!")
1147            .await;
1148        assert!(err.is_err());
1149    }
1150
1151    #[tokio::test]
1152    async fn test_register_user_duplicate_email() {
1153        let mgr = make_manager();
1154        mgr.register_user("carol", "dup@example.com", "StrongP@ss1!")
1155            .await
1156            .unwrap();
1157        let err = mgr
1158            .register_user("carol2", "dup@example.com", "StrongP@ss1!")
1159            .await;
1160        assert!(err.is_err());
1161    }
1162
1163    // ── get_user_info ───────────────────────────────────────────────────
1164
1165    #[tokio::test]
1166    async fn test_get_user_info_success() {
1167        let mgr = make_manager();
1168        let id = mgr
1169            .register_user("dave", "dave@example.com", "StrongP@ss1!")
1170            .await
1171            .unwrap();
1172        let info = mgr.get_user_info(&id).await.unwrap();
1173        assert_eq!(info.username, "dave");
1174        assert!(info.active);
1175    }
1176
1177    #[tokio::test]
1178    async fn test_get_user_info_not_found() {
1179        let mgr = make_manager();
1180        assert!(mgr.get_user_info("nonexistent").await.is_err());
1181    }
1182
1183    // ── user_exists ─────────────────────────────────────────────────────
1184
1185    #[tokio::test]
1186    async fn test_user_exists_true() {
1187        let mgr = make_manager();
1188        let id = mgr
1189            .register_user("eve", "eve@example.com", "StrongP@ss1!")
1190            .await
1191            .unwrap();
1192        assert!(mgr.user_exists(&id).await.unwrap());
1193    }
1194
1195    #[tokio::test]
1196    async fn test_user_exists_false() {
1197        let mgr = make_manager();
1198        assert!(!mgr.user_exists("nobody").await.unwrap());
1199    }
1200
1201    #[tokio::test]
1202    async fn test_user_exists_empty_id() {
1203        let mgr = make_manager();
1204        assert!(!mgr.user_exists("").await.unwrap());
1205    }
1206
1207    // ── delete_user ─────────────────────────────────────────────────────
1208
1209    #[tokio::test]
1210    async fn test_delete_user_success() {
1211        let mgr = make_manager();
1212        let id = mgr
1213            .register_user("frank", "frank@example.com", "StrongP@ss1!")
1214            .await
1215            .unwrap();
1216        mgr.delete_user("frank").await.unwrap();
1217        assert!(!mgr.user_exists(&id).await.unwrap());
1218    }
1219
1220    #[tokio::test]
1221    async fn test_delete_user_not_found() {
1222        let mgr = make_manager();
1223        assert!(mgr.delete_user("ghost").await.is_err());
1224    }
1225
1226    #[tokio::test]
1227    async fn test_delete_user_by_id() {
1228        let mgr = make_manager();
1229        let id = mgr
1230            .register_user("gina", "gina@example.com", "StrongP@ss1!")
1231            .await
1232            .unwrap();
1233        mgr.delete_user_by_id(&id).await.unwrap();
1234        assert!(!mgr.user_exists(&id).await.unwrap());
1235    }
1236
1237    // ── list_users ──────────────────────────────────────────────────────
1238
1239    #[tokio::test]
1240    async fn test_list_users_empty() {
1241        let mgr = make_manager();
1242        let users = mgr.list_users(None, None, false).await.unwrap();
1243        assert!(users.is_empty());
1244    }
1245
1246    #[tokio::test]
1247    async fn test_list_users_with_limit_and_offset() {
1248        let mgr = make_manager();
1249        mgr.register_user("u1", "u1@example.com", "StrongP@ss1!")
1250            .await
1251            .unwrap();
1252        mgr.register_user("u2", "u2@example.com", "StrongP@ss1!")
1253            .await
1254            .unwrap();
1255        mgr.register_user("u3", "u3@example.com", "StrongP@ss1!")
1256            .await
1257            .unwrap();
1258        let page = mgr.list_users(Some(1), Some(1), false).await.unwrap();
1259        assert_eq!(page.len(), 1);
1260    }
1261
1262    // ── verify_user_password ────────────────────────────────────────────
1263
1264    #[tokio::test]
1265    async fn test_verify_password_correct() {
1266        let mgr = make_manager();
1267        let id = mgr
1268            .register_user("hank", "hank@example.com", "StrongP@ss1!")
1269            .await
1270            .unwrap();
1271        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1272    }
1273
1274    #[tokio::test]
1275    async fn test_verify_password_incorrect() {
1276        let mgr = make_manager();
1277        let id = mgr
1278            .register_user("ivan", "ivan@example.com", "StrongP@ss1!")
1279            .await
1280            .unwrap();
1281        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1282    }
1283
1284    #[tokio::test]
1285    async fn test_verify_password_user_not_found() {
1286        let mgr = make_manager();
1287        assert!(mgr.verify_user_password("ghost", "x").await.is_err());
1288    }
1289
1290    #[tokio::test]
1291    async fn test_register_and_verify_round_trips_with_bcrypt_configured() {
1292        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1293        let id = mgr
1294            .register_user("bcrypt_user", "bcrypt_user@example.com", "StrongP@ss1!")
1295            .await
1296            .unwrap();
1297        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1298        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1299    }
1300
1301    #[tokio::test]
1302    async fn test_register_and_verify_round_trips_with_argon2_configured() {
1303        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1304        let id = mgr
1305            .register_user("argon2_user", "argon2_user@example.com", "StrongP@ss1!")
1306            .await
1307            .unwrap();
1308        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1309        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1310    }
1311
1312    #[tokio::test]
1313    async fn test_register_user_honors_configured_algorithm_not_hardcoded_bcrypt() {
1314        // Before this fix, register_user always called bcrypt::hash
1315        // regardless of configuration. Prove the stored hash's own format
1316        // actually reflects PasswordHashAlgorithm::Argon2 -- an Argon2id PHC
1317        // string, not a bcrypt `$2` hash.
1318        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1319        let id = mgr
1320            .register_user("argon2_format", "argon2_format@example.com", "StrongP@ss1!")
1321            .await
1322            .unwrap();
1323        let user_key = format!("user:{}", id);
1324        let bytes = mgr.storage.get_kv(&user_key).await.unwrap().unwrap();
1325        let user_data: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1326        let hash = user_data["password_hash"].as_str().unwrap();
1327        assert!(
1328            hash.starts_with("$argon2"),
1329            "expected an Argon2id PHC hash, got: {hash}"
1330        );
1331    }
1332
1333    #[tokio::test]
1334    async fn test_existing_bcrypt_hash_still_verifies_after_switching_to_argon2() {
1335        // A user registered under the old/Bcrypt-configured manager must
1336        // keep verifying correctly even after the deployment switches its
1337        // configured algorithm to Argon2 -- verification must detect the
1338        // stored hash's actual format, not assume the current config.
1339        let bcrypt_mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1340        let id = bcrypt_mgr
1341            .register_user("legacy_user", "legacy_user@example.com", "StrongP@ss1!")
1342            .await
1343            .unwrap();
1344
1345        // Re-open the same storage under a manager now configured for Argon2.
1346        let argon2_mgr =
1347            UserManager::new(bcrypt_mgr.storage.clone(), PasswordHashAlgorithm::Argon2);
1348        assert!(
1349            argon2_mgr
1350                .verify_user_password(&id, "StrongP@ss1!")
1351                .await
1352                .unwrap(),
1353            "a bcrypt hash created under the old config must still verify after the \
1354             configured algorithm changes"
1355        );
1356    }
1357
1358    #[tokio::test]
1359    async fn test_scrypt_is_rejected_not_silently_substituted() {
1360        // Scrypt has no implementation in this crate yet. Registering must
1361        // fail loudly rather than silently falling back to a different
1362        // algorithm than the one configured.
1363        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Scrypt);
1364        let result = mgr
1365            .register_user("scrypt_user", "scrypt_user@example.com", "StrongP@ss1!")
1366            .await;
1367        assert!(result.is_err());
1368    }
1369
1370    // ── update_user_password ────────────────────────────────────────────
1371
1372    #[tokio::test]
1373    async fn test_update_password() {
1374        let mgr = make_manager();
1375        let id = mgr
1376            .register_user("jack", "jack@example.com", "StrongP@ss1!")
1377            .await
1378            .unwrap();
1379        mgr.update_user_password("jack", "NewStr0ng!Pass")
1380            .await
1381            .unwrap();
1382        assert!(
1383            mgr.verify_user_password(&id, "NewStr0ng!Pass")
1384                .await
1385                .unwrap()
1386        );
1387        assert!(!mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1388    }
1389
1390    #[tokio::test]
1391    async fn test_update_password_user_not_found() {
1392        let mgr = make_manager();
1393        assert!(
1394            mgr.update_user_password("ghost", "NewStr0ng!Pass")
1395                .await
1396                .is_err()
1397        );
1398    }
1399
1400    // ── update_user_roles ───────────────────────────────────────────────
1401
1402    #[tokio::test]
1403    async fn test_update_user_roles() {
1404        let mgr = make_manager();
1405        let id = mgr
1406            .register_user("kate", "kate@example.com", "StrongP@ss1!")
1407            .await
1408            .unwrap();
1409        mgr.update_user_roles(&id, &["admin".into(), "user".into()])
1410            .await
1411            .unwrap();
1412        let info = mgr.get_user_info(&id).await.unwrap();
1413        assert!(info.roles.contains("admin"));
1414    }
1415
1416    #[tokio::test]
1417    async fn test_update_user_roles_not_found() {
1418        let mgr = make_manager();
1419        assert!(
1420            mgr.update_user_roles("ghost", &["admin".into()])
1421                .await
1422                .is_err()
1423        );
1424    }
1425
1426    // ── set_user_active ─────────────────────────────────────────────────
1427
1428    #[tokio::test]
1429    async fn test_set_user_active_disable() {
1430        let mgr = make_manager();
1431        let id = mgr
1432            .register_user("leon", "leon@example.com", "StrongP@ss1!")
1433            .await
1434            .unwrap();
1435        mgr.set_user_active(&id, false).await.unwrap();
1436        let info = mgr.get_user_info(&id).await.unwrap();
1437        assert!(!info.active);
1438    }
1439
1440    #[tokio::test]
1441    async fn test_set_user_active_not_found() {
1442        let mgr = make_manager();
1443        assert!(mgr.set_user_active("ghost", false).await.is_err());
1444    }
1445
1446    // ── update_user_email ───────────────────────────────────────────────
1447
1448    #[tokio::test]
1449    async fn test_update_user_email() {
1450        let mgr = make_manager();
1451        let id = mgr
1452            .register_user("mary", "mary@example.com", "StrongP@ss1!")
1453            .await
1454            .unwrap();
1455        mgr.update_user_email(&id, "mary_new@example.com")
1456            .await
1457            .unwrap();
1458        let info = mgr.get_user_info(&id).await.unwrap();
1459        assert_eq!(info.email.as_deref(), Some("mary_new@example.com"));
1460    }
1461
1462    #[tokio::test]
1463    async fn test_update_user_email_already_taken() {
1464        let mgr = make_manager();
1465        mgr.register_user("n1", "taken@example.com", "StrongP@ss1!")
1466            .await
1467            .unwrap();
1468        let id2 = mgr
1469            .register_user("n2", "n2@example.com", "StrongP@ss1!")
1470            .await
1471            .unwrap();
1472        assert!(
1473            mgr.update_user_email(&id2, "taken@example.com")
1474                .await
1475                .is_err()
1476        );
1477    }
1478
1479    // ── API key operations ──────────────────────────────────────────────
1480
1481    #[tokio::test]
1482    async fn test_create_and_validate_api_key() {
1483        let mgr = make_manager();
1484        let id = mgr
1485            .register_user("oscar", "oscar@example.com", "StrongP@ss1!")
1486            .await
1487            .unwrap();
1488        let key = mgr.create_api_key(&id, None).await.unwrap();
1489        assert!(key.starts_with("ak_"));
1490        let info = mgr.validate_api_key(&key).await.unwrap();
1491        assert_eq!(info.id, id);
1492    }
1493
1494    #[tokio::test]
1495    async fn test_validate_api_key_invalid() {
1496        let mgr = make_manager();
1497        assert!(mgr.validate_api_key("bad_key").await.is_err());
1498    }
1499
1500    #[tokio::test]
1501    async fn test_revoke_api_key() {
1502        let mgr = make_manager();
1503        let id = mgr
1504            .register_user("pat", "pat@example.com", "StrongP@ss1!")
1505            .await
1506            .unwrap();
1507        let key = mgr.create_api_key(&id, None).await.unwrap();
1508        mgr.revoke_api_key(&key).await.unwrap();
1509        assert!(mgr.validate_api_key(&key).await.is_err());
1510    }
1511
1512    #[tokio::test]
1513    async fn test_revoke_api_key_not_found() {
1514        let mgr = make_manager();
1515        assert!(mgr.revoke_api_key("nonexistent").await.is_err());
1516    }
1517
1518    // ── validate_username ───────────────────────────────────────────────
1519
1520    #[tokio::test]
1521    async fn test_validate_username_valid() {
1522        let mgr = make_manager();
1523        assert!(mgr.validate_username("good_user-1").await.unwrap());
1524    }
1525
1526    #[tokio::test]
1527    async fn test_validate_username_too_short() {
1528        let mgr = make_manager();
1529        assert!(!mgr.validate_username("ab").await.unwrap());
1530    }
1531
1532    #[tokio::test]
1533    async fn test_validate_username_special_chars() {
1534        let mgr = make_manager();
1535        assert!(!mgr.validate_username("user@name").await.unwrap());
1536    }
1537
1538    // ── validate_display_name ───────────────────────────────────────────
1539
1540    #[tokio::test]
1541    async fn test_validate_display_name_valid() {
1542        let mgr = make_manager();
1543        assert!(mgr.validate_display_name("Alice Bob").await.unwrap());
1544    }
1545
1546    #[tokio::test]
1547    async fn test_validate_display_name_empty() {
1548        let mgr = make_manager();
1549        assert!(!mgr.validate_display_name("").await.unwrap());
1550    }
1551
1552    #[tokio::test]
1553    async fn test_validate_display_name_only_whitespace() {
1554        let mgr = make_manager();
1555        assert!(!mgr.validate_display_name("   ").await.unwrap());
1556    }
1557
1558    // ── validate_password_strength ──────────────────────────────────────
1559
1560    #[tokio::test]
1561    async fn test_validate_password_strong() {
1562        let mgr = make_manager();
1563        assert!(
1564            mgr.validate_password_strength("C0mpl3x!P@ssw0rd")
1565                .await
1566                .unwrap()
1567        );
1568    }
1569
1570    #[tokio::test]
1571    async fn test_validate_password_weak() {
1572        let mgr = make_manager();
1573        assert!(!mgr.validate_password_strength("123").await.unwrap());
1574    }
1575
1576    // ── validate_user_input ─────────────────────────────────────────────
1577
1578    #[tokio::test]
1579    async fn test_validate_user_input_clean() {
1580        let mgr = make_manager();
1581        assert!(mgr.validate_user_input("Hello World 123").await.unwrap());
1582    }
1583
1584    #[tokio::test]
1585    async fn test_validate_user_input_html_tags() {
1586        let mgr = make_manager();
1587        assert!(
1588            !mgr.validate_user_input("<script>alert(1)</script>")
1589                .await
1590                .unwrap()
1591        );
1592    }
1593
1594    #[tokio::test]
1595    async fn test_validate_user_input_sql_injection() {
1596        let mgr = make_manager();
1597        assert!(
1598            !mgr.validate_user_input("'; drop table users--")
1599                .await
1600                .unwrap()
1601        );
1602    }
1603
1604    #[tokio::test]
1605    async fn test_validate_user_input_template_injection() {
1606        let mgr = make_manager();
1607        assert!(!mgr.validate_user_input("${evil}").await.unwrap());
1608    }
1609
1610    #[tokio::test]
1611    async fn test_validate_user_input_path_traversal() {
1612        let mgr = make_manager();
1613        assert!(!mgr.validate_user_input("../../etc/passwd").await.unwrap());
1614    }
1615
1616    #[tokio::test]
1617    async fn test_validate_user_input_javascript_uri() {
1618        let mgr = make_manager();
1619        assert!(
1620            !mgr.validate_user_input("javascript:alert(1)")
1621                .await
1622                .unwrap()
1623        );
1624    }
1625
1626    #[tokio::test]
1627    async fn test_validate_user_input_empty() {
1628        let mgr = make_manager();
1629        assert!(!mgr.validate_user_input("").await.unwrap());
1630    }
1631
1632    #[tokio::test]
1633    async fn test_validate_user_input_encoded_tags() {
1634        let mgr = make_manager();
1635        assert!(!mgr.validate_user_input("%3cscript%3e").await.unwrap());
1636    }
1637
1638    // ── username_exists / email_exists ───────────────────────────────────
1639
1640    #[tokio::test]
1641    async fn test_username_exists() {
1642        let mgr = make_manager();
1643        mgr.register_user("quinn", "quinn@example.com", "StrongP@ss1!")
1644            .await
1645            .unwrap();
1646        assert!(mgr.username_exists("quinn").await.unwrap());
1647        assert!(!mgr.username_exists("noone").await.unwrap());
1648    }
1649
1650    #[tokio::test]
1651    async fn test_email_exists() {
1652        let mgr = make_manager();
1653        mgr.register_user("ross", "ross@example.com", "StrongP@ss1!")
1654            .await
1655            .unwrap();
1656        assert!(mgr.email_exists("ross@example.com").await.unwrap());
1657        assert!(!mgr.email_exists("nobody@example.com").await.unwrap());
1658    }
1659
1660    // ── get_user_by_username ────────────────────────────────────────────
1661
1662    #[tokio::test]
1663    async fn test_get_user_by_username() {
1664        let mgr = make_manager();
1665        mgr.register_user("sam", "sam@example.com", "StrongP@ss1!")
1666            .await
1667            .unwrap();
1668        let data = mgr.get_user_by_username("sam").await.unwrap();
1669        assert_eq!(data["username"].as_str(), Some("sam"));
1670    }
1671
1672    #[tokio::test]
1673    async fn test_get_user_by_username_not_found() {
1674        let mgr = make_manager();
1675        assert!(mgr.get_user_by_username("ghost").await.is_err());
1676    }
1677
1678    // ── get_user_profile ────────────────────────────────────────────────
1679
1680    #[tokio::test]
1681    async fn test_get_user_profile() {
1682        let mgr = make_manager();
1683        let id = mgr
1684            .register_user("tina", "tina@example.com", "StrongP@ss1!")
1685            .await
1686            .unwrap();
1687        let profile = mgr.get_user_profile(&id).await.unwrap();
1688        assert_eq!(profile.username.as_deref(), Some("tina"));
1689        assert_eq!(profile.email.as_deref(), Some("tina@example.com"));
1690        // password_hash should NOT be in additional_data
1691        assert!(!profile.additional_data.contains_key("password_hash"));
1692    }
1693
1694    #[tokio::test]
1695    async fn test_get_user_profile_not_found() {
1696        let mgr = make_manager();
1697        assert!(mgr.get_user_profile("ghost").await.is_err());
1698    }
1699
1700    // ── get_user_roles ──────────────────────────────────────────────────
1701
1702    #[tokio::test]
1703    async fn test_get_user_roles_default() {
1704        let mgr = make_manager();
1705        let id = mgr
1706            .register_user("uma", "uma@example.com", "StrongP@ss1!")
1707            .await
1708            .unwrap();
1709        let roles = mgr.get_user_roles(&id).await.unwrap();
1710        assert!(roles.contains(&"user".to_string()));
1711    }
1712
1713    #[tokio::test]
1714    async fn test_get_user_roles_not_found_returns_default() {
1715        let mgr = make_manager();
1716        let roles = mgr.get_user_roles("ghost").await.unwrap();
1717        assert_eq!(roles, vec!["user".to_string()]);
1718    }
1719
1720    // ── verify_login_credentials ────────────────────────────────────────
1721
1722    #[tokio::test]
1723    async fn test_verify_login_credentials_success() {
1724        let mgr = make_manager();
1725        mgr.register_user("vera", "vera@example.com", "StrongP@ss1!")
1726            .await
1727            .unwrap();
1728        let result = mgr
1729            .verify_login_credentials("vera", "StrongP@ss1!")
1730            .await
1731            .unwrap();
1732        assert!(result.is_some());
1733        assert!(!result.unwrap().mfa_enabled);
1734    }
1735
1736    #[tokio::test]
1737    async fn test_verify_login_credentials_wrong_password() {
1738        let mgr = make_manager();
1739        mgr.register_user("wanda", "wanda@example.com", "StrongP@ss1!")
1740            .await
1741            .unwrap();
1742        let result = mgr
1743            .verify_login_credentials("wanda", "wrong")
1744            .await
1745            .unwrap();
1746        assert!(result.is_none());
1747    }
1748
1749    #[tokio::test]
1750    async fn test_register_user_credentials_record_honors_bcrypt_configured_algorithm() {
1751        // The user:credentials:{username} record (read by
1752        // verify_login_credentials -- the actual login path) must be hashed
1753        // with the configured algorithm too, not hardcoded to Argon2id
1754        // independent of the user:{id} record.
1755        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1756        mgr.register_user("bcrypt_login", "bcrypt_login@example.com", "StrongP@ss1!")
1757            .await
1758            .unwrap();
1759        let creds_key = "user:credentials:bcrypt_login";
1760        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1761        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1762        let hash = creds["password_hash"].as_str().unwrap();
1763        assert!(
1764            hash.starts_with("$2"),
1765            "expected a bcrypt hash on the login-credentials record, got: {hash}"
1766        );
1767    }
1768
1769    #[tokio::test]
1770    async fn test_register_user_credentials_record_argon2_default_unchanged() {
1771        // Derive the algorithm from AuthConfig::default() itself, not a
1772        // hardcoded PasswordHashAlgorithm::Argon2, so this proves the
1773        // crate's actual default produces an Argon2id credentials record --
1774        // not just that Argon2 behaves correctly when explicitly chosen.
1775        let default_algorithm = crate::config::AuthConfig::default()
1776            .security
1777            .password_hash_algorithm;
1778        assert!(matches!(default_algorithm, PasswordHashAlgorithm::Argon2));
1779        let mgr = make_manager_with_algorithm(default_algorithm);
1780        mgr.register_user("argon2_login", "argon2_login@example.com", "StrongP@ss1!")
1781            .await
1782            .unwrap();
1783        let creds_key = "user:credentials:argon2_login";
1784        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1785        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1786        let hash = creds["password_hash"].as_str().unwrap();
1787        assert!(
1788            hash.starts_with("$argon2"),
1789            "expected an Argon2id hash on the login-credentials record, got: {hash}"
1790        );
1791    }
1792
1793    #[tokio::test]
1794    async fn test_login_round_trip_under_bcrypt_configured_algorithm() {
1795        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1796        mgr.register_user("bcrypt_rt", "bcrypt_rt@example.com", "StrongP@ss1!")
1797            .await
1798            .unwrap();
1799        assert!(
1800            mgr.verify_login_credentials("bcrypt_rt", "StrongP@ss1!")
1801                .await
1802                .unwrap()
1803                .is_some(),
1804            "correct password must log in under Bcrypt"
1805        );
1806        assert!(
1807            mgr.verify_login_credentials("bcrypt_rt", "wrong")
1808                .await
1809                .unwrap()
1810                .is_none(),
1811            "wrong password must be rejected under Bcrypt"
1812        );
1813    }
1814
1815    #[tokio::test]
1816    async fn test_login_round_trip_under_argon2_configured_algorithm() {
1817        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1818        mgr.register_user("argon2_rt", "argon2_rt@example.com", "StrongP@ss1!")
1819            .await
1820            .unwrap();
1821        assert!(
1822            mgr.verify_login_credentials("argon2_rt", "StrongP@ss1!")
1823                .await
1824                .unwrap()
1825                .is_some(),
1826            "correct password must log in under Argon2"
1827        );
1828        assert!(
1829            mgr.verify_login_credentials("argon2_rt", "wrong")
1830                .await
1831                .unwrap()
1832                .is_none(),
1833            "wrong password must be rejected under Argon2"
1834        );
1835    }
1836
1837    #[tokio::test]
1838    async fn test_update_password_updates_credentials_record_under_configured_algorithm() {
1839        // update_password's user:credentials:{username} rewrite must also
1840        // use the configured algorithm, not hardcoded Argon2id.
1841        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1842        mgr.register_user("bcrypt_update", "bcrypt_update@example.com", "StrongP@ss1!")
1843            .await
1844            .unwrap();
1845        mgr.update_user_password("bcrypt_update", "NewerP@ss2!")
1846            .await
1847            .unwrap();
1848
1849        let creds_key = "user:credentials:bcrypt_update";
1850        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1851        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1852        let hash = creds["password_hash"].as_str().unwrap();
1853        assert!(
1854            hash.starts_with("$2"),
1855            "expected the rewritten login-credentials hash to stay bcrypt, got: {hash}"
1856        );
1857        assert!(
1858            mgr.verify_login_credentials("bcrypt_update", "NewerP@ss2!")
1859                .await
1860                .unwrap()
1861                .is_some(),
1862            "login must succeed with the new password after update_password"
1863        );
1864    }
1865
1866    #[tokio::test]
1867    async fn test_verify_login_credentials_unknown_user() {
1868        let mgr = make_manager();
1869        let result = mgr
1870            .verify_login_credentials("ghost", "StrongP@ss1!")
1871            .await
1872            .unwrap();
1873        assert!(result.is_none());
1874    }
1875
1876    #[test]
1877    fn test_dummy_password_hash_is_precomputed_at_construction() {
1878        // Structural proof that the unknown-user path in
1879        // verify_login_credentials costs exactly one verification, not one
1880        // hash plus one verification: the dummy hash must already exist
1881        // right after construction, before any lookup happens at all.
1882        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1883        assert!(
1884            mgr.dummy_password_hash.is_some(),
1885            "dummy_password_hash must be computed at construction time, not lazily on first \
1886             unknown-user lookup"
1887        );
1888
1889        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1890        assert!(mgr.dummy_password_hash.is_some());
1891    }
1892
1893    #[tokio::test]
1894    async fn test_unknown_user_lookup_performs_zero_hashes_and_one_verify() {
1895        // Mutation-proof version of the earlier (removed) test: comparing
1896        // dummy_password_hash before/after a lookup cannot catch a
1897        // regression that reintroduces "hash a fresh dummy, then verify"
1898        // in the None branch while leaving the (now-unused) field alone --
1899        // that mutation calls hash_with_algorithm once and
1900        // verify_password_any_format once, exactly like the buggy
1901        // round-2 code did, and the field itself would never be touched
1902        // either way. Counting both operations directly is what actually
1903        // distinguishes "one verify against a precomputed hash" (the
1904        // fix) from "one hash plus one verify" (the regression this is
1905        // guarding against), which is the actual cost difference that
1906        // created the timing oracle.
1907        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1908        reset_call_counters();
1909
1910        mgr.verify_login_credentials("ghost", "whatever")
1911            .await
1912            .unwrap();
1913
1914        assert_eq!(
1915            call_counts(),
1916            (0, 1),
1917            "the unknown-user path must perform zero hashing operations and exactly one \
1918             verification -- any hashing here (even once) reintroduces the timing oracle \
1919             this test guards against"
1920        );
1921    }
1922
1923    #[tokio::test]
1924    async fn test_known_user_wrong_password_performs_zero_hashes_and_one_verify() {
1925        // Same shape as above, for a real user with a wrong password --
1926        // establishing that the unknown-user path (test above) costs
1927        // exactly the same number of operations as this one, which is the
1928        // actual property a constant-time comparison needs.
1929        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1930        mgr.register_user("real_user", "real_user@example.com", "StrongP@ss1!")
1931            .await
1932            .unwrap();
1933        reset_call_counters();
1934
1935        mgr.verify_login_credentials("real_user", "wrong")
1936            .await
1937            .unwrap();
1938
1939        assert_eq!(call_counts(), (0, 1));
1940    }
1941
1942    #[tokio::test]
1943    async fn test_verify_login_credentials_empty_inputs() {
1944        let mgr = make_manager();
1945        assert!(
1946            mgr.verify_login_credentials("", "pass")
1947                .await
1948                .unwrap()
1949                .is_none()
1950        );
1951        assert!(
1952            mgr.verify_login_credentials("user", "")
1953                .await
1954                .unwrap()
1955                .is_none()
1956        );
1957    }
1958
1959    #[tokio::test]
1960    async fn test_verify_login_credentials_deactivated() {
1961        let mgr = make_manager();
1962        let id = mgr
1963            .register_user("xena", "xena@example.com", "StrongP@ss1!")
1964            .await
1965            .unwrap();
1966        mgr.set_user_active(&id, false).await.unwrap();
1967        let result = mgr
1968            .verify_login_credentials("xena", "StrongP@ss1!")
1969            .await
1970            .unwrap();
1971        assert!(result.is_none());
1972    }
1973
1974    // ── get_username_by_id ──────────────────────────────────────────────
1975
1976    #[tokio::test]
1977    async fn test_get_username_by_id() {
1978        let mgr = make_manager();
1979        let id = mgr
1980            .register_user("yara", "yara@example.com", "StrongP@ss1!")
1981            .await
1982            .unwrap();
1983        let username = mgr.get_username_by_id(&id).await.unwrap();
1984        assert_eq!(username, "yara");
1985    }
1986
1987    #[tokio::test]
1988    async fn test_get_username_by_id_not_found() {
1989        let mgr = make_manager();
1990        assert!(mgr.get_username_by_id("ghost").await.is_err());
1991    }
1992
1993    // ── list_users active_only filter ───────────────────────────────────
1994
1995    #[tokio::test]
1996    async fn test_list_users_active_only() {
1997        let mgr = make_manager();
1998        let id1 = mgr
1999            .register_user("active1", "active1@example.com", "StrongP@ss1!")
2000            .await
2001            .unwrap();
2002        let id2 = mgr
2003            .register_user("inactive1", "inactive1@example.com", "StrongP@ss1!")
2004            .await
2005            .unwrap();
2006        mgr.set_user_active(&id2, false).await.unwrap();
2007
2008        let all = mgr.list_users(None, None, false).await.unwrap();
2009        let active = mgr.list_users(None, None, true).await.unwrap();
2010        assert!(all.len() > active.len());
2011        assert!(active.iter().all(|u| u.active));
2012        // The inactive user should still be in the "all" list
2013        assert!(all.iter().any(|u| u.id == id1));
2014        assert!(all.iter().any(|u| u.id == id2));
2015    }
2016}