Skip to main content

auth_framework/server/oauth/
oauth2_enhanced_storage.rs

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