Skip to main content

auth_framework/
oauth2_server.rs

1//! OAuth 2.0 Authorization Server Implementation
2//!
3//! This module provides a fully secure OAuth 2.0 authorization server implementation
4//! with all critical vulnerabilities addressed and proper validation.
5
6use crate::errors::{AuthError, Result};
7use crate::oauth2_enhanced_storage::{
8    EnhancedAuthorizationCode, EnhancedClientCredentials, EnhancedTokenStorage, RefreshToken,
9};
10use crate::security::secure_utils::constant_time_compare;
11use crate::tokens::{AuthToken, TokenManager};
12use crate::user_context::{SessionStore, UserContext};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::sync::RwLock;
18
19/// OAuth 2.0 grant types
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21pub enum GrantType {
22    AuthorizationCode,
23    RefreshToken,
24    ClientCredentials,
25    DeviceCode,
26    TokenExchange,
27}
28
29impl std::fmt::Display for GrantType {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            GrantType::AuthorizationCode => write!(f, "authorization_code"),
33            GrantType::RefreshToken => write!(f, "refresh_token"),
34            GrantType::ClientCredentials => write!(f, "client_credentials"),
35            GrantType::DeviceCode => write!(f, "urn:ietf:params:oauth:grant-type:device_code"),
36            GrantType::TokenExchange => {
37                write!(f, "urn:ietf:params:oauth:grant-type:token-exchange")
38            }
39        }
40    }
41}
42
43/// OAuth 2.0 response types
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45pub enum ResponseType {
46    Code,
47    Token,
48    IdToken,
49}
50
51/// OAuth 2.0 server configuration
52#[derive(Debug, Clone)]
53pub struct OAuth2Config {
54    /// Authorization server issuer identifier
55    pub issuer: String,
56    /// Authorization code lifetime
57    pub authorization_code_lifetime: Duration,
58    /// Access token lifetime
59    pub access_token_lifetime: Duration,
60    /// Refresh token lifetime
61    pub refresh_token_lifetime: Duration,
62    /// Device code lifetime
63    pub device_code_lifetime: Duration,
64    /// Default scope if none specified
65    pub default_scope: Option<String>,
66    /// Maximum scope lifetime
67    pub max_scope_lifetime: Duration,
68    /// Require PKCE for public clients
69    pub require_pkce: bool,
70    /// Enable token introspection
71    pub enable_introspection: bool,
72    /// Enable token revocation
73    pub enable_revocation: bool,
74}
75
76impl Default for OAuth2Config {
77    fn default() -> Self {
78        Self {
79            issuer: "https://auth.example.com".to_string(),
80            authorization_code_lifetime: Duration::from_secs(600), // 10 minutes
81            access_token_lifetime: Duration::from_secs(3600),      // 1 hour
82            refresh_token_lifetime: Duration::from_secs(86400 * 7), // 7 days
83            device_code_lifetime: Duration::from_secs(600),        // 10 minutes
84            default_scope: Some("read".to_string()),
85            max_scope_lifetime: Duration::from_secs(86400 * 30), // 30 days
86            require_pkce: true,
87            enable_introspection: true,
88            enable_revocation: true,
89        }
90    }
91}
92
93/// Token request structure
94#[derive(Clone, Serialize, Deserialize, Default)]
95pub struct TokenRequest {
96    pub grant_type: String,
97    pub client_id: String,
98    pub client_secret: Option<String>,
99    pub code: Option<String>,
100    pub redirect_uri: Option<String>,
101    pub refresh_token: Option<String>,
102    pub scope: Option<String>,
103    pub code_verifier: Option<String>,
104    pub username: Option<String>,
105    pub password: Option<String>,
106    pub device_code: Option<String>,
107}
108
109impl std::fmt::Debug for TokenRequest {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        let mut d = f.debug_struct("TokenRequest");
112        d.field("grant_type", &self.grant_type);
113        d.field("client_id", &self.client_id);
114        d.field(
115            "client_secret",
116            &crate::utils::redact::redacted(&self.client_secret),
117        );
118        d.field("code", &crate::utils::redact::redacted(&self.code));
119        d.field("redirect_uri", &self.redirect_uri);
120        d.field(
121            "refresh_token",
122            &crate::utils::redact::redacted(&self.refresh_token),
123        );
124        d.field("scope", &self.scope);
125        d.field(
126            "code_verifier",
127            &crate::utils::redact::redacted(&self.code_verifier),
128        );
129        d.field("username", &self.username);
130        d.field("password", &crate::utils::redact::redacted(&self.password));
131        d.field(
132            "device_code",
133            &crate::utils::redact::redacted(&self.device_code),
134        );
135        d.finish()
136    }
137}
138
139/// Token response structure
140#[derive(Clone, Serialize, Deserialize)]
141pub struct TokenResponse {
142    pub access_token: String,
143    pub token_type: String,
144    pub expires_in: u64,
145    pub refresh_token: Option<String>,
146    pub scope: Option<String>,
147    pub id_token: Option<String>,
148}
149
150impl std::fmt::Debug for TokenResponse {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        let mut d = f.debug_struct("TokenResponse");
153        d.field(
154            "access_token",
155            &crate::utils::redact::redacted(&self.access_token),
156        );
157        d.field("token_type", &self.token_type);
158        d.field("expires_in", &self.expires_in);
159        d.field(
160            "refresh_token",
161            &crate::utils::redact::redacted(&self.refresh_token),
162        );
163        d.field("scope", &self.scope);
164        d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
165        d.finish()
166    }
167}
168
169/// Authorization request structure
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct AuthorizationRequest {
172    pub client_id: String,
173    pub response_type: String,
174    pub redirect_uri: String,
175    pub scope: Option<String>,
176    pub state: Option<String>,
177    pub code_challenge: Option<String>,
178    pub code_challenge_method: Option<String>,
179    pub nonce: Option<String>,
180}
181
182/// OAuth 2.0 Authorization Server
183pub struct OAuth2Server {
184    config: OAuth2Config,
185    token_storage: Arc<RwLock<EnhancedTokenStorage>>,
186    session_store: Arc<RwLock<SessionStore>>,
187    token_manager: Arc<TokenManager>,
188}
189
190impl OAuth2Server {
191    pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
192        Ok(Self {
193            config,
194            token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
195            session_store: Arc::new(RwLock::new(SessionStore::new())),
196            token_manager,
197        })
198    }
199
200    /// Register a confidential client with proper secret validation
201    pub async fn register_confidential_client(
202        &self,
203        client_id: String,
204        client_secret: &str,
205        redirect_uris: Vec<String>,
206        allowed_scopes: Vec<String>,
207        grant_types: Vec<String>,
208    ) -> Result<()> {
209        // Validate client secret strength
210        if client_secret.len() < 32 {
211            return Err(AuthError::auth_method(
212                "oauth2",
213                "Client secret must be at least 32 characters",
214            ));
215        }
216
217        let credentials = EnhancedClientCredentials::new_confidential(
218            client_id,
219            client_secret,
220            redirect_uris,
221            allowed_scopes,
222            grant_types,
223        )?;
224
225        let mut storage = self.token_storage.write().await;
226        storage.store_client_credentials(credentials).await?;
227
228        Ok(())
229    }
230
231    /// Register a public client (PKCE required)
232    pub async fn register_public_client(
233        &self,
234        client_id: String,
235        redirect_uris: Vec<String>,
236        allowed_scopes: Vec<String>,
237        grant_types: Vec<String>,
238    ) -> Result<()> {
239        let credentials = EnhancedClientCredentials::new_public(
240            client_id,
241            redirect_uris,
242            allowed_scopes,
243            grant_types,
244        );
245
246        let mut storage = self.token_storage.write().await;
247        storage.store_client_credentials(credentials).await?;
248
249        Ok(())
250    }
251
252    /// Create authorization code with proper user context
253    pub async fn create_authorization_code(
254        &self,
255        request: AuthorizationRequest,
256        user_context: UserContext,
257    ) -> Result<EnhancedAuthorizationCode> {
258        // Validate client exists and supports authorization code flow
259        let storage = self.token_storage.read().await;
260        let client = storage
261            .get_client_credentials(&request.client_id)
262            .await?
263            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
264
265        if !client.supports_grant_type("authorization_code") {
266            return Err(AuthError::auth_method(
267                "oauth2",
268                "Client does not support authorization code grant",
269            ));
270        }
271
272        if !client.redirect_uris.contains(&request.redirect_uri) {
273            return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
274        }
275
276        // Parse and validate scopes
277        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
278        let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
279
280        // Create authorization code with proper user context
281        let auth_code = EnhancedAuthorizationCode::new(
282            client.client_id.clone(),
283            user_context.user_id.clone(), // FIXED: Use real user ID from context
284            request.redirect_uri,
285            authorized_scopes,
286            request.code_challenge,
287            request.code_challenge_method,
288            self.config.authorization_code_lifetime,
289        );
290
291        // Store authorization code
292        drop(storage);
293        let mut storage = self.token_storage.write().await;
294        storage.store_authorization_code(auth_code.clone()).await?;
295
296        Ok(auth_code)
297    }
298
299    /// Handle token exchange with comprehensive validation
300    pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
301        match request.grant_type.as_str() {
302            "authorization_code" => self.handle_authorization_code_grant(request).await,
303            "refresh_token" => self.handle_refresh_token_grant(request).await,
304            "client_credentials" => self.handle_client_credentials_grant(request).await,
305            _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
306        }
307    }
308
309    /// Handle authorization code grant with proper validation
310    async fn handle_authorization_code_grant(
311        &self,
312        request: TokenRequest,
313    ) -> Result<TokenResponse> {
314        // Validate client credentials FIRST
315        let storage = self.token_storage.read().await;
316        let _client = storage
317            .get_client_credentials(&request.client_id)
318            .await?
319            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
320
321        // CRITICAL FIX: Validate client secret properly
322        if !storage
323            .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
324            .await?
325        {
326            return Err(AuthError::auth_method(
327                "oauth2",
328                "Invalid client credentials",
329            ));
330        }
331
332        // Get and validate authorization code
333        let code = request
334            .code
335            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;
336
337        drop(storage);
338        let mut storage = self.token_storage.write().await;
339        let auth_code = storage
340            .consume_authorization_code(&code)
341            .await?
342            .ok_or_else(|| {
343                AuthError::auth_method("oauth2", "Invalid or expired authorization code")
344            })?;
345
346        // Validate code belongs to this client
347        if auth_code.client_id != request.client_id {
348            return Err(AuthError::auth_method(
349                "oauth2",
350                "Authorization code does not belong to client",
351            ));
352        }
353
354        // Validate PKCE if required
355        if let Some(challenge) = &auth_code.code_challenge {
356            let verifier = request
357                .code_verifier
358                .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;
359
360            if !self.validate_pkce_challenge(
361                challenge,
362                &verifier,
363                &auth_code.code_challenge_method,
364            )? {
365                return Err(AuthError::auth_method(
366                    "oauth2",
367                    "Invalid PKCE code verifier",
368                ));
369            }
370        }
371
372        // Generate tokens with proper user context
373        let access_token = self
374            .generate_access_token(
375                &auth_code.client_id,
376                Some(&auth_code.user_id), // FIXED: Use actual user ID from auth code
377                &auth_code.scopes,
378            )
379            .await?;
380
381        // Generate refresh token
382        let refresh_token = RefreshToken::new(
383            auth_code.client_id.clone(),
384            auth_code.user_id.clone(), // FIXED: Use actual user ID
385            auth_code.scopes.clone(),  // FIXED: Use authorized scopes from auth code
386            self.config.refresh_token_lifetime,
387        );
388
389        let refresh_token_id = storage.store_refresh_token(refresh_token).await?;
390
391        Ok(TokenResponse {
392            access_token: access_token.access_token,
393            token_type: "Bearer".to_string(),
394            expires_in: self.config.access_token_lifetime.as_secs(),
395            refresh_token: Some(refresh_token_id),
396            scope: Some(auth_code.scopes.join(" ")),
397            id_token: None,
398        })
399    }
400
401    /// Handle refresh token grant with proper validation
402    async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
403        // Validate client credentials
404        let storage = self.token_storage.read().await;
405        if !storage
406            .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
407            .await?
408        {
409            return Err(AuthError::auth_method(
410                "oauth2",
411                "Invalid client credentials",
412            ));
413        }
414
415        // Get and validate refresh token
416        let refresh_token_id = request
417            .refresh_token
418            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
419
420        // CRITICAL FIX: Validate refresh token from storage
421        let stored_token = storage
422            .get_refresh_token(&refresh_token_id)
423            .await?
424            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
425
426        if !stored_token.is_valid() {
427            return Err(AuthError::auth_method(
428                "oauth2",
429                "Refresh token is expired or revoked",
430            ));
431        }
432
433        // Validate token belongs to this client
434        if stored_token.client_id != request.client_id {
435            return Err(AuthError::auth_method(
436                "oauth2",
437                "Refresh token does not belong to client",
438            ));
439        }
440
441        // Parse requested scopes (must be subset of original)
442        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
443        let authorized_scopes = if requested_scopes.is_empty() {
444            stored_token.scopes.clone() // FIXED: Use original scopes from token
445        } else {
446            self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
447        };
448
449        drop(storage);
450
451        // Generate new access token
452        let access_token = self
453            .generate_access_token(
454                &stored_token.client_id,
455                Some(&stored_token.user_id), // FIXED: Use actual user ID from token
456                &authorized_scopes,
457            )
458            .await?;
459
460        // Generate new refresh token
461        let mut storage = self.token_storage.write().await;
462        storage.revoke_refresh_token(&refresh_token_id).await?; // Revoke old token
463
464        let new_refresh_token = RefreshToken::new(
465            stored_token.client_id.clone(),
466            stored_token.user_id.clone(),
467            authorized_scopes.clone(),
468            self.config.refresh_token_lifetime,
469        );
470
471        let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
472
473        Ok(TokenResponse {
474            access_token: access_token.access_token,
475            token_type: "Bearer".to_string(),
476            expires_in: self.config.access_token_lifetime.as_secs(),
477            refresh_token: Some(new_refresh_token_id),
478            scope: Some(authorized_scopes.join(" ")),
479            id_token: None,
480        })
481    }
482
483    /// Handle client credentials grant with proper validation
484    async fn handle_client_credentials_grant(
485        &self,
486        request: TokenRequest,
487    ) -> Result<TokenResponse> {
488        // Validate client credentials
489        let storage = self.token_storage.read().await;
490        let client = storage
491            .get_client_credentials(&request.client_id)
492            .await?
493            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
494
495        // CRITICAL FIX: Validate client secret properly
496        if !storage
497            .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
498            .await?
499        {
500            return Err(AuthError::auth_method(
501                "oauth2",
502                "Invalid client credentials",
503            ));
504        }
505
506        if !client.supports_grant_type("client_credentials") {
507            return Err(AuthError::auth_method(
508                "oauth2",
509                "Client does not support client credentials grant",
510            ));
511        }
512
513        // Parse and validate scopes
514        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
515        let authorized_scopes = requested_scopes
516            .iter()
517            .filter(|scope| client.has_scope(scope))
518            .cloned()
519            .collect::<Vec<_>>();
520
521        if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
522            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
523        }
524
525        drop(storage);
526
527        // Generate access token (no user context for client credentials)
528        let access_token = self
529            .generate_access_token(&request.client_id, None, &authorized_scopes)
530            .await?;
531
532        Ok(TokenResponse {
533            access_token: access_token.access_token,
534            token_type: "Bearer".to_string(),
535            expires_in: self.config.access_token_lifetime.as_secs(),
536            refresh_token: None, // No refresh token for client credentials
537            scope: Some(authorized_scopes.join(" ")),
538            id_token: None,
539        })
540    }
541
542    /// Generate access token with proper validation
543    async fn generate_access_token(
544        &self,
545        client_id: &str,
546        user_id: Option<&str>,
547        scopes: &[String],
548    ) -> Result<AuthToken> {
549        let subject = user_id.unwrap_or(client_id);
550        let mut token = self.token_manager.create_auth_token(
551            subject,
552            scopes.iter().map(|s| s.to_string()).collect(),
553            "oauth2",
554            Some(self.config.access_token_lifetime),
555        )?;
556
557        // Add client_id claim
558        token.add_custom_claim(
559            "client_id".to_string(),
560            serde_json::Value::String(client_id.to_string()),
561        );
562
563        // Add user_id claim if present
564        if let Some(uid) = user_id {
565            token.add_custom_claim(
566                "user_id".to_string(),
567                serde_json::Value::String(uid.to_string()),
568            );
569        }
570
571        Ok(token)
572    }
573
574    /// Parse scopes from scope string
575    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
576        match scope_str {
577            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
578            None => match &self.config.default_scope {
579                Some(default) => Ok(vec![default.clone()]),
580                None => Ok(vec![]),
581            },
582        }
583    }
584
585    /// Authorize scopes based on client and user permissions
586    fn authorize_scopes(
587        &self,
588        client: &EnhancedClientCredentials,
589        user_context: &UserContext,
590        requested_scopes: &[String],
591    ) -> Result<Vec<String>> {
592        let mut authorized = Vec::new();
593
594        for scope in requested_scopes {
595            // Check if client is allowed this scope
596            if client.has_scope(scope) {
597                // Check if user has this scope (if applicable)
598                if user_context.has_scope(scope) {
599                    authorized.push(scope.clone());
600                }
601            }
602        }
603
604        if authorized.is_empty() && !requested_scopes.is_empty() {
605            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
606        }
607
608        Ok(authorized)
609    }
610
611    /// Validate that requested scopes are subset of original scopes
612    fn validate_scope_subset(
613        &self,
614        original_scopes: &[String],
615        requested_scopes: &[String],
616    ) -> Result<Vec<String>> {
617        let mut validated = Vec::new();
618
619        for scope in requested_scopes {
620            if original_scopes.contains(scope) {
621                validated.push(scope.clone());
622            } else {
623                return Err(AuthError::auth_method(
624                    "oauth2",
625                    format!("Requested scope '{}' not in original grant", scope),
626                ));
627            }
628        }
629
630        Ok(validated)
631    }
632
633    /// Validate PKCE code challenge
634    fn validate_pkce_challenge(
635        &self,
636        challenge: &str,
637        verifier: &str,
638        method: &Option<String>,
639    ) -> Result<bool> {
640        let method = method.as_deref().unwrap_or("plain");
641
642        match method {
643            "plain" => Ok(constant_time_compare(
644                challenge.as_bytes(),
645                verifier.as_bytes(),
646            )),
647            "S256" => {
648                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
649                use sha2::{Digest, Sha256};
650
651                let hash = Sha256::digest(verifier.as_bytes());
652                let encoded = URL_SAFE_NO_PAD.encode(hash);
653                Ok(constant_time_compare(
654                    challenge.as_bytes(),
655                    encoded.as_bytes(),
656                ))
657            }
658            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
659        }
660    }
661
662    /// Revoke token (refresh token or access token)
663    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
664        let mut storage = self.token_storage.write().await;
665
666        // Validate client is authorized to revoke this token
667        if client_id.is_empty() {
668            return Err(AuthError::auth_method(
669                "oauth2",
670                "Client ID is required for token revocation",
671            ));
672        }
673
674        // Verify client exists by trying to get its credentials
675        if storage.get_client_credentials(client_id).await.is_err() {
676            return Err(AuthError::auth_method("oauth2", "Invalid client"));
677        }
678
679        // Try to revoke as refresh token first
680        if storage.validate_refresh_token(token).await? {
681            return storage.revoke_refresh_token(token).await;
682        }
683
684        // For access tokens, we would need to maintain a revocation list
685        // This is a simplified implementation
686        Ok(false)
687    }
688
689    /// Clean up expired tokens
690    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
691        let mut storage = self.token_storage.write().await;
692        storage.cleanup_expired_tokens().await
693    }
694
695    /// Authenticate user and create session
696    pub async fn authenticate_user(
697        &self,
698        username: &str,
699        password: &str,
700        scopes: Vec<String>,
701    ) -> Result<UserContext> {
702        // CRITICAL SECURITY FIX: Validate credentials against storage
703        let storage = self.token_storage.read().await;
704
705        // Validate username exists and password is correct using storage
706        if !self
707            .validate_user_credentials_against_storage(&storage, username, password)
708            .await?
709        {
710            return Err(AuthError::auth_method(
711                "oauth2",
712                "Invalid username or password",
713            ));
714        }
715
716        // Validate user is authorized for requested scopes
717        let authorized_scopes = self
718            .validate_user_scopes_against_storage(&storage, username, &scopes)
719            .await?;
720
721        drop(storage);
722
723        // Create user context with validated information
724        let user_context = UserContext::new(
725            self.generate_user_id(username).await?,
726            username.to_string(),
727            self.get_user_email(username).await?,
728        )
729        .with_scopes(authorized_scopes);
730
731        let mut session_store = self.session_store.write().await;
732        session_store.create_session(user_context.clone());
733
734        Ok(user_context)
735    }
736
737    /// Validate user credentials against secure storage
738    async fn validate_user_credentials_against_storage(
739        &self,
740        storage: &EnhancedTokenStorage,
741        username: &str,
742        password: &str,
743    ) -> Result<bool> {
744        // Minimum security requirements - but don't return early to prevent timing attacks
745        let is_empty = username.is_empty() || password.is_empty();
746        let is_too_short = password.len() < 8;
747
748        // Always perform the expensive bcrypt operation to prevent timing attacks
749        match storage.get_user_credentials(username).await {
750            Ok(Some(stored_credentials)) => {
751                // Use bcrypt to verify password against hash
752                use bcrypt::verify;
753                match verify(password, &stored_credentials.password_hash) {
754                    Ok(is_valid) => {
755                        // Only return true if all conditions are met
756                        Ok(is_valid && !is_empty && !is_too_short)
757                    }
758                    Err(_) => {
759                        // Hash verification failed - fail securely
760                        Ok(false)
761                    }
762                }
763            }
764            Ok(None) => {
765                // User not found - still do dummy bcrypt operation to prevent timing attacks
766                use bcrypt::verify;
767                let _dummy_result = verify(
768                    password,
769                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
770                );
771                Ok(false)
772            }
773            Err(_) => {
774                // Storage error - still do dummy bcrypt operation to prevent timing attacks
775                use bcrypt::verify;
776                let _dummy_result = verify(
777                    password,
778                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
779                );
780                Ok(false)
781            }
782        }
783    }
784
785    /// Validate user is authorized for requested scopes using storage
786    async fn validate_user_scopes_against_storage(
787        &self,
788        storage: &EnhancedTokenStorage,
789        username: &str,
790        requested_scopes: &[String],
791    ) -> Result<Vec<String>> {
792        // Get user permissions from storage
793        let user_permissions = match storage.get_user_permissions(username).await {
794            Ok(Some(permissions)) => permissions.scopes,
795            Ok(None) => {
796                return Err(AuthError::auth_method(
797                    "oauth2",
798                    "User not found in permission store",
799                ));
800            }
801            Err(_) => {
802                return Err(AuthError::auth_method(
803                    "oauth2",
804                    "Failed to retrieve user permissions",
805                ));
806            }
807        };
808
809        let mut authorized = Vec::new();
810        for scope in requested_scopes {
811            if user_permissions.contains(scope) {
812                authorized.push(scope.clone());
813            }
814        }
815
816        // If no scopes requested, give default read scope for valid users
817        if authorized.is_empty() && !requested_scopes.is_empty() {
818            return Err(AuthError::auth_method(
819                "oauth2",
820                "User not authorized for requested scopes",
821            ));
822        }
823
824        if authorized.is_empty() {
825            // Check if user has at least read permission for default scope
826            if user_permissions.contains(&"read".to_string()) {
827                authorized.push("read".to_string());
828            } else {
829                return Err(AuthError::auth_method(
830                    "oauth2",
831                    "User has no authorized scopes",
832                ));
833            }
834        }
835
836        Ok(authorized)
837    }
838
839    /// Generate consistent user ID
840    async fn generate_user_id(&self, username: &str) -> Result<String> {
841        // In production, this would be the user's UUID from the database
842        // For now, create a deterministic but unique ID
843        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
844        let hash_str = format!("{:x}", hash);
845        Ok(format!("user_{}", &hash_str[0..16]))
846    }
847
848    /// Get user email from user store
849    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
850        // In production, this would query the user database
851        Ok(Some(format!("{}@example.com", username)))
852    }
853
854    /// Get user context from session
855    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
856        let session_store = self.session_store.read().await;
857        Ok(session_store.get_session(session_id).cloned())
858    }
859
860    /// Invalidate user session
861    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
862        let mut session_store = self.session_store.write().await;
863        Ok(session_store.invalidate_session(session_id))
864    }
865}