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