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        // The JWT carries the client: it is delegated access, not the user's own session.
550        let mut token = self.token_manager.create_client_auth_token(
551            subject,
552            client_id,
553            scopes.iter().map(|s| s.to_string()).collect(),
554            "oauth2",
555            Some(self.config.access_token_lifetime),
556        )?;
557
558        // Add client_id claim
559        token.add_custom_claim(
560            "client_id".to_string(),
561            serde_json::Value::String(client_id.to_string()),
562        );
563
564        // Add user_id claim if present
565        if let Some(uid) = user_id {
566            token.add_custom_claim(
567                "user_id".to_string(),
568                serde_json::Value::String(uid.to_string()),
569            );
570        }
571
572        Ok(token)
573    }
574
575    /// Parse scopes from scope string
576    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
577        match scope_str {
578            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
579            None => match &self.config.default_scope {
580                Some(default) => Ok(vec![default.clone()]),
581                None => Ok(vec![]),
582            },
583        }
584    }
585
586    /// Authorize scopes based on client and user permissions
587    fn authorize_scopes(
588        &self,
589        client: &EnhancedClientCredentials,
590        user_context: &UserContext,
591        requested_scopes: &[String],
592    ) -> Result<Vec<String>> {
593        let mut authorized = Vec::new();
594
595        for scope in requested_scopes {
596            // Check if client is allowed this scope
597            if client.has_scope(scope) {
598                // Check if user has this scope (if applicable)
599                if user_context.has_scope(scope) {
600                    authorized.push(scope.clone());
601                }
602            }
603        }
604
605        if authorized.is_empty() && !requested_scopes.is_empty() {
606            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
607        }
608
609        Ok(authorized)
610    }
611
612    /// Validate that requested scopes are subset of original scopes
613    fn validate_scope_subset(
614        &self,
615        original_scopes: &[String],
616        requested_scopes: &[String],
617    ) -> Result<Vec<String>> {
618        let mut validated = Vec::new();
619
620        for scope in requested_scopes {
621            if original_scopes.contains(scope) {
622                validated.push(scope.clone());
623            } else {
624                return Err(AuthError::auth_method(
625                    "oauth2",
626                    format!("Requested scope '{}' not in original grant", scope),
627                ));
628            }
629        }
630
631        Ok(validated)
632    }
633
634    /// Validate PKCE code challenge
635    fn validate_pkce_challenge(
636        &self,
637        challenge: &str,
638        verifier: &str,
639        method: &Option<String>,
640    ) -> Result<bool> {
641        let method = method.as_deref().unwrap_or("plain");
642
643        match method {
644            "plain" => Ok(constant_time_compare(
645                challenge.as_bytes(),
646                verifier.as_bytes(),
647            )),
648            "S256" => {
649                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
650                use sha2::{Digest, Sha256};
651
652                let hash = Sha256::digest(verifier.as_bytes());
653                let encoded = URL_SAFE_NO_PAD.encode(hash);
654                Ok(constant_time_compare(
655                    challenge.as_bytes(),
656                    encoded.as_bytes(),
657                ))
658            }
659            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
660        }
661    }
662
663    /// Revoke token (refresh token or access token)
664    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
665        let mut storage = self.token_storage.write().await;
666
667        // Validate client is authorized to revoke this token
668        if client_id.is_empty() {
669            return Err(AuthError::auth_method(
670                "oauth2",
671                "Client ID is required for token revocation",
672            ));
673        }
674
675        // Verify client exists by trying to get its credentials
676        if storage.get_client_credentials(client_id).await.is_err() {
677            return Err(AuthError::auth_method("oauth2", "Invalid client"));
678        }
679
680        // Try to revoke as refresh token first
681        if storage.validate_refresh_token(token).await? {
682            return storage.revoke_refresh_token(token).await;
683        }
684
685        // For access tokens, we would need to maintain a revocation list
686        // This is a simplified implementation
687        Ok(false)
688    }
689
690    /// Clean up expired tokens
691    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
692        let mut storage = self.token_storage.write().await;
693        storage.cleanup_expired_tokens().await
694    }
695
696    /// Authenticate user and create session
697    pub async fn authenticate_user(
698        &self,
699        username: &str,
700        password: &str,
701        scopes: Vec<String>,
702    ) -> Result<UserContext> {
703        // CRITICAL SECURITY FIX: Validate credentials against storage
704        let storage = self.token_storage.read().await;
705
706        // Validate username exists and password is correct using storage
707        if !self
708            .validate_user_credentials_against_storage(&storage, username, password)
709            .await?
710        {
711            return Err(AuthError::auth_method(
712                "oauth2",
713                "Invalid username or password",
714            ));
715        }
716
717        // Validate user is authorized for requested scopes
718        let authorized_scopes = self
719            .validate_user_scopes_against_storage(&storage, username, &scopes)
720            .await?;
721
722        drop(storage);
723
724        // Create user context with validated information
725        let user_context = UserContext::new(
726            self.generate_user_id(username).await?,
727            username.to_string(),
728            self.get_user_email(username).await?,
729        )
730        .with_scopes(authorized_scopes);
731
732        let mut session_store = self.session_store.write().await;
733        session_store.create_session(user_context.clone());
734
735        Ok(user_context)
736    }
737
738    /// Validate user credentials against secure storage
739    async fn validate_user_credentials_against_storage(
740        &self,
741        storage: &EnhancedTokenStorage,
742        username: &str,
743        password: &str,
744    ) -> Result<bool> {
745        // Minimum security requirements - but don't return early to prevent timing attacks
746        let is_empty = username.is_empty() || password.is_empty();
747        let is_too_short = password.len() < 8;
748
749        // Always perform the expensive bcrypt operation to prevent timing attacks
750        match storage.get_user_credentials(username).await {
751            Ok(Some(stored_credentials)) => {
752                // Use bcrypt to verify password against hash
753                use bcrypt::verify;
754                match verify(password, &stored_credentials.password_hash) {
755                    Ok(is_valid) => {
756                        // Only return true if all conditions are met
757                        Ok(is_valid && !is_empty && !is_too_short)
758                    }
759                    Err(_) => {
760                        // Hash verification failed - fail securely
761                        Ok(false)
762                    }
763                }
764            }
765            Ok(None) => {
766                // User not found - still do dummy bcrypt operation to prevent timing attacks
767                use bcrypt::verify;
768                let _dummy_result = verify(
769                    password,
770                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
771                );
772                Ok(false)
773            }
774            Err(_) => {
775                // Storage error - still do dummy bcrypt operation to prevent timing attacks
776                use bcrypt::verify;
777                let _dummy_result = verify(
778                    password,
779                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
780                );
781                Ok(false)
782            }
783        }
784    }
785
786    /// Validate user is authorized for requested scopes using storage
787    async fn validate_user_scopes_against_storage(
788        &self,
789        storage: &EnhancedTokenStorage,
790        username: &str,
791        requested_scopes: &[String],
792    ) -> Result<Vec<String>> {
793        // Get user permissions from storage
794        let user_permissions = match storage.get_user_permissions(username).await {
795            Ok(Some(permissions)) => permissions.scopes,
796            Ok(None) => {
797                return Err(AuthError::auth_method(
798                    "oauth2",
799                    "User not found in permission store",
800                ));
801            }
802            Err(_) => {
803                return Err(AuthError::auth_method(
804                    "oauth2",
805                    "Failed to retrieve user permissions",
806                ));
807            }
808        };
809
810        let mut authorized = Vec::new();
811        for scope in requested_scopes {
812            if user_permissions.contains(scope) {
813                authorized.push(scope.clone());
814            }
815        }
816
817        // If no scopes requested, give default read scope for valid users
818        if authorized.is_empty() && !requested_scopes.is_empty() {
819            return Err(AuthError::auth_method(
820                "oauth2",
821                "User not authorized for requested scopes",
822            ));
823        }
824
825        if authorized.is_empty() {
826            // Check if user has at least read permission for default scope
827            if user_permissions.contains(&"read".to_string()) {
828                authorized.push("read".to_string());
829            } else {
830                return Err(AuthError::auth_method(
831                    "oauth2",
832                    "User has no authorized scopes",
833                ));
834            }
835        }
836
837        Ok(authorized)
838    }
839
840    /// Generate consistent user ID
841    async fn generate_user_id(&self, username: &str) -> Result<String> {
842        // In production, this would be the user's UUID from the database
843        // For now, create a deterministic but unique ID
844        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
845        let hash_str = format!("{:x}", hash);
846        Ok(format!("user_{}", &hash_str[0..16]))
847    }
848
849    /// Get user email from user store
850    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
851        // In production, this would query the user database
852        Ok(Some(format!("{}@example.com", username)))
853    }
854
855    /// Get user context from session
856    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
857        let session_store = self.session_store.read().await;
858        Ok(session_store.get_session(session_id).cloned())
859    }
860
861    /// Invalidate user session
862    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
863        let mut session_store = self.session_store.write().await;
864        Ok(session_store.invalidate_session(session_id))
865    }
866}