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