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        // Claim the username and the email atomically. The existence checks above are only a
503        // cheap early exit: two simultaneous registrations both pass them, so the claim itself
504        // has to be a compare-and-set, and exactly one caller wins each key.
505        if !self
506            .storage
507            .store_kv_if_absent(&username_key, user_id.as_bytes(), None)
508            .await?
509        {
510            return Err(AuthError::validation("Username already exists".to_string()));
511        }
512        if !self
513            .storage
514            .store_kv_if_absent(&email_key, user_id.as_bytes(), None)
515            .await?
516        {
517            let _ = self.storage.delete_kv(&username_key).await;
518            return Err(AuthError::validation("Email already exists".to_string()));
519        }
520
521        let user_key = format!("user:{}", user_id);
522        if let Err(e) = self
523            .storage
524            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
525            .await
526        {
527            // Do not leave the name and the address claimed by an account that does not exist.
528            let _ = self.storage.delete_kv(&username_key).await;
529            let _ = self.storage.delete_kv(&email_key).await;
530            return Err(e);
531        }
532
533        // Maintain global user index for admin listing.
534        let index_key = "users:index";
535        let mut ids: Vec<String> = match self.storage.get_kv(index_key).await? {
536            Some(bytes) => serde_json::from_slice(&bytes).unwrap_or_default(),
537            None => vec![],
538        };
539        ids.push(user_id.clone());
540        if let Ok(idx_json) = serde_json::to_vec(&ids)
541            && let Err(e) = self.storage.store_kv(index_key, &idx_json, None).await
542        {
543            warn!("Failed to update user index during registration: {}", e);
544        }
545
546        // Store the credentials record for verify_login_credentials, hashed
547        // with the same configured algorithm as the user:{id} record above.
548        let creds_key = format!("user:credentials:{}", username);
549        let creds_hash = match self.hash_password(password) {
550            Ok(h) => h,
551            Err(e) => {
552                warn!("Failed to hash credentials for user '{}': {}", username, e);
553                return Ok(user_id);
554            }
555        };
556        let creds_data = serde_json::json!({
557            "user_id": user_id,
558            "username": username,
559            "email": email,
560            "password_hash": creds_hash,
561            "created_at": chrono::Utc::now().to_rfc3339(),
562        });
563        if let Err(e) = self
564            .storage
565            .store_kv(&creds_key, creds_data.to_string().as_bytes(), None)
566            .await
567        {
568            warn!("Failed to store credentials for user '{}': {}", username, e);
569        }
570
571        info!("User '{}' registered successfully", username);
572        Ok(user_id)
573    }
574
575    /// Delete a user and all associated storage records.
576    ///
577    /// # Example
578    /// ```rust,ignore
579    /// um.delete_user("alice").await?;
580    /// ```
581    pub async fn delete_user(&self, username: &str) -> Result<()> {
582        debug!("Deleting user: {}", username);
583
584        let username_key = format!("user:username:{}", username);
585        let user_id_data = self
586            .storage
587            .get_kv(&username_key)
588            .await?
589            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
590
591        let user_id = String::from_utf8(user_id_data)
592            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
593
594        // Remove email reverse-lookup.
595        let user_key = format!("user:{}", user_id);
596        if let Some(user_data_bytes) = self.storage.get_kv(&user_key).await?
597            && let Ok(user_json_str) = String::from_utf8(user_data_bytes)
598            && let Ok(user_data) = serde_json::from_str::<serde_json::Value>(&user_json_str)
599            && let Some(email) = user_data.get("email").and_then(|v| v.as_str())
600            && let Err(e) = self
601                .storage
602                .delete_kv(&format!("user:email:{}", email))
603                .await
604        {
605            warn!(
606                "Failed to delete email index for user '{}': {}",
607                username, e
608            );
609        }
610
611        // Remove from global index.
612        let index_key = "users:index";
613        if let Ok(Some(bytes)) = self.storage.get_kv(index_key).await {
614            let mut ids: Vec<String> = serde_json::from_slice(&bytes).unwrap_or_default();
615            ids.retain(|id| id != &user_id);
616            if let Ok(idx_json) = serde_json::to_vec(&ids)
617                && let Err(e) = self.storage.store_kv(index_key, &idx_json, None).await
618            {
619                warn!(
620                    "Failed to update user index during deletion of '{}': {}",
621                    username, e
622                );
623            }
624        }
625
626        // Remember that this account existed and was deleted: a missing record alone cannot be
627        // told apart from a federated subject that never had one, and the deleted account's
628        // tokens must stop working.
629        // Without the tombstone the deleted account's tokens would keep working: abort.
630        self.storage
631            .store_kv(&format!("deleted_user:{}", user_id), b"1", None)
632            .await
633            .map_err(|e| {
634                warn!("Failed to record the deletion of '{}': {}", username, e);
635                e
636            })?;
637        if let Err(e) = self.storage.delete_kv(&user_key).await {
638            warn!("Failed to delete user record for '{}': {}", username, e);
639        }
640        if let Err(e) = self.storage.delete_kv(&username_key).await {
641            warn!("Failed to delete username index for '{}': {}", username, e);
642        }
643        if let Err(e) = self
644            .storage
645            .delete_kv(&format!("user:credentials:{}", username))
646            .await
647        {
648            warn!("Failed to delete credentials for '{}': {}", username, e);
649        }
650        if let Err(e) = self
651            .storage
652            .delete_kv(&format!("user:{}:totp_secret", user_id))
653            .await
654        {
655            warn!("Failed to delete TOTP secret for '{}': {}", username, e);
656        }
657        if let Err(e) = self
658            .storage
659            .delete_kv(&format!("user:{}:backup_codes", user_id))
660            .await
661        {
662            warn!("Failed to delete backup codes for '{}': {}", username, e);
663        }
664
665        info!("User '{}' deleted successfully", username);
666        Ok(())
667    }
668
669    /// Delete a user by canonical user ID.
670    ///
671    /// # Example
672    /// ```rust,ignore
673    /// um.delete_user_by_id("user-1").await?;
674    /// ```
675    pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
676        let username = self.get_username_by_id(user_id).await?;
677        self.delete_user(&username).await
678    }
679
680    /// Update the roles assigned to a user.
681    ///
682    /// # Example
683    /// ```rust,ignore
684    /// um.update_user_roles("user-1", &["admin".into(), "editor".into()]).await?;
685    /// ```
686    pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
687        let user_key = format!("user:{}", user_id);
688        let bytes = self
689            .storage
690            .get_kv(&user_key)
691            .await?
692            .ok_or(AuthError::UserNotFound)?;
693        let mut user_data: serde_json::Value =
694            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
695        user_data["roles"] = serde_json::json!(roles);
696        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
697        self.storage
698            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
699            .await?;
700        info!("Roles updated for user '{}'", user_id);
701        Ok(())
702    }
703
704    /// Enable or disable a user account.
705    ///
706    /// # Example
707    /// ```rust,ignore
708    /// um.set_user_active("user-1", false).await?; // disable
709    /// ```
710    pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
711        let user_key = format!("user:{}", user_id);
712        let bytes = self
713            .storage
714            .get_kv(&user_key)
715            .await?
716            .ok_or(AuthError::UserNotFound)?;
717        let mut user_data: serde_json::Value =
718            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
719        user_data["active"] = serde_json::json!(active);
720        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
721        self.storage
722            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
723            .await?;
724        info!("User '{}' active status set to {}", user_id, active);
725        Ok(())
726    }
727
728    /// Update the email address stored on a user.
729    ///
730    /// # Example
731    /// ```rust,ignore
732    /// um.update_user_email("user-1", "new@example.com").await?;
733    /// ```
734    pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
735        let user_key = format!("user:{}", user_id);
736        let bytes = self
737            .storage
738            .get_kv(&user_key)
739            .await?
740            .ok_or(AuthError::UserNotFound)?;
741        let mut user_data: serde_json::Value =
742            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
743
744        let new_email_key = format!("user:email:{}", email);
745        if let Some(existing_user_id) = self.storage.get_kv(&new_email_key).await? {
746            let existing_user_id = String::from_utf8(existing_user_id)
747                .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {e}")))?;
748            if existing_user_id != user_id {
749                return Err(AuthError::validation("Email already exists".to_string()));
750            }
751        }
752
753        if let Some(old_email) = user_data.get("email").and_then(|value| value.as_str())
754            && old_email != email
755        {
756            self.storage
757                .delete_kv(&format!("user:email:{}", old_email))
758                .await?;
759        }
760
761        user_data["email"] = serde_json::json!(email);
762        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
763
764        self.storage
765            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
766            .await?;
767        self.storage
768            .store_kv(&new_email_key, user_id.as_bytes(), None)
769            .await?;
770
771        Ok(())
772    }
773
774    /// Verify a user's password against the stored hash.
775    ///
776    /// Detects whether the stored hash is bcrypt or Argon2id from its own
777    /// prefix and verifies against that format, independent of the
778    /// currently configured [`PasswordHashAlgorithm`]. This is deliberate:
779    /// changing the configured algorithm must not break verification for
780    /// users whose password was hashed under the old one.
781    ///
782    /// # Example
783    /// ```rust,ignore
784    /// let ok = um.verify_user_password("user-1", "secret").await?;
785    /// assert!(ok);
786    /// ```
787    pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
788        let user_key = format!("user:{}", user_id);
789        let bytes = self
790            .storage
791            .get_kv(&user_key)
792            .await?
793            .ok_or(AuthError::UserNotFound)?;
794        let user_data: serde_json::Value =
795            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
796        let hash = user_data["password_hash"]
797            .as_str()
798            .ok_or_else(|| AuthError::internal("User has no password hash".to_string()))?;
799        verify_password_any_format(password, hash)
800    }
801
802    /// Resolve a user_id to its username.
803    ///
804    /// # Example
805    /// ```rust,ignore
806    /// let name = um.get_username_by_id("user-1").await?;
807    /// ```
808    pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
809        let user_key = format!("user:{}", user_id);
810        let bytes = self
811            .storage
812            .get_kv(&user_key)
813            .await?
814            .ok_or(AuthError::UserNotFound)?;
815        let user_data: serde_json::Value =
816            serde_json::from_slice(&bytes).map_err(|e| AuthError::crypto(format!("{e}")))?;
817        user_data["username"]
818            .as_str()
819            .map(|s| s.to_string())
820            .ok_or_else(|| AuthError::internal("User has no username field".to_string()))
821    }
822
823    /// Check whether a username is already taken.
824    ///
825    /// # Example
826    /// ```rust,ignore
827    /// if um.username_exists("alice").await? {
828    ///     println!("taken");
829    /// }
830    /// ```
831    pub async fn username_exists(&self, username: &str) -> Result<bool> {
832        Ok(self
833            .storage
834            .get_kv(&format!("user:username:{}", username))
835            .await?
836            .is_some())
837    }
838
839    /// Check whether an email address is already registered.
840    ///
841    /// # Example
842    /// ```rust,ignore
843    /// if um.email_exists("a@b.com").await? {
844    ///     println!("already registered");
845    /// }
846    /// ```
847    pub async fn email_exists(&self, email: &str) -> Result<bool> {
848        Ok(self
849            .storage
850            .get_kv(&format!("user:email:{}", email))
851            .await?
852            .is_some())
853    }
854
855    /// Fetch raw user data by username.
856    ///
857    /// # Example
858    /// ```rust,ignore
859    /// let data = um.get_user_by_username("alice").await?;
860    /// println!("email: {:?}", data.get("email"));
861    /// ```
862    pub async fn get_user_by_username(
863        &self,
864        username: &str,
865    ) -> Result<HashMap<String, serde_json::Value>> {
866        let username_key = format!("user:username:{}", username);
867        let user_id_data = self
868            .storage
869            .get_kv(&username_key)
870            .await?
871            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
872        let user_id = String::from_utf8(user_id_data)
873            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
874        let user_key = format!("user:{}", user_id);
875        let user_data = self
876            .storage
877            .get_kv(&user_key)
878            .await?
879            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
880        let user_obj: serde_json::Value = serde_json::from_slice(&user_data)
881            .map_err(|e| AuthError::crypto(format!("Failed to parse user data: {}", e)))?;
882        if let Some(obj) = user_obj.as_object() {
883            Ok(obj
884                .into_iter()
885                .map(|(k, v)| (k.clone(), v.clone()))
886                .collect())
887        } else {
888            Err(AuthError::validation(
889                "Invalid user data structure".to_string(),
890            ))
891        }
892    }
893
894    /// Get a sanitised user profile (no password hash) for display/API.
895    ///
896    /// # Example
897    /// ```rust,ignore
898    /// let profile = um.get_user_profile("user-1").await?;
899    /// println!("email: {:?}", profile.email);
900    /// ```
901    pub async fn get_user_profile(
902        &self,
903        user_id: &str,
904    ) -> Result<crate::providers::ProviderProfile> {
905        let user_key = format!("user:{}", user_id);
906        if let Ok(Some(bytes)) = self.storage.get_kv(&user_key).await
907            && let Ok(user_data) = serde_json::from_slice::<serde_json::Value>(&bytes)
908        {
909            let username = user_data["username"].as_str().map(|s| s.to_string());
910            let email = user_data["email"].as_str().map(|s| s.to_string());
911            let name = user_data["name"].as_str().map(|s| s.to_string());
912            let email_verified = user_data["email_verified"].as_bool();
913
914            let mut additional_data = std::collections::HashMap::new();
915            if let Some(obj) = user_data.as_object() {
916                for (k, v) in obj {
917                    match k.as_str() {
918                        "user_id" | "username" | "email" | "name" | "email_verified"
919                        | "password_hash" | "created_at" | "updated_at" => {}
920                        _ => {
921                            additional_data.insert(k.clone(), v.clone());
922                        }
923                    }
924                }
925            }
926
927            return Ok(crate::providers::ProviderProfile {
928                id: Some(user_id.to_string()),
929                provider: Some("local".to_string()),
930                username,
931                name,
932                email,
933                email_verified,
934                picture: None,
935                locale: None,
936                additional_data,
937            });
938        }
939        Err(AuthError::UserNotFound)
940    }
941
942    /// Get a user's roles/scopes from storage, returning `["user"]` as fallback.
943    ///
944    /// # Example
945    /// ```rust,ignore
946    /// let roles = um.get_user_roles("user-1").await?;
947    /// assert!(roles.contains(&"user".to_string()));
948    /// ```
949    pub async fn get_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
950        let user_key = format!("user:{}", user_id);
951        if let Ok(Some(data)) = self.storage.get_kv(&user_key).await
952            && let Ok(v) = serde_json::from_slice::<serde_json::Value>(&data)
953            && let Some(arr) = v.get("roles").and_then(|r| r.as_array())
954        {
955            let roles: Vec<String> = arr
956                .iter()
957                .filter_map(|v| v.as_str().map(String::from))
958                .collect();
959            if !roles.is_empty() {
960                return Ok(roles);
961            }
962        }
963        Ok(vec!["user".to_string()])
964    }
965
966    /// Verify username/password credentials in a timing-safe manner.
967    ///
968    /// Returns `Ok(None)` when the credentials are invalid — a dummy
969    /// verification (under the configured algorithm, against a hash
970    /// precomputed once at construction) is always executed when the
971    /// username is not found, so callers cannot distinguish missing users
972    /// from wrong passwords via timing **for a manager whose stored users
973    /// all hash under the currently configured algorithm**. Returns
974    /// `Ok(Some(result))` on success.
975    ///
976    /// **Known gap: mid-migration timing oracle.** The dummy hash always
977    /// follows the *configured* algorithm, while a real existing user
978    /// verifies under whatever algorithm their own stored hash actually
979    /// is. If a deployment changes its configured algorithm without
980    /// rehashing existing users (this crate never rehashes on login), a
981    /// legacy user's wrong-password check costs their *old* algorithm's
982    /// verify time while an unknown username costs the *new* one's --
983    /// e.g. a Bcrypt-configured manager with legacy Argon2id users shows
984    /// ~39ms for a real wrong-password check vs. ~390ms for an unknown
985    /// username (and the reverse, Argon2-configured with legacy Bcrypt
986    /// users). This is not fixed by this crate and is not fixable without
987    /// rehashing on login (a separate, larger change): the oracle this
988    /// function closes is closed only once every stored user's hash
989    /// matches the currently configured algorithm.
990    ///
991    /// # Example
992    /// ```rust,ignore
993    /// match um.verify_login_credentials("alice", "password123").await? {
994    ///     Some(cred) => println!("user_id={}, mfa={}", cred.user_id, cred.mfa_enabled),
995    ///     None => println!("invalid credentials"),
996    /// }
997    /// ```
998    pub async fn verify_login_credentials(
999        &self,
1000        username: &str,
1001        password: &str,
1002    ) -> Result<Option<CredentialCheckResult>> {
1003        if username.is_empty() || password.is_empty() {
1004            return Ok(None);
1005        }
1006
1007        let user_key = format!("user:credentials:{username}");
1008        let stored_bytes = match self.storage.get_kv(&user_key).await? {
1009            Some(bytes) => bytes,
1010            None => {
1011                // Constant-time defense: perform exactly one verification
1012                // under the configured algorithm even for a nonexistent
1013                // user, costing the same as a known user with a wrong
1014                // password (one verify, below). Verifying against a hash
1015                // computed ONCE at construction time (dummy_password_hash),
1016                // rather than hashing a fresh password on every lookup, is
1017                // the point: hashing here too would cost one hash + one
1018                // verify -- roughly double a real wrong-password check --
1019                // which is itself a username-enumeration timing oracle.
1020                if let Some(dummy_hash) = &self.dummy_password_hash {
1021                    let _ = verify_password_any_format(password, dummy_hash);
1022                }
1023                return Ok(None);
1024            }
1025        };
1026
1027        let user_data_str = String::from_utf8(stored_bytes)
1028            .map_err(|e| AuthError::internal(format!("Failed to parse user data: {e}")))?;
1029        let user_data: serde_json::Value = serde_json::from_str(&user_data_str)
1030            .map_err(|e| AuthError::internal(format!("Failed to parse user JSON: {e}")))?;
1031
1032        let password_hash = user_data["password_hash"].as_str().ok_or_else(|| {
1033            AuthError::internal("Missing password hash in user record".to_string())
1034        })?;
1035
1036        if !verify_password_any_format(password, password_hash).unwrap_or(false) {
1037            return Ok(None);
1038        }
1039
1040        let user_id = user_data["user_id"]
1041            .as_str()
1042            .ok_or_else(|| AuthError::internal("Missing user_id in user record".to_string()))?
1043            .to_string();
1044
1045        // Check whether the account has been deactivated.
1046        let canonical_key = format!("user:{}", user_id);
1047        if let Ok(Some(canonical_bytes)) = self.storage.get_kv(&canonical_key).await
1048            && let Ok(canonical_str) = String::from_utf8(canonical_bytes)
1049            && let Ok(canonical_data) = serde_json::from_str::<serde_json::Value>(&canonical_str)
1050            && !canonical_data["active"].as_bool().unwrap_or(true)
1051        {
1052            return Ok(None);
1053        }
1054
1055        let mfa_enabled = matches!(
1056            self.storage
1057                .get_kv(&format!("mfa_enabled:{}", user_id))
1058                .await,
1059            Ok(Some(_))
1060        );
1061
1062        Ok(Some(CredentialCheckResult {
1063            user_id,
1064            mfa_enabled,
1065        }))
1066    }
1067
1068    /// Update a user's password by username.
1069    ///
1070    /// # Example
1071    /// ```rust,ignore
1072    /// um.update_user_password("alice", "N3wStr0ng!Pass").await?;
1073    /// ```
1074    pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
1075        debug!("Updating password for user: {}", username);
1076
1077        crate::utils::validation::validate_password(new_password)
1078            .map_err(|e| AuthError::validation(format!("Password validation failed: {e}")))?;
1079
1080        let username_key = format!("user:username:{}", username);
1081        let user_id_data = self
1082            .storage
1083            .get_kv(&username_key)
1084            .await?
1085            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
1086        let user_id = String::from_utf8(user_id_data)
1087            .map_err(|e| AuthError::crypto(format!("Invalid user ID format: {}", e)))?;
1088
1089        let user_key = format!("user:{}", user_id);
1090        let user_bytes = self
1091            .storage
1092            .get_kv(&user_key)
1093            .await?
1094            .ok_or_else(|| AuthError::validation("User not found".to_string()))?;
1095        let mut user_data: serde_json::Value = serde_json::from_slice(&user_bytes)
1096            .map_err(|e| AuthError::crypto(format!("Failed to parse user data: {}", e)))?;
1097
1098        let password_hash = self.hash_password(new_password)?;
1099        user_data["password_hash"] = serde_json::json!(password_hash);
1100        user_data["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
1101        self.storage
1102            .store_kv(&user_key, user_data.to_string().as_bytes(), None)
1103            .await?;
1104
1105        // Update the credentials record used by verify_login_credentials,
1106        // hashed with the same configured algorithm as above.
1107        let creds_key = format!("user:credentials:{}", username);
1108        let creds_hash = self.hash_password(new_password)?;
1109        let creds_bytes =
1110            self.storage.get_kv(&creds_key).await?.ok_or_else(|| {
1111                AuthError::internal("Login credentials record not found".to_string())
1112            })?;
1113        let mut creds: serde_json::Value = serde_json::from_slice(&creds_bytes)
1114            .map_err(|e| AuthError::internal(format!("Failed to parse credentials record: {e}")))?;
1115        creds["password_hash"] = serde_json::json!(creds_hash);
1116        creds["updated_at"] = serde_json::json!(chrono::Utc::now().to_rfc3339());
1117        self.storage
1118            .store_kv(&creds_key, creds.to_string().as_bytes(), None)
1119            .await?;
1120
1121        info!("Password updated for user: {}", username);
1122        Ok(())
1123    }
1124
1125    /// Update a user password by canonical user ID.
1126    ///
1127    /// # Example
1128    /// ```rust,ignore
1129    /// um.update_user_password_by_id("user-1", "N3wStr0ng!Pass").await?;
1130    /// ```
1131    pub async fn update_user_password_by_id(
1132        &self,
1133        user_id: &str,
1134        new_password: &str,
1135    ) -> Result<()> {
1136        let username = self.get_username_by_id(user_id).await?;
1137        self.update_user_password(&username, new_password).await
1138    }
1139}
1140
1141#[cfg(test)]
1142mod tests {
1143    use super::*;
1144    use crate::storage::MemoryStorage;
1145
1146    fn make_manager() -> UserManager {
1147        UserManager::new(
1148            Arc::new(MemoryStorage::new()),
1149            PasswordHashAlgorithm::Bcrypt,
1150        )
1151    }
1152
1153    fn make_manager_with_algorithm(algorithm: PasswordHashAlgorithm) -> UserManager {
1154        UserManager::new(Arc::new(MemoryStorage::new()), algorithm)
1155    }
1156
1157    // ── register_user ───────────────────────────────────────────────────
1158
1159    #[tokio::test]
1160    async fn test_register_user_success() {
1161        let mgr = make_manager();
1162        let id = mgr
1163            .register_user("alice", "alice@example.com", "StrongP@ss1!")
1164            .await
1165            .unwrap();
1166        assert!(id.starts_with("user"));
1167    }
1168
1169    #[tokio::test]
1170    async fn test_register_user_duplicate_username() {
1171        let mgr = make_manager();
1172        mgr.register_user("bob", "bob@example.com", "StrongP@ss1!")
1173            .await
1174            .unwrap();
1175        let err = mgr
1176            .register_user("bob", "bob2@example.com", "StrongP@ss1!")
1177            .await;
1178        assert!(err.is_err());
1179    }
1180
1181    #[tokio::test]
1182    async fn test_register_user_duplicate_email() {
1183        let mgr = make_manager();
1184        mgr.register_user("carol", "dup@example.com", "StrongP@ss1!")
1185            .await
1186            .unwrap();
1187        let err = mgr
1188            .register_user("carol2", "dup@example.com", "StrongP@ss1!")
1189            .await;
1190        assert!(err.is_err());
1191    }
1192
1193    // ── get_user_info ───────────────────────────────────────────────────
1194
1195    #[tokio::test]
1196    async fn test_get_user_info_success() {
1197        let mgr = make_manager();
1198        let id = mgr
1199            .register_user("dave", "dave@example.com", "StrongP@ss1!")
1200            .await
1201            .unwrap();
1202        let info = mgr.get_user_info(&id).await.unwrap();
1203        assert_eq!(info.username, "dave");
1204        assert!(info.active);
1205    }
1206
1207    #[tokio::test]
1208    async fn test_get_user_info_not_found() {
1209        let mgr = make_manager();
1210        assert!(mgr.get_user_info("nonexistent").await.is_err());
1211    }
1212
1213    // ── user_exists ─────────────────────────────────────────────────────
1214
1215    #[tokio::test]
1216    async fn test_user_exists_true() {
1217        let mgr = make_manager();
1218        let id = mgr
1219            .register_user("eve", "eve@example.com", "StrongP@ss1!")
1220            .await
1221            .unwrap();
1222        assert!(mgr.user_exists(&id).await.unwrap());
1223    }
1224
1225    #[tokio::test]
1226    async fn test_user_exists_false() {
1227        let mgr = make_manager();
1228        assert!(!mgr.user_exists("nobody").await.unwrap());
1229    }
1230
1231    #[tokio::test]
1232    async fn test_user_exists_empty_id() {
1233        let mgr = make_manager();
1234        assert!(!mgr.user_exists("").await.unwrap());
1235    }
1236
1237    // ── delete_user ─────────────────────────────────────────────────────
1238
1239    #[tokio::test]
1240    async fn test_delete_user_success() {
1241        let mgr = make_manager();
1242        let id = mgr
1243            .register_user("frank", "frank@example.com", "StrongP@ss1!")
1244            .await
1245            .unwrap();
1246        mgr.delete_user("frank").await.unwrap();
1247        assert!(!mgr.user_exists(&id).await.unwrap());
1248    }
1249
1250    #[tokio::test]
1251    async fn test_delete_user_not_found() {
1252        let mgr = make_manager();
1253        assert!(mgr.delete_user("ghost").await.is_err());
1254    }
1255
1256    #[tokio::test]
1257    async fn test_delete_user_by_id() {
1258        let mgr = make_manager();
1259        let id = mgr
1260            .register_user("gina", "gina@example.com", "StrongP@ss1!")
1261            .await
1262            .unwrap();
1263        mgr.delete_user_by_id(&id).await.unwrap();
1264        assert!(!mgr.user_exists(&id).await.unwrap());
1265    }
1266
1267    // ── list_users ──────────────────────────────────────────────────────
1268
1269    #[tokio::test]
1270    async fn test_list_users_empty() {
1271        let mgr = make_manager();
1272        let users = mgr.list_users(None, None, false).await.unwrap();
1273        assert!(users.is_empty());
1274    }
1275
1276    #[tokio::test]
1277    async fn test_list_users_with_limit_and_offset() {
1278        let mgr = make_manager();
1279        mgr.register_user("u1", "u1@example.com", "StrongP@ss1!")
1280            .await
1281            .unwrap();
1282        mgr.register_user("u2", "u2@example.com", "StrongP@ss1!")
1283            .await
1284            .unwrap();
1285        mgr.register_user("u3", "u3@example.com", "StrongP@ss1!")
1286            .await
1287            .unwrap();
1288        let page = mgr.list_users(Some(1), Some(1), false).await.unwrap();
1289        assert_eq!(page.len(), 1);
1290    }
1291
1292    // ── verify_user_password ────────────────────────────────────────────
1293
1294    #[tokio::test]
1295    async fn test_verify_password_correct() {
1296        let mgr = make_manager();
1297        let id = mgr
1298            .register_user("hank", "hank@example.com", "StrongP@ss1!")
1299            .await
1300            .unwrap();
1301        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1302    }
1303
1304    #[tokio::test]
1305    async fn test_verify_password_incorrect() {
1306        let mgr = make_manager();
1307        let id = mgr
1308            .register_user("ivan", "ivan@example.com", "StrongP@ss1!")
1309            .await
1310            .unwrap();
1311        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1312    }
1313
1314    #[tokio::test]
1315    async fn test_verify_password_user_not_found() {
1316        let mgr = make_manager();
1317        assert!(mgr.verify_user_password("ghost", "x").await.is_err());
1318    }
1319
1320    #[tokio::test]
1321    async fn test_register_and_verify_round_trips_with_bcrypt_configured() {
1322        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1323        let id = mgr
1324            .register_user("bcrypt_user", "bcrypt_user@example.com", "StrongP@ss1!")
1325            .await
1326            .unwrap();
1327        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1328        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1329    }
1330
1331    #[tokio::test]
1332    async fn test_register_and_verify_round_trips_with_argon2_configured() {
1333        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1334        let id = mgr
1335            .register_user("argon2_user", "argon2_user@example.com", "StrongP@ss1!")
1336            .await
1337            .unwrap();
1338        assert!(mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1339        assert!(!mgr.verify_user_password(&id, "wrong").await.unwrap());
1340    }
1341
1342    #[tokio::test]
1343    async fn test_register_user_honors_configured_algorithm_not_hardcoded_bcrypt() {
1344        // Before this fix, register_user always called bcrypt::hash
1345        // regardless of configuration. Prove the stored hash's own format
1346        // actually reflects PasswordHashAlgorithm::Argon2 -- an Argon2id PHC
1347        // string, not a bcrypt `$2` hash.
1348        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1349        let id = mgr
1350            .register_user("argon2_format", "argon2_format@example.com", "StrongP@ss1!")
1351            .await
1352            .unwrap();
1353        let user_key = format!("user:{}", id);
1354        let bytes = mgr.storage.get_kv(&user_key).await.unwrap().unwrap();
1355        let user_data: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1356        let hash = user_data["password_hash"].as_str().unwrap();
1357        assert!(
1358            hash.starts_with("$argon2"),
1359            "expected an Argon2id PHC hash, got: {hash}"
1360        );
1361    }
1362
1363    #[tokio::test]
1364    async fn test_existing_bcrypt_hash_still_verifies_after_switching_to_argon2() {
1365        // A user registered under the old/Bcrypt-configured manager must
1366        // keep verifying correctly even after the deployment switches its
1367        // configured algorithm to Argon2 -- verification must detect the
1368        // stored hash's actual format, not assume the current config.
1369        let bcrypt_mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1370        let id = bcrypt_mgr
1371            .register_user("legacy_user", "legacy_user@example.com", "StrongP@ss1!")
1372            .await
1373            .unwrap();
1374
1375        // Re-open the same storage under a manager now configured for Argon2.
1376        let argon2_mgr =
1377            UserManager::new(bcrypt_mgr.storage.clone(), PasswordHashAlgorithm::Argon2);
1378        assert!(
1379            argon2_mgr
1380                .verify_user_password(&id, "StrongP@ss1!")
1381                .await
1382                .unwrap(),
1383            "a bcrypt hash created under the old config must still verify after the \
1384             configured algorithm changes"
1385        );
1386    }
1387
1388    #[tokio::test]
1389    async fn test_scrypt_is_rejected_not_silently_substituted() {
1390        // Scrypt has no implementation in this crate yet. Registering must
1391        // fail loudly rather than silently falling back to a different
1392        // algorithm than the one configured.
1393        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Scrypt);
1394        let result = mgr
1395            .register_user("scrypt_user", "scrypt_user@example.com", "StrongP@ss1!")
1396            .await;
1397        assert!(result.is_err());
1398    }
1399
1400    // ── update_user_password ────────────────────────────────────────────
1401
1402    #[tokio::test]
1403    async fn test_update_password() {
1404        let mgr = make_manager();
1405        let id = mgr
1406            .register_user("jack", "jack@example.com", "StrongP@ss1!")
1407            .await
1408            .unwrap();
1409        mgr.update_user_password("jack", "NewStr0ng!Pass")
1410            .await
1411            .unwrap();
1412        assert!(
1413            mgr.verify_user_password(&id, "NewStr0ng!Pass")
1414                .await
1415                .unwrap()
1416        );
1417        assert!(!mgr.verify_user_password(&id, "StrongP@ss1!").await.unwrap());
1418    }
1419
1420    #[tokio::test]
1421    async fn test_update_password_user_not_found() {
1422        let mgr = make_manager();
1423        assert!(
1424            mgr.update_user_password("ghost", "NewStr0ng!Pass")
1425                .await
1426                .is_err()
1427        );
1428    }
1429
1430    // ── update_user_roles ───────────────────────────────────────────────
1431
1432    #[tokio::test]
1433    async fn test_update_user_roles() {
1434        let mgr = make_manager();
1435        let id = mgr
1436            .register_user("kate", "kate@example.com", "StrongP@ss1!")
1437            .await
1438            .unwrap();
1439        mgr.update_user_roles(&id, &["admin".into(), "user".into()])
1440            .await
1441            .unwrap();
1442        let info = mgr.get_user_info(&id).await.unwrap();
1443        assert!(info.roles.contains("admin"));
1444    }
1445
1446    #[tokio::test]
1447    async fn test_update_user_roles_not_found() {
1448        let mgr = make_manager();
1449        assert!(
1450            mgr.update_user_roles("ghost", &["admin".into()])
1451                .await
1452                .is_err()
1453        );
1454    }
1455
1456    // ── set_user_active ─────────────────────────────────────────────────
1457
1458    #[tokio::test]
1459    async fn test_set_user_active_disable() {
1460        let mgr = make_manager();
1461        let id = mgr
1462            .register_user("leon", "leon@example.com", "StrongP@ss1!")
1463            .await
1464            .unwrap();
1465        mgr.set_user_active(&id, false).await.unwrap();
1466        let info = mgr.get_user_info(&id).await.unwrap();
1467        assert!(!info.active);
1468    }
1469
1470    #[tokio::test]
1471    async fn test_set_user_active_not_found() {
1472        let mgr = make_manager();
1473        assert!(mgr.set_user_active("ghost", false).await.is_err());
1474    }
1475
1476    // ── update_user_email ───────────────────────────────────────────────
1477
1478    #[tokio::test]
1479    async fn test_update_user_email() {
1480        let mgr = make_manager();
1481        let id = mgr
1482            .register_user("mary", "mary@example.com", "StrongP@ss1!")
1483            .await
1484            .unwrap();
1485        mgr.update_user_email(&id, "mary_new@example.com")
1486            .await
1487            .unwrap();
1488        let info = mgr.get_user_info(&id).await.unwrap();
1489        assert_eq!(info.email.as_deref(), Some("mary_new@example.com"));
1490    }
1491
1492    #[tokio::test]
1493    async fn test_update_user_email_already_taken() {
1494        let mgr = make_manager();
1495        mgr.register_user("n1", "taken@example.com", "StrongP@ss1!")
1496            .await
1497            .unwrap();
1498        let id2 = mgr
1499            .register_user("n2", "n2@example.com", "StrongP@ss1!")
1500            .await
1501            .unwrap();
1502        assert!(
1503            mgr.update_user_email(&id2, "taken@example.com")
1504                .await
1505                .is_err()
1506        );
1507    }
1508
1509    // ── API key operations ──────────────────────────────────────────────
1510
1511    #[tokio::test]
1512    async fn test_create_and_validate_api_key() {
1513        let mgr = make_manager();
1514        let id = mgr
1515            .register_user("oscar", "oscar@example.com", "StrongP@ss1!")
1516            .await
1517            .unwrap();
1518        let key = mgr.create_api_key(&id, None).await.unwrap();
1519        assert!(key.starts_with("ak_"));
1520        let info = mgr.validate_api_key(&key).await.unwrap();
1521        assert_eq!(info.id, id);
1522    }
1523
1524    #[tokio::test]
1525    async fn test_validate_api_key_invalid() {
1526        let mgr = make_manager();
1527        assert!(mgr.validate_api_key("bad_key").await.is_err());
1528    }
1529
1530    #[tokio::test]
1531    async fn test_revoke_api_key() {
1532        let mgr = make_manager();
1533        let id = mgr
1534            .register_user("pat", "pat@example.com", "StrongP@ss1!")
1535            .await
1536            .unwrap();
1537        let key = mgr.create_api_key(&id, None).await.unwrap();
1538        mgr.revoke_api_key(&key).await.unwrap();
1539        assert!(mgr.validate_api_key(&key).await.is_err());
1540    }
1541
1542    #[tokio::test]
1543    async fn test_revoke_api_key_not_found() {
1544        let mgr = make_manager();
1545        assert!(mgr.revoke_api_key("nonexistent").await.is_err());
1546    }
1547
1548    // ── validate_username ───────────────────────────────────────────────
1549
1550    #[tokio::test]
1551    async fn test_validate_username_valid() {
1552        let mgr = make_manager();
1553        assert!(mgr.validate_username("good_user-1").await.unwrap());
1554    }
1555
1556    #[tokio::test]
1557    async fn test_validate_username_too_short() {
1558        let mgr = make_manager();
1559        assert!(!mgr.validate_username("ab").await.unwrap());
1560    }
1561
1562    #[tokio::test]
1563    async fn test_validate_username_special_chars() {
1564        let mgr = make_manager();
1565        assert!(!mgr.validate_username("user@name").await.unwrap());
1566    }
1567
1568    // ── validate_display_name ───────────────────────────────────────────
1569
1570    #[tokio::test]
1571    async fn test_validate_display_name_valid() {
1572        let mgr = make_manager();
1573        assert!(mgr.validate_display_name("Alice Bob").await.unwrap());
1574    }
1575
1576    #[tokio::test]
1577    async fn test_validate_display_name_empty() {
1578        let mgr = make_manager();
1579        assert!(!mgr.validate_display_name("").await.unwrap());
1580    }
1581
1582    #[tokio::test]
1583    async fn test_validate_display_name_only_whitespace() {
1584        let mgr = make_manager();
1585        assert!(!mgr.validate_display_name("   ").await.unwrap());
1586    }
1587
1588    // ── validate_password_strength ──────────────────────────────────────
1589
1590    #[tokio::test]
1591    async fn test_validate_password_strong() {
1592        let mgr = make_manager();
1593        assert!(
1594            mgr.validate_password_strength("C0mpl3x!P@ssw0rd")
1595                .await
1596                .unwrap()
1597        );
1598    }
1599
1600    #[tokio::test]
1601    async fn test_validate_password_weak() {
1602        let mgr = make_manager();
1603        assert!(!mgr.validate_password_strength("123").await.unwrap());
1604    }
1605
1606    // ── validate_user_input ─────────────────────────────────────────────
1607
1608    #[tokio::test]
1609    async fn test_validate_user_input_clean() {
1610        let mgr = make_manager();
1611        assert!(mgr.validate_user_input("Hello World 123").await.unwrap());
1612    }
1613
1614    #[tokio::test]
1615    async fn test_validate_user_input_html_tags() {
1616        let mgr = make_manager();
1617        assert!(
1618            !mgr.validate_user_input("<script>alert(1)</script>")
1619                .await
1620                .unwrap()
1621        );
1622    }
1623
1624    #[tokio::test]
1625    async fn test_validate_user_input_sql_injection() {
1626        let mgr = make_manager();
1627        assert!(
1628            !mgr.validate_user_input("'; drop table users--")
1629                .await
1630                .unwrap()
1631        );
1632    }
1633
1634    #[tokio::test]
1635    async fn test_validate_user_input_template_injection() {
1636        let mgr = make_manager();
1637        assert!(!mgr.validate_user_input("${evil}").await.unwrap());
1638    }
1639
1640    #[tokio::test]
1641    async fn test_validate_user_input_path_traversal() {
1642        let mgr = make_manager();
1643        assert!(!mgr.validate_user_input("../../etc/passwd").await.unwrap());
1644    }
1645
1646    #[tokio::test]
1647    async fn test_validate_user_input_javascript_uri() {
1648        let mgr = make_manager();
1649        assert!(
1650            !mgr.validate_user_input("javascript:alert(1)")
1651                .await
1652                .unwrap()
1653        );
1654    }
1655
1656    #[tokio::test]
1657    async fn test_validate_user_input_empty() {
1658        let mgr = make_manager();
1659        assert!(!mgr.validate_user_input("").await.unwrap());
1660    }
1661
1662    #[tokio::test]
1663    async fn test_validate_user_input_encoded_tags() {
1664        let mgr = make_manager();
1665        assert!(!mgr.validate_user_input("%3cscript%3e").await.unwrap());
1666    }
1667
1668    // ── username_exists / email_exists ───────────────────────────────────
1669
1670    #[tokio::test]
1671    async fn test_username_exists() {
1672        let mgr = make_manager();
1673        mgr.register_user("quinn", "quinn@example.com", "StrongP@ss1!")
1674            .await
1675            .unwrap();
1676        assert!(mgr.username_exists("quinn").await.unwrap());
1677        assert!(!mgr.username_exists("noone").await.unwrap());
1678    }
1679
1680    #[tokio::test]
1681    async fn test_email_exists() {
1682        let mgr = make_manager();
1683        mgr.register_user("ross", "ross@example.com", "StrongP@ss1!")
1684            .await
1685            .unwrap();
1686        assert!(mgr.email_exists("ross@example.com").await.unwrap());
1687        assert!(!mgr.email_exists("nobody@example.com").await.unwrap());
1688    }
1689
1690    // ── get_user_by_username ────────────────────────────────────────────
1691
1692    #[tokio::test]
1693    async fn test_get_user_by_username() {
1694        let mgr = make_manager();
1695        mgr.register_user("sam", "sam@example.com", "StrongP@ss1!")
1696            .await
1697            .unwrap();
1698        let data = mgr.get_user_by_username("sam").await.unwrap();
1699        assert_eq!(data["username"].as_str(), Some("sam"));
1700    }
1701
1702    #[tokio::test]
1703    async fn test_get_user_by_username_not_found() {
1704        let mgr = make_manager();
1705        assert!(mgr.get_user_by_username("ghost").await.is_err());
1706    }
1707
1708    // ── get_user_profile ────────────────────────────────────────────────
1709
1710    #[tokio::test]
1711    async fn test_get_user_profile() {
1712        let mgr = make_manager();
1713        let id = mgr
1714            .register_user("tina", "tina@example.com", "StrongP@ss1!")
1715            .await
1716            .unwrap();
1717        let profile = mgr.get_user_profile(&id).await.unwrap();
1718        assert_eq!(profile.username.as_deref(), Some("tina"));
1719        assert_eq!(profile.email.as_deref(), Some("tina@example.com"));
1720        // password_hash should NOT be in additional_data
1721        assert!(!profile.additional_data.contains_key("password_hash"));
1722    }
1723
1724    #[tokio::test]
1725    async fn test_get_user_profile_not_found() {
1726        let mgr = make_manager();
1727        assert!(mgr.get_user_profile("ghost").await.is_err());
1728    }
1729
1730    // ── get_user_roles ──────────────────────────────────────────────────
1731
1732    #[tokio::test]
1733    async fn test_get_user_roles_default() {
1734        let mgr = make_manager();
1735        let id = mgr
1736            .register_user("uma", "uma@example.com", "StrongP@ss1!")
1737            .await
1738            .unwrap();
1739        let roles = mgr.get_user_roles(&id).await.unwrap();
1740        assert!(roles.contains(&"user".to_string()));
1741    }
1742
1743    #[tokio::test]
1744    async fn test_get_user_roles_not_found_returns_default() {
1745        let mgr = make_manager();
1746        let roles = mgr.get_user_roles("ghost").await.unwrap();
1747        assert_eq!(roles, vec!["user".to_string()]);
1748    }
1749
1750    // ── verify_login_credentials ────────────────────────────────────────
1751
1752    #[tokio::test]
1753    async fn test_verify_login_credentials_success() {
1754        let mgr = make_manager();
1755        mgr.register_user("vera", "vera@example.com", "StrongP@ss1!")
1756            .await
1757            .unwrap();
1758        let result = mgr
1759            .verify_login_credentials("vera", "StrongP@ss1!")
1760            .await
1761            .unwrap();
1762        assert!(result.is_some());
1763        assert!(!result.unwrap().mfa_enabled);
1764    }
1765
1766    #[tokio::test]
1767    async fn test_verify_login_credentials_wrong_password() {
1768        let mgr = make_manager();
1769        mgr.register_user("wanda", "wanda@example.com", "StrongP@ss1!")
1770            .await
1771            .unwrap();
1772        let result = mgr
1773            .verify_login_credentials("wanda", "wrong")
1774            .await
1775            .unwrap();
1776        assert!(result.is_none());
1777    }
1778
1779    #[tokio::test]
1780    async fn test_register_user_credentials_record_honors_bcrypt_configured_algorithm() {
1781        // The user:credentials:{username} record (read by
1782        // verify_login_credentials -- the actual login path) must be hashed
1783        // with the configured algorithm too, not hardcoded to Argon2id
1784        // independent of the user:{id} record.
1785        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1786        mgr.register_user("bcrypt_login", "bcrypt_login@example.com", "StrongP@ss1!")
1787            .await
1788            .unwrap();
1789        let creds_key = "user:credentials:bcrypt_login";
1790        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1791        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1792        let hash = creds["password_hash"].as_str().unwrap();
1793        assert!(
1794            hash.starts_with("$2"),
1795            "expected a bcrypt hash on the login-credentials record, got: {hash}"
1796        );
1797    }
1798
1799    #[tokio::test]
1800    async fn test_register_user_credentials_record_argon2_default_unchanged() {
1801        // Derive the algorithm from AuthConfig::default() itself, not a
1802        // hardcoded PasswordHashAlgorithm::Argon2, so this proves the
1803        // crate's actual default produces an Argon2id credentials record --
1804        // not just that Argon2 behaves correctly when explicitly chosen.
1805        let default_algorithm = crate::config::AuthConfig::default()
1806            .security
1807            .password_hash_algorithm;
1808        assert!(matches!(default_algorithm, PasswordHashAlgorithm::Argon2));
1809        let mgr = make_manager_with_algorithm(default_algorithm);
1810        mgr.register_user("argon2_login", "argon2_login@example.com", "StrongP@ss1!")
1811            .await
1812            .unwrap();
1813        let creds_key = "user:credentials:argon2_login";
1814        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1815        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1816        let hash = creds["password_hash"].as_str().unwrap();
1817        assert!(
1818            hash.starts_with("$argon2"),
1819            "expected an Argon2id hash on the login-credentials record, got: {hash}"
1820        );
1821    }
1822
1823    #[tokio::test]
1824    async fn test_login_round_trip_under_bcrypt_configured_algorithm() {
1825        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1826        mgr.register_user("bcrypt_rt", "bcrypt_rt@example.com", "StrongP@ss1!")
1827            .await
1828            .unwrap();
1829        assert!(
1830            mgr.verify_login_credentials("bcrypt_rt", "StrongP@ss1!")
1831                .await
1832                .unwrap()
1833                .is_some(),
1834            "correct password must log in under Bcrypt"
1835        );
1836        assert!(
1837            mgr.verify_login_credentials("bcrypt_rt", "wrong")
1838                .await
1839                .unwrap()
1840                .is_none(),
1841            "wrong password must be rejected under Bcrypt"
1842        );
1843    }
1844
1845    #[tokio::test]
1846    async fn test_login_round_trip_under_argon2_configured_algorithm() {
1847        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1848        mgr.register_user("argon2_rt", "argon2_rt@example.com", "StrongP@ss1!")
1849            .await
1850            .unwrap();
1851        assert!(
1852            mgr.verify_login_credentials("argon2_rt", "StrongP@ss1!")
1853                .await
1854                .unwrap()
1855                .is_some(),
1856            "correct password must log in under Argon2"
1857        );
1858        assert!(
1859            mgr.verify_login_credentials("argon2_rt", "wrong")
1860                .await
1861                .unwrap()
1862                .is_none(),
1863            "wrong password must be rejected under Argon2"
1864        );
1865    }
1866
1867    #[tokio::test]
1868    async fn test_update_password_updates_credentials_record_under_configured_algorithm() {
1869        // update_password's user:credentials:{username} rewrite must also
1870        // use the configured algorithm, not hardcoded Argon2id.
1871        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1872        mgr.register_user("bcrypt_update", "bcrypt_update@example.com", "StrongP@ss1!")
1873            .await
1874            .unwrap();
1875        mgr.update_user_password("bcrypt_update", "NewerP@ss2!")
1876            .await
1877            .unwrap();
1878
1879        let creds_key = "user:credentials:bcrypt_update";
1880        let bytes = mgr.storage.get_kv(creds_key).await.unwrap().unwrap();
1881        let creds: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1882        let hash = creds["password_hash"].as_str().unwrap();
1883        assert!(
1884            hash.starts_with("$2"),
1885            "expected the rewritten login-credentials hash to stay bcrypt, got: {hash}"
1886        );
1887        assert!(
1888            mgr.verify_login_credentials("bcrypt_update", "NewerP@ss2!")
1889                .await
1890                .unwrap()
1891                .is_some(),
1892            "login must succeed with the new password after update_password"
1893        );
1894    }
1895
1896    #[tokio::test]
1897    async fn test_verify_login_credentials_unknown_user() {
1898        let mgr = make_manager();
1899        let result = mgr
1900            .verify_login_credentials("ghost", "StrongP@ss1!")
1901            .await
1902            .unwrap();
1903        assert!(result.is_none());
1904    }
1905
1906    #[test]
1907    fn test_dummy_password_hash_is_precomputed_at_construction() {
1908        // Structural proof that the unknown-user path in
1909        // verify_login_credentials costs exactly one verification, not one
1910        // hash plus one verification: the dummy hash must already exist
1911        // right after construction, before any lookup happens at all.
1912        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1913        assert!(
1914            mgr.dummy_password_hash.is_some(),
1915            "dummy_password_hash must be computed at construction time, not lazily on first \
1916             unknown-user lookup"
1917        );
1918
1919        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Bcrypt);
1920        assert!(mgr.dummy_password_hash.is_some());
1921    }
1922
1923    #[tokio::test]
1924    async fn test_unknown_user_lookup_performs_zero_hashes_and_one_verify() {
1925        // Mutation-proof version of the earlier (removed) test: comparing
1926        // dummy_password_hash before/after a lookup cannot catch a
1927        // regression that reintroduces "hash a fresh dummy, then verify"
1928        // in the None branch while leaving the (now-unused) field alone --
1929        // that mutation calls hash_with_algorithm once and
1930        // verify_password_any_format once, exactly like the buggy
1931        // round-2 code did, and the field itself would never be touched
1932        // either way. Counting both operations directly is what actually
1933        // distinguishes "one verify against a precomputed hash" (the
1934        // fix) from "one hash plus one verify" (the regression this is
1935        // guarding against), which is the actual cost difference that
1936        // created the timing oracle.
1937        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1938        reset_call_counters();
1939
1940        mgr.verify_login_credentials("ghost", "whatever")
1941            .await
1942            .unwrap();
1943
1944        assert_eq!(
1945            call_counts(),
1946            (0, 1),
1947            "the unknown-user path must perform zero hashing operations and exactly one \
1948             verification -- any hashing here (even once) reintroduces the timing oracle \
1949             this test guards against"
1950        );
1951    }
1952
1953    #[tokio::test]
1954    async fn test_known_user_wrong_password_performs_zero_hashes_and_one_verify() {
1955        // Same shape as above, for a real user with a wrong password --
1956        // establishing that the unknown-user path (test above) costs
1957        // exactly the same number of operations as this one, which is the
1958        // actual property a constant-time comparison needs.
1959        let mgr = make_manager_with_algorithm(PasswordHashAlgorithm::Argon2);
1960        mgr.register_user("real_user", "real_user@example.com", "StrongP@ss1!")
1961            .await
1962            .unwrap();
1963        reset_call_counters();
1964
1965        mgr.verify_login_credentials("real_user", "wrong")
1966            .await
1967            .unwrap();
1968
1969        assert_eq!(call_counts(), (0, 1));
1970    }
1971
1972    #[tokio::test]
1973    async fn test_verify_login_credentials_empty_inputs() {
1974        let mgr = make_manager();
1975        assert!(
1976            mgr.verify_login_credentials("", "pass")
1977                .await
1978                .unwrap()
1979                .is_none()
1980        );
1981        assert!(
1982            mgr.verify_login_credentials("user", "")
1983                .await
1984                .unwrap()
1985                .is_none()
1986        );
1987    }
1988
1989    #[tokio::test]
1990    async fn test_verify_login_credentials_deactivated() {
1991        let mgr = make_manager();
1992        let id = mgr
1993            .register_user("xena", "xena@example.com", "StrongP@ss1!")
1994            .await
1995            .unwrap();
1996        mgr.set_user_active(&id, false).await.unwrap();
1997        let result = mgr
1998            .verify_login_credentials("xena", "StrongP@ss1!")
1999            .await
2000            .unwrap();
2001        assert!(result.is_none());
2002    }
2003
2004    // ── get_username_by_id ──────────────────────────────────────────────
2005
2006    #[tokio::test]
2007    async fn test_get_username_by_id() {
2008        let mgr = make_manager();
2009        let id = mgr
2010            .register_user("yara", "yara@example.com", "StrongP@ss1!")
2011            .await
2012            .unwrap();
2013        let username = mgr.get_username_by_id(&id).await.unwrap();
2014        assert_eq!(username, "yara");
2015    }
2016
2017    #[tokio::test]
2018    async fn test_get_username_by_id_not_found() {
2019        let mgr = make_manager();
2020        assert!(mgr.get_username_by_id("ghost").await.is_err());
2021    }
2022
2023    // ── list_users active_only filter ───────────────────────────────────
2024
2025    #[tokio::test]
2026    async fn test_list_users_active_only() {
2027        let mgr = make_manager();
2028        let id1 = mgr
2029            .register_user("active1", "active1@example.com", "StrongP@ss1!")
2030            .await
2031            .unwrap();
2032        let id2 = mgr
2033            .register_user("inactive1", "inactive1@example.com", "StrongP@ss1!")
2034            .await
2035            .unwrap();
2036        mgr.set_user_active(&id2, false).await.unwrap();
2037
2038        let all = mgr.list_users(None, None, false).await.unwrap();
2039        let active = mgr.list_users(None, None, true).await.unwrap();
2040        assert!(all.len() > active.len());
2041        assert!(active.iter().all(|u| u.active));
2042        // The inactive user should still be in the "all" list
2043        assert!(all.iter().any(|u| u.id == id1));
2044        assert!(all.iter().any(|u| u.id == id2));
2045    }
2046}