Skip to main content

auth_framework/
oauth2_enhanced_storage.rs

1//! Enhanced OAuth2 token and code storage with proper validation
2
3use crate::errors::Result;
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::time::SystemTime;
7use uuid::Uuid;
8
9/// Stored refresh token with validation metadata
10#[derive(Clone, Serialize, Deserialize)]
11pub struct RefreshToken {
12    pub token_id: String,
13    pub client_id: String,
14    pub user_id: String,
15    pub scopes: Vec<String>,
16    pub issued_at: SystemTime,
17    pub expires_at: SystemTime,
18    pub is_revoked: bool,
19}
20
21impl std::fmt::Debug for RefreshToken {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        let mut d = f.debug_struct("RefreshToken");
24        d.field("token_id", &crate::utils::redact::redacted(&self.token_id));
25        d.field("client_id", &self.client_id);
26        d.field("user_id", &self.user_id);
27        d.field("scopes", &self.scopes);
28        d.field("issued_at", &self.issued_at);
29        d.field("expires_at", &self.expires_at);
30        d.field("is_revoked", &self.is_revoked);
31        d.finish()
32    }
33}
34
35impl RefreshToken {
36    pub fn new(
37        client_id: String,
38        user_id: String,
39        scopes: Vec<String>,
40        lifetime: std::time::Duration,
41    ) -> Self {
42        let now = SystemTime::now();
43        Self {
44            token_id: Uuid::new_v4().to_string(),
45            client_id,
46            user_id,
47            scopes,
48            issued_at: now,
49            expires_at: now + lifetime,
50            is_revoked: false,
51        }
52    }
53
54    pub fn is_expired(&self) -> bool {
55        SystemTime::now() > self.expires_at
56    }
57
58    pub fn is_valid(&self) -> bool {
59        !self.is_revoked && !self.is_expired()
60    }
61
62    pub fn revoke(&mut self) {
63        self.is_revoked = true;
64    }
65}
66
67/// Enhanced authorization code with user context
68#[derive(Clone, Serialize, Deserialize)]
69pub struct EnhancedAuthorizationCode {
70    pub code: String,
71    pub client_id: String,
72    pub user_id: String,
73    pub redirect_uri: String,
74    pub scopes: Vec<String>,
75    pub code_challenge: Option<String>,
76    pub code_challenge_method: Option<String>,
77    pub issued_at: SystemTime,
78    pub expires_at: SystemTime,
79    pub is_used: bool,
80}
81
82impl std::fmt::Debug for EnhancedAuthorizationCode {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        let mut d = f.debug_struct("EnhancedAuthorizationCode");
85        d.field("code", &crate::utils::redact::redacted(&self.code));
86        d.field("client_id", &self.client_id);
87        d.field("user_id", &self.user_id);
88        d.field("redirect_uri", &self.redirect_uri);
89        d.field("scopes", &self.scopes);
90        d.field("code_challenge", &self.code_challenge);
91        d.field("code_challenge_method", &self.code_challenge_method);
92        d.field("issued_at", &self.issued_at);
93        d.field("expires_at", &self.expires_at);
94        d.field("is_used", &self.is_used);
95        d.finish()
96    }
97}
98
99impl EnhancedAuthorizationCode {
100    pub fn new(
101        client_id: String,
102        user_id: String,
103        redirect_uri: String,
104        scopes: Vec<String>,
105        code_challenge: Option<String>,
106        code_challenge_method: Option<String>,
107        lifetime: std::time::Duration,
108    ) -> Self {
109        let now = SystemTime::now();
110        Self {
111            code: Uuid::new_v4().to_string(),
112            client_id,
113            user_id,
114            redirect_uri,
115            scopes,
116            code_challenge,
117            code_challenge_method,
118            issued_at: now,
119            expires_at: now + lifetime,
120            is_used: false,
121        }
122    }
123
124    pub fn is_expired(&self) -> bool {
125        SystemTime::now() > self.expires_at
126    }
127
128    pub fn is_valid(&self) -> bool {
129        !self.is_used && !self.is_expired()
130    }
131
132    pub fn mark_used(&mut self) {
133        self.is_used = true;
134    }
135}
136
137/// Enhanced client credentials with proper secret validation
138#[derive(Clone, Serialize, Deserialize)]
139pub struct EnhancedClientCredentials {
140    pub client_id: String,
141    pub client_secret_hash: String,
142    pub client_type: ClientType,
143    pub redirect_uris: Vec<String>,
144    pub allowed_scopes: Vec<String>,
145    pub grant_types: Vec<String>,
146    pub created_at: SystemTime,
147    pub is_active: bool,
148}
149
150impl std::fmt::Debug for EnhancedClientCredentials {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        let mut d = f.debug_struct("EnhancedClientCredentials");
153        d.field("client_id", &self.client_id);
154        d.field(
155            "client_secret_hash",
156            &crate::utils::redact::redacted(&self.client_secret_hash),
157        );
158        d.field("client_type", &self.client_type);
159        d.field("redirect_uris", &self.redirect_uris);
160        d.field("allowed_scopes", &self.allowed_scopes);
161        d.field("grant_types", &self.grant_types);
162        d.field("created_at", &self.created_at);
163        d.field("is_active", &self.is_active);
164        d.finish()
165    }
166}
167
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub enum ClientType {
170    Confidential,
171    Public,
172}
173
174impl EnhancedClientCredentials {
175    pub fn new_confidential(
176        client_id: String,
177        client_secret: &str,
178        redirect_uris: Vec<String>,
179        allowed_scopes: Vec<String>,
180        grant_types: Vec<String>,
181    ) -> Result<Self> {
182        use crate::security::secure_utils::hash_password;
183
184        Ok(Self {
185            client_id,
186            client_secret_hash: hash_password(client_secret)?,
187            client_type: ClientType::Confidential,
188            redirect_uris,
189            allowed_scopes,
190            grant_types,
191            created_at: SystemTime::now(),
192            is_active: true,
193        })
194    }
195
196    pub fn new_public(
197        client_id: String,
198        redirect_uris: Vec<String>,
199        allowed_scopes: Vec<String>,
200        grant_types: Vec<String>,
201    ) -> Self {
202        Self {
203            client_id,
204            client_secret_hash: String::new(), // Public clients don't have secrets
205            client_type: ClientType::Public,
206            redirect_uris,
207            allowed_scopes,
208            grant_types,
209            created_at: SystemTime::now(),
210            is_active: true,
211        }
212    }
213
214    pub fn validate_secret(&self, provided_secret: &str) -> Result<bool> {
215        match self.client_type {
216            ClientType::Public => Ok(true), // Public clients don't need secret validation
217            ClientType::Confidential => {
218                use crate::security::secure_utils::verify_password;
219                verify_password(provided_secret, &self.client_secret_hash)
220            }
221        }
222    }
223
224    pub fn requires_secret(&self) -> bool {
225        matches!(self.client_type, ClientType::Confidential)
226    }
227
228    pub fn has_scope(&self, scope: &str) -> bool {
229        self.allowed_scopes.contains(&scope.to_string())
230    }
231
232    pub fn supports_grant_type(&self, grant_type: &str) -> bool {
233        self.grant_types.contains(&grant_type.to_string())
234    }
235}
236
237/// Enhanced token storage with proper validation
238#[derive(Clone)]
239pub struct EnhancedTokenStorage {
240    refresh_tokens: HashMap<String, RefreshToken>,
241    authorization_codes: HashMap<String, EnhancedAuthorizationCode>,
242    client_credentials: HashMap<String, EnhancedClientCredentials>,
243}
244
245impl std::fmt::Debug for EnhancedTokenStorage {
246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        let mut d = f.debug_struct("EnhancedTokenStorage");
248        d.field(
249            "refresh_tokens",
250            &crate::utils::redact::redacted(&self.refresh_tokens),
251        );
252        d.field(
253            "authorization_codes",
254            &crate::utils::redact::redacted(&self.authorization_codes),
255        );
256        d.field(
257            "client_credentials",
258            &crate::utils::redact::redacted(&self.client_credentials),
259        );
260        d.finish()
261    }
262}
263
264impl EnhancedTokenStorage {
265    pub fn new() -> Self {
266        Self {
267            refresh_tokens: HashMap::new(),
268            authorization_codes: HashMap::new(),
269            client_credentials: HashMap::new(),
270        }
271    }
272
273    // Refresh token operations
274    pub async fn store_refresh_token(&mut self, token: RefreshToken) -> Result<String> {
275        let token_id = token.token_id.clone();
276        self.refresh_tokens.insert(token_id.clone(), token);
277        Ok(token_id)
278    }
279
280    pub async fn get_refresh_token(&self, token_id: &str) -> Result<Option<RefreshToken>> {
281        Ok(self.refresh_tokens.get(token_id).cloned())
282    }
283
284    pub async fn validate_refresh_token(&self, token_id: &str) -> Result<bool> {
285        match self.refresh_tokens.get(token_id) {
286            Some(token) => Ok(token.is_valid()),
287            None => Ok(false),
288        }
289    }
290
291    pub async fn revoke_refresh_token(&mut self, token_id: &str) -> Result<bool> {
292        match self.refresh_tokens.get_mut(token_id) {
293            Some(token) => {
294                token.revoke();
295                Ok(true)
296            }
297            None => Ok(false),
298        }
299    }
300
301    // Authorization code operations
302    pub async fn store_authorization_code(
303        &mut self,
304        code: EnhancedAuthorizationCode,
305    ) -> Result<String> {
306        let code_value = code.code.clone();
307        self.authorization_codes.insert(code_value.clone(), code);
308        Ok(code_value)
309    }
310
311    pub async fn get_authorization_code(
312        &self,
313        code: &str,
314    ) -> Result<Option<EnhancedAuthorizationCode>> {
315        Ok(self.authorization_codes.get(code).cloned())
316    }
317
318    pub async fn consume_authorization_code(
319        &mut self,
320        code: &str,
321    ) -> Result<Option<EnhancedAuthorizationCode>> {
322        match self.authorization_codes.get_mut(code) {
323            Some(auth_code) if auth_code.is_valid() => {
324                auth_code.mark_used();
325                Ok(Some(auth_code.clone()))
326            }
327            _ => Ok(None),
328        }
329    }
330
331    // Client credentials operations
332    pub async fn store_client_credentials(
333        &mut self,
334        credentials: EnhancedClientCredentials,
335    ) -> Result<()> {
336        let client_id = credentials.client_id.clone();
337        self.client_credentials.insert(client_id, credentials);
338        Ok(())
339    }
340
341    pub async fn get_client_credentials(
342        &self,
343        client_id: &str,
344    ) -> Result<Option<EnhancedClientCredentials>> {
345        Ok(self.client_credentials.get(client_id).cloned())
346    }
347
348    pub async fn validate_client_credentials(
349        &self,
350        client_id: &str,
351        client_secret: Option<&str>,
352    ) -> Result<bool> {
353        match self.client_credentials.get(client_id) {
354            Some(credentials) if credentials.is_active => {
355                if credentials.requires_secret() {
356                    match client_secret {
357                        Some(secret) => credentials.validate_secret(secret),
358                        None => Ok(false), // Secret required but not provided
359                    }
360                } else {
361                    Ok(true) // Public client, no secret required
362                }
363            }
364            _ => Ok(false), // Client not found or inactive
365        }
366    }
367
368    // Cleanup operations
369    pub async fn cleanup_expired_tokens(&mut self) -> Result<usize> {
370        let initial_count = self.refresh_tokens.len() + self.authorization_codes.len();
371
372        // Remove expired refresh tokens
373        self.refresh_tokens.retain(|_, token| token.is_valid());
374
375        // Remove expired authorization codes
376        self.authorization_codes.retain(|_, code| code.is_valid());
377
378        let final_count = self.refresh_tokens.len() + self.authorization_codes.len();
379        Ok(initial_count - final_count)
380    }
381
382    // User credential management methods
383
384    /// Get user credentials for authentication
385    pub async fn get_user_credentials(&self, username: &str) -> Result<Option<UserCredentials>> {
386        // For demo purposes, use pre-computed bcrypt hashes for known users
387        // In production, this would query a database with pre-hashed passwords
388        let demo_users = [
389            (
390                "admin",
391                "$2b$12$UfM9FwL8dbLOFTOmL8kAVOUe8.mFYGsqtaEjpMrS6yOGhN6SHL6me", // hash of "admin_password_123456789"
392                vec!["read", "write", "admin", "delete"],
393            ),
394            (
395                "user",
396                "$2b$12$3Jb05MyZ7QDS81DJkt3QLeyR9z.S9yQqULr42kZ5F5crUYbwJaXdW", // hash of "user_password_123456789"
397                vec!["read", "write"],
398            ),
399            (
400                "test",
401                "$2b$12$bM6NV4EQdo8kJHUhhZGpIuIsalt4eD9J8co0KyO6pzEPX0ClONwTy", // hash of "test_password_123456789"
402                vec!["read"],
403            ),
404        ];
405
406        for (demo_user, password_hash, demo_scopes) in &demo_users {
407            if username == *demo_user {
408                return Ok(Some(UserCredentials {
409                    username: username.to_string(),
410                    password_hash: password_hash.to_string(),
411                    scopes: demo_scopes.iter().map(|s| s.to_string()).collect(),
412                    is_active: true,
413                }));
414            }
415        }
416
417        Ok(None)
418    }
419
420    /// Get user permissions/scopes
421    pub async fn get_user_permissions(&self, username: &str) -> Result<Option<UserPermissions>> {
422        // Get credentials which include permissions
423        if let Some(credentials) = self.get_user_credentials(username).await? {
424            Ok(Some(UserPermissions {
425                username: credentials.username,
426                scopes: credentials.scopes,
427                is_active: credentials.is_active,
428            }))
429        } else {
430            Ok(None)
431        }
432    }
433}
434
435/// User credentials stored in the system
436#[derive(Clone, Serialize, Deserialize)]
437pub struct UserCredentials {
438    pub username: String,
439    pub password_hash: String, // In production: bcrypt/argon2 hash
440    pub scopes: Vec<String>,
441    pub is_active: bool,
442}
443
444impl std::fmt::Debug for UserCredentials {
445    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
446        let mut d = f.debug_struct("UserCredentials");
447        d.field("username", &self.username);
448        d.field(
449            "password_hash",
450            &crate::utils::redact::redacted(&self.password_hash),
451        );
452        d.field("scopes", &self.scopes);
453        d.field("is_active", &self.is_active);
454        d.finish()
455    }
456}
457
458/// User permissions/scopes
459#[derive(Debug, Clone, Serialize, Deserialize)]
460pub struct UserPermissions {
461    pub username: String,
462    pub scopes: Vec<String>,
463    pub is_active: bool,
464}
465
466impl Default for EnhancedTokenStorage {
467    fn default() -> Self {
468        Self::new()
469    }
470}