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