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        // One write lock from the validity check to the revoke: a refresh token rotates exactly
404        // once even when many requests present it at the same time (RFC 6749 section 10.4).
405        let mut storage = self.token_storage.write().await;
406        // Validate client credentials
407        if !storage
408            .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
409            .await?
410        {
411            return Err(AuthError::auth_method(
412                "oauth2",
413                "Invalid client credentials",
414            ));
415        }
416
417        // Get and validate refresh token
418        let refresh_token_id = request
419            .refresh_token
420            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
421
422        // CRITICAL FIX: Validate refresh token from storage
423        let stored_token = storage
424            .get_refresh_token(&refresh_token_id)
425            .await?
426            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
427
428        if !stored_token.is_valid() {
429            return Err(AuthError::auth_method(
430                "oauth2",
431                "Refresh token is expired or revoked",
432            ));
433        }
434
435        // Validate token belongs to this client
436        if stored_token.client_id != request.client_id {
437            return Err(AuthError::auth_method(
438                "oauth2",
439                "Refresh token does not belong to client",
440            ));
441        }
442
443        // Parse requested scopes (must be subset of original)
444        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
445        let authorized_scopes = if requested_scopes.is_empty() {
446            stored_token.scopes.clone() // FIXED: Use original scopes from token
447        } else {
448            self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
449        };
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        storage.revoke_refresh_token(&refresh_token_id).await?; // Revoke old token
462
463        let new_refresh_token = RefreshToken::new(
464            stored_token.client_id.clone(),
465            stored_token.user_id.clone(),
466            authorized_scopes.clone(),
467            self.config.refresh_token_lifetime,
468        );
469
470        let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
471
472        Ok(TokenResponse {
473            access_token: access_token.access_token,
474            token_type: "Bearer".to_string(),
475            expires_in: self.config.access_token_lifetime.as_secs(),
476            refresh_token: Some(new_refresh_token_id),
477            scope: Some(authorized_scopes.join(" ")),
478            id_token: None,
479        })
480    }
481
482    /// Handle client credentials grant with proper validation
483    async fn handle_client_credentials_grant(
484        &self,
485        request: TokenRequest,
486    ) -> Result<TokenResponse> {
487        // Validate client credentials
488        let storage = self.token_storage.read().await;
489        let client = storage
490            .get_client_credentials(&request.client_id)
491            .await?
492            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
493
494        // CRITICAL FIX: Validate client secret properly
495        if !storage
496            .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
497            .await?
498        {
499            return Err(AuthError::auth_method(
500                "oauth2",
501                "Invalid client credentials",
502            ));
503        }
504
505        if !client.supports_grant_type("client_credentials") {
506            return Err(AuthError::auth_method(
507                "oauth2",
508                "Client does not support client credentials grant",
509            ));
510        }
511
512        // Parse and validate scopes
513        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
514        let authorized_scopes = requested_scopes
515            .iter()
516            .filter(|scope| client.has_scope(scope))
517            .cloned()
518            .collect::<Vec<_>>();
519
520        if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
521            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
522        }
523
524        drop(storage);
525
526        // Generate access token (no user context for client credentials)
527        let access_token = self
528            .generate_access_token(&request.client_id, None, &authorized_scopes)
529            .await?;
530
531        Ok(TokenResponse {
532            access_token: access_token.access_token,
533            token_type: "Bearer".to_string(),
534            expires_in: self.config.access_token_lifetime.as_secs(),
535            refresh_token: None, // No refresh token for client credentials
536            scope: Some(authorized_scopes.join(" ")),
537            id_token: None,
538        })
539    }
540
541    /// Generate access token with proper validation
542    async fn generate_access_token(
543        &self,
544        client_id: &str,
545        user_id: Option<&str>,
546        scopes: &[String],
547    ) -> Result<AuthToken> {
548        let subject = user_id.unwrap_or(client_id);
549        let mut token = self.token_manager.create_auth_token(
550            subject,
551            scopes.iter().map(|s| s.to_string()).collect(),
552            "oauth2",
553            Some(self.config.access_token_lifetime),
554        )?;
555
556        // Add client_id claim
557        token.add_custom_claim(
558            "client_id".to_string(),
559            serde_json::Value::String(client_id.to_string()),
560        );
561
562        // Add user_id claim if present
563        if let Some(uid) = user_id {
564            token.add_custom_claim(
565                "user_id".to_string(),
566                serde_json::Value::String(uid.to_string()),
567            );
568        }
569
570        Ok(token)
571    }
572
573    /// Parse scopes from scope string
574    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
575        match scope_str {
576            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
577            None => match &self.config.default_scope {
578                Some(default) => Ok(vec![default.clone()]),
579                None => Ok(vec![]),
580            },
581        }
582    }
583
584    /// Authorize scopes based on client and user permissions
585    fn authorize_scopes(
586        &self,
587        client: &EnhancedClientCredentials,
588        user_context: &UserContext,
589        requested_scopes: &[String],
590    ) -> Result<Vec<String>> {
591        let mut authorized = Vec::new();
592
593        for scope in requested_scopes {
594            // Check if client is allowed this scope
595            if client.has_scope(scope) {
596                // Check if user has this scope (if applicable)
597                if user_context.has_scope(scope) {
598                    authorized.push(scope.clone());
599                }
600            }
601        }
602
603        if authorized.is_empty() && !requested_scopes.is_empty() {
604            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
605        }
606
607        Ok(authorized)
608    }
609
610    /// Validate that requested scopes are subset of original scopes
611    fn validate_scope_subset(
612        &self,
613        original_scopes: &[String],
614        requested_scopes: &[String],
615    ) -> Result<Vec<String>> {
616        let mut validated = Vec::new();
617
618        for scope in requested_scopes {
619            if original_scopes.contains(scope) {
620                validated.push(scope.clone());
621            } else {
622                return Err(AuthError::auth_method(
623                    "oauth2",
624                    format!("Requested scope '{}' not in original grant", scope),
625                ));
626            }
627        }
628
629        Ok(validated)
630    }
631
632    /// Validate PKCE code challenge
633    fn validate_pkce_challenge(
634        &self,
635        challenge: &str,
636        verifier: &str,
637        method: &Option<String>,
638    ) -> Result<bool> {
639        let method = method.as_deref().unwrap_or("plain");
640
641        match method {
642            "plain" => Ok(constant_time_compare(
643                challenge.as_bytes(),
644                verifier.as_bytes(),
645            )),
646            "S256" => {
647                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
648                use sha2::{Digest, Sha256};
649
650                let hash = Sha256::digest(verifier.as_bytes());
651                let encoded = URL_SAFE_NO_PAD.encode(hash);
652                Ok(constant_time_compare(
653                    challenge.as_bytes(),
654                    encoded.as_bytes(),
655                ))
656            }
657            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
658        }
659    }
660
661    /// Revoke token (refresh token or access token)
662    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
663        let mut storage = self.token_storage.write().await;
664
665        // Validate client is authorized to revoke this token
666        if client_id.is_empty() {
667            return Err(AuthError::auth_method(
668                "oauth2",
669                "Client ID is required for token revocation",
670            ));
671        }
672
673        // Verify client exists by trying to get its credentials
674        if storage.get_client_credentials(client_id).await.is_err() {
675            return Err(AuthError::auth_method("oauth2", "Invalid client"));
676        }
677
678        // Try to revoke as refresh token first
679        if storage.validate_refresh_token(token).await? {
680            return storage.revoke_refresh_token(token).await;
681        }
682
683        // For access tokens, we would need to maintain a revocation list
684        // This is a simplified implementation
685        Ok(false)
686    }
687
688    /// Clean up expired tokens
689    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
690        let mut storage = self.token_storage.write().await;
691        storage.cleanup_expired_tokens().await
692    }
693
694    /// Authenticate user and create session
695    pub async fn authenticate_user(
696        &self,
697        username: &str,
698        password: &str,
699        scopes: Vec<String>,
700    ) -> Result<UserContext> {
701        // CRITICAL SECURITY FIX: Validate credentials against storage
702        let storage = self.token_storage.read().await;
703
704        // Validate username exists and password is correct using storage
705        if !self
706            .validate_user_credentials_against_storage(&storage, username, password)
707            .await?
708        {
709            return Err(AuthError::auth_method(
710                "oauth2",
711                "Invalid username or password",
712            ));
713        }
714
715        // Validate user is authorized for requested scopes
716        let authorized_scopes = self
717            .validate_user_scopes_against_storage(&storage, username, &scopes)
718            .await?;
719
720        drop(storage);
721
722        // Create user context with validated information
723        let user_context = UserContext::new(
724            self.generate_user_id(username).await?,
725            username.to_string(),
726            self.get_user_email(username).await?,
727        )
728        .with_scopes(authorized_scopes);
729
730        let mut session_store = self.session_store.write().await;
731        session_store.create_session(user_context.clone());
732
733        Ok(user_context)
734    }
735
736    /// Validate user credentials against secure storage
737    async fn validate_user_credentials_against_storage(
738        &self,
739        storage: &EnhancedTokenStorage,
740        username: &str,
741        password: &str,
742    ) -> Result<bool> {
743        // Minimum security requirements - but don't return early to prevent timing attacks
744        let is_empty = username.is_empty() || password.is_empty();
745        let is_too_short = password.len() < 8;
746
747        // Always perform the expensive bcrypt operation to prevent timing attacks
748        match storage.get_user_credentials(username).await {
749            Ok(Some(stored_credentials)) => {
750                // Use bcrypt to verify password against hash
751                use bcrypt::verify;
752                match verify(password, &stored_credentials.password_hash) {
753                    Ok(is_valid) => {
754                        // Only return true if all conditions are met
755                        Ok(is_valid && !is_empty && !is_too_short)
756                    }
757                    Err(_) => {
758                        // Hash verification failed - fail securely
759                        Ok(false)
760                    }
761                }
762            }
763            Ok(None) => {
764                // User not found - still do dummy bcrypt operation to prevent timing attacks
765                use bcrypt::verify;
766                let _dummy_result = verify(
767                    password,
768                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
769                );
770                Ok(false)
771            }
772            Err(_) => {
773                // Storage error - still do dummy bcrypt operation to prevent timing attacks
774                use bcrypt::verify;
775                let _dummy_result = verify(
776                    password,
777                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
778                );
779                Ok(false)
780            }
781        }
782    }
783
784    /// Validate user is authorized for requested scopes using storage
785    async fn validate_user_scopes_against_storage(
786        &self,
787        storage: &EnhancedTokenStorage,
788        username: &str,
789        requested_scopes: &[String],
790    ) -> Result<Vec<String>> {
791        // Get user permissions from storage
792        let user_permissions = match storage.get_user_permissions(username).await {
793            Ok(Some(permissions)) => permissions.scopes,
794            Ok(None) => {
795                return Err(AuthError::auth_method(
796                    "oauth2",
797                    "User not found in permission store",
798                ));
799            }
800            Err(_) => {
801                return Err(AuthError::auth_method(
802                    "oauth2",
803                    "Failed to retrieve user permissions",
804                ));
805            }
806        };
807
808        let mut authorized = Vec::new();
809        for scope in requested_scopes {
810            if user_permissions.contains(scope) {
811                authorized.push(scope.clone());
812            }
813        }
814
815        // If no scopes requested, give default read scope for valid users
816        if authorized.is_empty() && !requested_scopes.is_empty() {
817            return Err(AuthError::auth_method(
818                "oauth2",
819                "User not authorized for requested scopes",
820            ));
821        }
822
823        if authorized.is_empty() {
824            // Check if user has at least read permission for default scope
825            if user_permissions.contains(&"read".to_string()) {
826                authorized.push("read".to_string());
827            } else {
828                return Err(AuthError::auth_method(
829                    "oauth2",
830                    "User has no authorized scopes",
831                ));
832            }
833        }
834
835        Ok(authorized)
836    }
837
838    /// Generate consistent user ID
839    async fn generate_user_id(&self, username: &str) -> Result<String> {
840        // In production, this would be the user's UUID from the database
841        // For now, create a deterministic but unique ID
842        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
843        let hash_str = format!("{:x}", hash);
844        Ok(format!("user_{}", &hash_str[0..16]))
845    }
846
847    /// Get user email from user store
848    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
849        // In production, this would query the user database
850        Ok(Some(format!("{}@example.com", username)))
851    }
852
853    /// Get user context from session
854    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
855        let session_store = self.session_store.read().await;
856        Ok(session_store.get_session(session_id).cloned())
857    }
858
859    /// Invalidate user session
860    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
861        let mut session_store = self.session_store.write().await;
862        Ok(session_store.invalidate_session(session_id))
863    }
864}