Skip to main content

auth_framework/auth_modular/
user_manager.rs

1//! User management module
2
3use crate::errors::{AuthError, Result};
4use crate::storage::AuthStorage;
5use std::collections::HashMap;
6use std::sync::Arc;
7use tracing::{debug, info};
8
9/// User information structure
10#[derive(Debug, Clone)]
11pub struct UserInfo {
12    /// User ID
13    pub id: String,
14
15    /// Username
16    pub username: String,
17
18    /// Email address
19    pub email: Option<String>,
20
21    /// Display name
22    pub name: Option<String>,
23
24    /// User roles
25    pub roles: Vec<String>,
26
27    /// Whether the user is active
28    pub active: bool,
29
30    /// Additional user attributes
31    pub attributes: HashMap<String, serde_json::Value>,
32}
33
34/// User manager for handling user operations
35pub struct UserManager {
36    storage: Arc<dyn AuthStorage>,
37}
38
39impl UserManager {
40    /// Create a new user manager
41    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
42        Self { storage }
43    }
44
45    /// KV row name for an API key: a domain-separated one-way digest, never
46    /// the raw key.
47    fn api_key_storage_key(api_key: &str) -> String {
48        format!(
49            "api_key_h:{}",
50            crate::storage::key_names::digest("api_key", api_key)
51        )
52    }
53
54    /// The pre-fix row name (the raw key). Read only to migrate or delete.
55    fn legacy_api_key_storage_key(api_key: &str) -> String {
56        format!("api_key:{api_key}")
57    }
58
59    /// Tombstone written by a revoke, so a migration that read the legacy row
60    /// before the revoke and writes the digest row after it can tell, and take
61    /// its row back out. Short-lived: it only has to outlast an in-flight
62    /// migration, and a revoke removes the legacy row that migrations read.
63    fn revoked_marker_key(api_key: &str) -> String {
64        format!(
65            "api_key_revoked:{}",
66            crate::storage::key_names::digest("api_key", api_key)
67        )
68    }
69
70    /// Fetch an API key's row, migrating one stored under the legacy name:
71    /// write the row under the digest name, then delete the legacy row.
72    ///
73    /// This release's storage trait has no create-if-absent, so races are
74    /// settled by ordering and a revoke marker rather than by who created the
75    /// row. Several readers may migrate at once: they write identical rows and
76    /// each deletes the legacy name, which is harmless. A revoke deletes the
77    /// legacy row, the digest row and leaves a marker; a migration that wrote
78    /// its digest row after the revoke finds the marker and removes the row
79    /// again. The migrated row's lifetime comes from its own `expires_at`.
80    async fn get_api_key_row(&self, api_key: &str, storage_key: &str) -> Result<Option<Vec<u8>>> {
81        if let Some(row) = self.storage.get_kv(storage_key).await? {
82            return Ok(Some(row));
83        }
84        let legacy_key = Self::legacy_api_key_storage_key(api_key);
85        let Some(row) = self.storage.get_kv(&legacy_key).await? else {
86            // Not under the legacy name either: a migration that ran between
87            // the two reads has moved the row, so read the digest name again.
88            return self.storage.get_kv(storage_key).await;
89        };
90
91        let ttl = match serde_json::from_slice::<serde_json::Value>(&row)
92            .ok()
93            .and_then(|v| v["expires_at"].as_str().map(str::to_owned))
94            .and_then(|s| s.parse::<chrono::DateTime<chrono::Utc>>().ok())
95            .map(|at| at - chrono::Utc::now())
96        {
97            // expired: do not recreate it; the caller rejects it from the row
98            Some(left) if left <= chrono::Duration::zero() => return Ok(Some(row)),
99            // whole seconds, rounded up: the Redis backends cannot take less
100            Some(left) => left.to_std().ok().map(|d| {
101                std::time::Duration::from_secs(d.as_secs() + u64::from(d.subsec_nanos() > 0))
102            }),
103            None => None,
104        };
105
106        self.storage.store_kv(storage_key, &row, ttl).await?;
107        if self
108            .storage
109            .get_kv(&Self::revoked_marker_key(api_key))
110            .await?
111            .is_some()
112        {
113            // revoked while we were migrating: take the new row back out
114            self.storage.delete_kv(storage_key).await?;
115            return Ok(None);
116        }
117        self.storage.delete_kv(&legacy_key).await?;
118        Ok(Some(row))
119    }
120
121    /// Create API key for a user
122    pub async fn create_api_key(
123        &self,
124        user_id: &str,
125        expires_in: Option<std::time::Duration>,
126    ) -> Result<String> {
127        debug!("Creating API key for user '{}'", user_id);
128
129        // Generate a secure API key
130        let api_key = format!("ak_{}", crate::utils::crypto::generate_token(32));
131
132        // Store API key metadata
133        let key_data = serde_json::json!({
134            "user_id": user_id,
135            "created_at": chrono::Utc::now(),
136            "expires_at": expires_in.map(|d| chrono::Utc::now() + chrono::Duration::from_std(d).unwrap())
137        });
138
139        // The raw key is a bearer credential: the row is named by a one-way
140        // digest so a reader of the store cannot recover working keys.
141        let storage_key = Self::api_key_storage_key(&api_key);
142        self.storage
143            .store_kv(&storage_key, key_data.to_string().as_bytes(), expires_in)
144            .await?;
145
146        info!("API key created for user '{}'", user_id);
147        Ok(api_key)
148    }
149
150    /// Validate API key and return user information
151    pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
152        debug!("Validating API key");
153
154        let storage_key = Self::api_key_storage_key(api_key);
155        if let Some(key_data) = self.get_api_key_row(api_key, &storage_key).await? {
156            let key_info: serde_json::Value = serde_json::from_slice(&key_data)?;
157
158            if let Some(user_id) = key_info["user_id"].as_str() {
159                // Check expiration
160                if let Some(expires_at_str) = key_info["expires_at"].as_str() {
161                    let expires_at: chrono::DateTime<chrono::Utc> = expires_at_str
162                        .parse()
163                        .map_err(|_| AuthError::token("Invalid API key expiration"))?;
164
165                    if chrono::Utc::now() > expires_at {
166                        return Err(AuthError::token("API key expired"));
167                    }
168                }
169
170                // Return user information
171                Ok(UserInfo {
172                    id: user_id.to_string(),
173                    username: format!("api_user_{}", user_id),
174                    email: None,
175                    name: None,
176                    roles: vec!["api_user".to_string()],
177                    active: true,
178                    attributes: HashMap::new(),
179                })
180            } else {
181                Err(AuthError::token("Invalid API key format"))
182            }
183        } else {
184            Err(AuthError::token("Invalid API key"))
185        }
186    }
187
188    /// Revoke API key
189    pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
190        debug!("Revoking API key");
191
192        let storage_key = Self::api_key_storage_key(api_key);
193        let legacy_key = Self::legacy_api_key_storage_key(api_key);
194        // Legacy name first: a migration writes the digest row before it
195        // deletes the legacy row, so a row is always visible under one of the
196        // two names when read in this order.
197        let found_legacy = self.storage.get_kv(&legacy_key).await?.is_some();
198        let found_new = self.storage.get_kv(&storage_key).await?.is_some();
199        if found_new || found_legacy {
200            // Marker first, so a migration that read the legacy row earlier
201            // and writes the digest row after this revoke removes it again.
202            self.storage
203                .store_kv(
204                    &Self::revoked_marker_key(api_key),
205                    b"1",
206                    Some(std::time::Duration::from_secs(300)),
207                )
208                .await?;
209            // Both names (a key may exist under either, or both mid-migration),
210            // legacy first so a migration in flight cannot recreate the row.
211            self.storage.delete_kv(&legacy_key).await?;
212            self.storage.delete_kv(&storage_key).await?;
213            info!("API key revoked");
214            Ok(())
215        } else {
216            Err(AuthError::token("API key not found"))
217        }
218    }
219
220    /// Validate username format
221    pub async fn validate_username(&self, username: &str) -> Result<bool> {
222        debug!("Validating username format: '{}'", username);
223
224        let is_valid = username.len() >= 3
225            && username.len() <= 32
226            && username
227                .chars()
228                .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
229
230        Ok(is_valid)
231    }
232
233    /// Validate display name format
234    pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
235        debug!("Validating display name format");
236
237        let is_valid = !display_name.is_empty()
238            && display_name.len() <= 100
239            && !display_name.trim().is_empty();
240
241        Ok(is_valid)
242    }
243
244    /// Validate password strength using security policy
245    pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
246        debug!("Validating password strength");
247
248        let strength = crate::utils::password::check_password_strength(password);
249
250        // Consider Medium, Strong, and VeryStrong passwords as valid
251        let is_valid = !matches!(
252            strength.level,
253            crate::utils::password::PasswordStrengthLevel::Weak
254        );
255
256        if !is_valid {
257            debug!(
258                "Password validation failed: {}",
259                strength.feedback.join(", ")
260            );
261        }
262
263        Ok(is_valid)
264    }
265
266    /// Validate user input for security
267    pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
268        debug!("Validating user input");
269
270        // Comprehensive security validation
271        let is_valid = !input.contains('<')
272            && !input.contains('>')
273            && !input.contains("script")
274            && !input.contains("javascript:")
275            && !input.contains("data:")
276            && !input.contains("file:")
277            && !input.contains("${")  // Template injection
278            && !input.contains("{{")  // Template injection
279            && !input.contains("'}") && !input.contains("'}")  // Template injection
280            && !input.contains("'; DROP") && !input.contains("' DROP") // SQL injection
281            && !input.contains("; DROP") && !input.contains(";DROP") // SQL injection
282            && !input.contains("--") // SQL comments
283            && !input.contains("../") // Path traversal
284            && !input.contains("..\\") // Path traversal (Windows)
285            && !input.contains('\0') // Null byte injection
286            && !input.contains("%00") // URL encoded null byte
287            && !input.contains("jndi:") // LDAP injection
288            && !input.contains("%3C") && !input.contains("%3E") // URL encoded < >
289            && input.len() <= 1000;
290
291        Ok(is_valid)
292    }
293
294    /// Map user attribute
295    pub async fn map_user_attribute(
296        &self,
297        user_id: &str,
298        attribute: &str,
299        value: &str,
300    ) -> Result<()> {
301        debug!(
302            "Mapping attribute '{}' = '{}' for user '{}'",
303            attribute, value, user_id
304        );
305
306        let key = format!("user:{}:attribute:{}", user_id, attribute);
307        self.storage.store_kv(&key, value.as_bytes(), None).await?;
308
309        info!("Attribute '{}' mapped for user '{}'", attribute, user_id);
310        Ok(())
311    }
312
313    /// Get user attribute
314    pub async fn get_user_attribute(
315        &self,
316        user_id: &str,
317        attribute: &str,
318    ) -> Result<Option<String>> {
319        debug!("Getting attribute '{}' for user '{}'", attribute, user_id);
320
321        let key = format!("user:{}:attribute:{}", user_id, attribute);
322        if let Some(value_data) = self.storage.get_kv(&key).await? {
323            Ok(Some(String::from_utf8(value_data).map_err(|e| {
324                AuthError::internal(format!("Failed to parse attribute value: {}", e))
325            })?))
326        } else {
327            // Return some default values for common attributes for demo purposes
328            match attribute {
329                "department" => Ok(Some("engineering".to_string())),
330                "clearance_level" => Ok(Some("3".to_string())),
331                "location" => Ok(Some("office".to_string())),
332                _ => Ok(None),
333            }
334        }
335    }
336
337    /// Get user information by ID
338    pub async fn get_user_info(&self, user_id: &str) -> Result<UserInfo> {
339        debug!("Getting user info for '{}'", user_id);
340
341        // For now, return a basic user info structure
342        // In a real implementation, this would query a user database
343        Ok(UserInfo {
344            id: user_id.to_string(),
345            username: format!("user_{}", user_id),
346            email: None,
347            name: None,
348            roles: vec!["user".to_string()],
349            active: true,
350            attributes: HashMap::new(),
351        })
352    }
353
354    /// Check if user exists
355    pub async fn user_exists(&self, user_id: &str) -> Result<bool> {
356        debug!("Checking if user '{}' exists", user_id);
357
358        // For now, assume all non-empty user IDs exist
359        // In a real implementation, this would check a user database
360        Ok(!user_id.is_empty())
361    }
362}