Skip to main content

auth_framework/server/oauth/
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::security::secure_utils::constant_time_compare;
8use crate::server::oauth::oauth2_enhanced_storage::{
9    EnhancedAuthorizationCode, EnhancedClientCredentials, EnhancedTokenStorage, RefreshToken,
10};
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
43impl std::str::FromStr for GrantType {
44    type Err = AuthError;
45
46    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
47        match s {
48            "authorization_code" => Ok(Self::AuthorizationCode),
49            "refresh_token" => Ok(Self::RefreshToken),
50            "client_credentials" => Ok(Self::ClientCredentials),
51            "urn:ietf:params:oauth:grant-type:device_code" => Ok(Self::DeviceCode),
52            "urn:ietf:params:oauth:grant-type:token-exchange" => Ok(Self::TokenExchange),
53            other => Err(AuthError::auth_method(
54                "oauth2",
55                format!("Unsupported grant type: {other}"),
56            )),
57        }
58    }
59}
60
61/// OAuth 2.0 response types
62#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
63pub enum ResponseType {
64    Code,
65    Token,
66    IdToken,
67}
68
69impl std::fmt::Display for ResponseType {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            ResponseType::Code => write!(f, "code"),
73            ResponseType::Token => write!(f, "token"),
74            ResponseType::IdToken => write!(f, "id_token"),
75        }
76    }
77}
78
79impl std::str::FromStr for ResponseType {
80    type Err = AuthError;
81
82    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
83        match s {
84            "code" => Ok(Self::Code),
85            "token" => Ok(Self::Token),
86            "id_token" => Ok(Self::IdToken),
87            other => Err(AuthError::auth_method(
88                "oauth2",
89                format!("Unsupported response type: {other}"),
90            )),
91        }
92    }
93}
94
95/// OAuth 2.0 server configuration
96#[derive(Debug, Clone)]
97pub struct OAuth2Config {
98    /// Authorization server issuer identifier
99    pub issuer: String,
100    /// Authorization code lifetime
101    pub authorization_code_lifetime: Duration,
102    /// Access token lifetime
103    pub access_token_lifetime: Duration,
104    /// Refresh token lifetime
105    pub refresh_token_lifetime: Duration,
106    /// Device code lifetime
107    pub device_code_lifetime: Duration,
108    /// Default scope if none specified
109    pub default_scope: Option<String>,
110    /// Maximum scope lifetime
111    pub max_scope_lifetime: Duration,
112    /// Require PKCE for public clients
113    pub require_pkce: bool,
114    /// Enable token introspection
115    pub enable_introspection: bool,
116    /// Enable token revocation
117    pub enable_revocation: bool,
118}
119
120impl Default for OAuth2Config {
121    fn default() -> Self {
122        Self {
123            issuer: "https://auth.example.com".to_string(),
124            authorization_code_lifetime: Duration::from_secs(600), // 10 minutes
125            access_token_lifetime: Duration::from_secs(3600),      // 1 hour
126            refresh_token_lifetime: Duration::from_secs(86400 * 7), // 7 days
127            device_code_lifetime: Duration::from_secs(600),        // 10 minutes
128            default_scope: Some("read".to_string()),
129            max_scope_lifetime: Duration::from_secs(86400 * 30), // 30 days
130            require_pkce: true,
131            enable_introspection: true,
132            enable_revocation: true,
133        }
134    }
135}
136
137impl OAuth2Config {
138    /// Create a new builder for `OAuth2Config`, starting from defaults.
139    ///
140    /// # Example
141    ///
142    /// ```rust,no_run
143    /// use auth_framework::oauth2_server::OAuth2Config;
144    /// use std::time::Duration;
145    ///
146    /// let config = OAuth2Config::builder()
147    ///     .issuer("https://id.example.com")
148    ///     .access_token_lifetime(Duration::from_secs(1800))
149    ///     .require_pkce(true)
150    ///     .build();
151    /// ```
152    pub fn builder() -> OAuth2ConfigBuilder {
153        OAuth2ConfigBuilder::default()
154    }
155}
156
157/// A builder for [`OAuth2Config`].
158///
159/// Obtain via [`OAuth2Config::builder()`]. All fields start with secure
160/// defaults; override only what you need.
161#[derive(Debug, Clone, Default)]
162pub struct OAuth2ConfigBuilder {
163    config: OAuth2Config,
164}
165
166impl OAuth2ConfigBuilder {
167    /// Set the authorization server issuer identifier.
168    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
169        self.config.issuer = issuer.into();
170        self
171    }
172
173    /// Set the authorization code lifetime.
174    pub fn authorization_code_lifetime(mut self, lifetime: Duration) -> Self {
175        self.config.authorization_code_lifetime = lifetime;
176        self
177    }
178
179    /// Set the access token lifetime.
180    pub fn access_token_lifetime(mut self, lifetime: Duration) -> Self {
181        self.config.access_token_lifetime = lifetime;
182        self
183    }
184
185    /// Set the refresh token lifetime.
186    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
187        self.config.refresh_token_lifetime = lifetime;
188        self
189    }
190
191    /// Set the device code lifetime.
192    pub fn device_code_lifetime(mut self, lifetime: Duration) -> Self {
193        self.config.device_code_lifetime = lifetime;
194        self
195    }
196
197    /// Set the default scope granted when none is specified.
198    pub fn default_scope(mut self, scope: impl Into<String>) -> Self {
199        self.config.default_scope = Some(scope.into());
200        self
201    }
202
203    /// Set the maximum scope lifetime.
204    pub fn max_scope_lifetime(mut self, lifetime: Duration) -> Self {
205        self.config.max_scope_lifetime = lifetime;
206        self
207    }
208
209    /// Set whether PKCE is required for public clients.
210    pub fn require_pkce(mut self, require: bool) -> Self {
211        self.config.require_pkce = require;
212        self
213    }
214
215    /// Enable or disable token introspection (RFC 7662).
216    pub fn enable_introspection(mut self, enable: bool) -> Self {
217        self.config.enable_introspection = enable;
218        self
219    }
220
221    /// Enable or disable token revocation (RFC 7009).
222    pub fn enable_revocation(mut self, enable: bool) -> Self {
223        self.config.enable_revocation = enable;
224        self
225    }
226
227    /// Build the [`OAuth2Config`].
228    pub fn build(self) -> OAuth2Config {
229        self.config
230    }
231}
232
233/// Token request structure
234///
235/// Use the convenience constructors for common grant types instead of filling
236/// every field manually:
237///
238/// ```rust,no_run
239/// use auth_framework::server::oauth::oauth2_server::TokenRequest;
240///
241/// // Authorization code exchange
242/// let req = TokenRequest::authorization_code("my_code")
243///     .client_id("client123")
244///     .client_secret("secret")
245///     .redirect_uri("https://app.example.com/cb")
246///     .code_verifier("pkce_verifier");
247///
248/// // Refresh token grant
249/// let req = TokenRequest::refresh("my_refresh_token");
250///
251/// // Client credentials grant
252/// let req = TokenRequest::client_credentials("client123", "secret");
253/// ```
254#[derive(Debug, Clone, Serialize, Deserialize, Default)]
255pub struct TokenRequest {
256    pub grant_type: String,
257    /// Client identifier. Optional here because HTTP clients may use HTTP Basic auth
258    /// (`Authorization: Basic …`) instead of embedding it in the request body.
259    #[serde(default)]
260    pub client_id: Option<String>,
261    pub client_secret: Option<String>,
262    pub code: Option<String>,
263    pub redirect_uri: Option<String>,
264    pub refresh_token: Option<String>,
265    pub scope: Option<String>,
266    pub code_verifier: Option<String>,
267    pub username: Option<String>,
268    pub password: Option<String>,
269    pub device_code: Option<String>,
270    /// RFC 8707 Resource Indicators — target resource URI(s).
271    #[serde(default)]
272    pub resource: Option<Vec<String>>,
273}
274
275impl TokenRequest {
276    /// Create a token request for the **authorization_code** grant.
277    pub fn authorization_code(code: impl Into<String>) -> Self {
278        Self {
279            grant_type: "authorization_code".to_string(),
280            code: Some(code.into()),
281            ..Default::default()
282        }
283    }
284
285    /// Create a token request for the **refresh_token** grant.
286    pub fn refresh(token: impl Into<String>) -> Self {
287        Self {
288            grant_type: "refresh_token".to_string(),
289            refresh_token: Some(token.into()),
290            ..Default::default()
291        }
292    }
293
294    /// Create a token request for the **client_credentials** grant.
295    pub fn client_credentials(
296        client_id: impl Into<String>,
297        client_secret: impl Into<String>,
298    ) -> Self {
299        Self {
300            grant_type: "client_credentials".to_string(),
301            client_id: Some(client_id.into()),
302            client_secret: Some(client_secret.into()),
303            ..Default::default()
304        }
305    }
306
307    /// Set the client ID.
308    pub fn client_id(mut self, id: impl Into<String>) -> Self {
309        self.client_id = Some(id.into());
310        self
311    }
312
313    /// Set the client secret.
314    pub fn client_secret(mut self, secret: impl Into<String>) -> Self {
315        self.client_secret = Some(secret.into());
316        self
317    }
318
319    /// Set the redirect URI.
320    pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
321        self.redirect_uri = Some(uri.into());
322        self
323    }
324
325    /// Set the PKCE code verifier.
326    pub fn code_verifier(mut self, verifier: impl Into<String>) -> Self {
327        self.code_verifier = Some(verifier.into());
328        self
329    }
330
331    /// Set the requested scope.
332    pub fn scope(mut self, scope: impl Into<String>) -> Self {
333        self.scope = Some(scope.into());
334        self
335    }
336
337    /// Set RFC 8707 resource indicators.
338    pub fn resource(mut self, uris: Vec<String>) -> Self {
339        self.resource = Some(uris);
340        self
341    }
342}
343
344/// Token response structure
345#[derive(Debug, Clone, Serialize, Deserialize)]
346pub struct TokenResponse {
347    pub access_token: String,
348    pub token_type: String,
349    pub expires_in: u64,
350    pub refresh_token: Option<String>,
351    pub scope: Option<String>,
352    pub id_token: Option<String>,
353}
354
355/// Authorization request structure
356///
357/// Use [`AuthorizationRequest::new`] for a concise starting point:
358///
359/// ```rust,no_run
360/// use auth_framework::server::oauth::oauth2_server::AuthorizationRequest;
361///
362/// let req = AuthorizationRequest::new("client123", "code", "https://app.example.com/cb")
363///     .scope("openid profile")
364///     .state("random_state")
365///     .pkce("challenge", "S256");
366/// ```
367#[derive(Debug, Clone, Serialize, Deserialize)]
368pub struct AuthorizationRequest {
369    pub client_id: String,
370    pub response_type: String,
371    pub redirect_uri: String,
372    pub scope: Option<String>,
373    pub state: Option<String>,
374    pub code_challenge: Option<String>,
375    pub code_challenge_method: Option<String>,
376    pub nonce: Option<String>,
377    /// RFC 8707 Resource Indicators — target resource URI(s).
378    #[serde(default)]
379    pub resource: Option<Vec<String>>,
380}
381
382impl AuthorizationRequest {
383    /// Create a new authorization request with the required fields.
384    pub fn new(
385        client_id: impl Into<String>,
386        response_type: impl Into<String>,
387        redirect_uri: impl Into<String>,
388    ) -> Self {
389        Self {
390            client_id: client_id.into(),
391            response_type: response_type.into(),
392            redirect_uri: redirect_uri.into(),
393            scope: None,
394            state: None,
395            code_challenge: None,
396            code_challenge_method: None,
397            nonce: None,
398            resource: None,
399        }
400    }
401
402    /// Set the requested scope.
403    pub fn scope(mut self, scope: impl Into<String>) -> Self {
404        self.scope = Some(scope.into());
405        self
406    }
407
408    /// Set the OAuth state parameter.
409    pub fn state(mut self, state: impl Into<String>) -> Self {
410        self.state = Some(state.into());
411        self
412    }
413
414    /// Set the PKCE code challenge and method.
415    pub fn pkce(mut self, challenge: impl Into<String>, method: impl Into<String>) -> Self {
416        self.code_challenge = Some(challenge.into());
417        self.code_challenge_method = Some(method.into());
418        self
419    }
420
421    /// Set the nonce.
422    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
423        self.nonce = Some(nonce.into());
424        self
425    }
426
427    /// Set RFC 8707 resource indicators.
428    pub fn resource(mut self, uris: Vec<String>) -> Self {
429        self.resource = Some(uris);
430        self
431    }
432}
433
434/// OAuth 2.0 Authorization Server
435pub struct OAuth2Server {
436    config: OAuth2Config,
437    token_storage: Arc<RwLock<EnhancedTokenStorage>>,
438    session_store: Arc<RwLock<SessionStore>>,
439    token_manager: Arc<TokenManager>,
440}
441
442impl OAuth2Server {
443    pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
444        Ok(Self {
445            config,
446            token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
447            session_store: Arc::new(RwLock::new(SessionStore::new())),
448            token_manager,
449        })
450    }
451
452    /// Register a confidential client with proper secret validation
453    pub async fn register_confidential_client(
454        &self,
455        client_id: String,
456        client_secret: &str,
457        redirect_uris: Vec<String>,
458        allowed_scopes: Vec<String>,
459        grant_types: Vec<String>,
460    ) -> Result<()> {
461        // Validate client secret strength
462        if client_secret.len() < 32 {
463            return Err(AuthError::auth_method(
464                "oauth2",
465                "Client secret must be at least 32 characters",
466            ));
467        }
468
469        let credentials = EnhancedClientCredentials::new_confidential(
470            client_id,
471            client_secret,
472            redirect_uris,
473            allowed_scopes,
474            grant_types,
475        )?;
476
477        let mut storage = self.token_storage.write().await;
478        storage.store_client_credentials(credentials).await?;
479
480        Ok(())
481    }
482
483    /// Register a public client (PKCE required)
484    pub async fn register_public_client(
485        &self,
486        client_id: String,
487        redirect_uris: Vec<String>,
488        allowed_scopes: Vec<String>,
489        grant_types: Vec<String>,
490    ) -> Result<()> {
491        let credentials = EnhancedClientCredentials::new_public(
492            client_id,
493            redirect_uris,
494            allowed_scopes,
495            grant_types,
496        );
497
498        let mut storage = self.token_storage.write().await;
499        storage.store_client_credentials(credentials).await?;
500
501        Ok(())
502    }
503
504    /// Create authorization code with proper user context
505    pub async fn create_authorization_code(
506        &self,
507        request: AuthorizationRequest,
508        user_context: UserContext,
509    ) -> Result<EnhancedAuthorizationCode> {
510        // Validate client exists and supports authorization code flow
511        let storage = self.token_storage.read().await;
512        let client = storage
513            .get_client_credentials(&request.client_id)
514            .await?
515            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
516
517        if !client.supports_grant_type("authorization_code") {
518            return Err(AuthError::auth_method(
519                "oauth2",
520                "Client does not support authorization code grant",
521            ));
522        }
523
524        if !client.redirect_uris.contains(&request.redirect_uri) {
525            return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
526        }
527
528        // Parse and validate scopes
529        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
530        let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
531
532        // Create authorization code with proper user context
533        let auth_code = EnhancedAuthorizationCode::new(
534            client.client_id.clone(),
535            user_context.user_id.clone(), // FIXED: Use real user ID from context
536            request.redirect_uri,
537            authorized_scopes,
538            request.code_challenge,
539            request.code_challenge_method,
540            self.config.authorization_code_lifetime,
541        );
542
543        // Store authorization code
544        drop(storage);
545        let mut storage = self.token_storage.write().await;
546        storage.store_authorization_code(auth_code.clone()).await?;
547
548        Ok(auth_code)
549    }
550
551    /// Handle token exchange with comprehensive validation
552    pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
553        match request.grant_type.as_str() {
554            "authorization_code" => self.handle_authorization_code_grant(request).await,
555            "refresh_token" => self.handle_refresh_token_grant(request).await,
556            "client_credentials" => self.handle_client_credentials_grant(request).await,
557            _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
558        }
559    }
560
561    /// Handle authorization code grant with proper validation
562    async fn handle_authorization_code_grant(
563        &self,
564        request: TokenRequest,
565    ) -> Result<TokenResponse> {
566        let client_id = request
567            .client_id
568            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
569        // Validate client credentials FIRST
570        let storage = self.token_storage.read().await;
571        let _client = storage
572            .get_client_credentials(&client_id)
573            .await?
574            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
575
576        // CRITICAL FIX: Validate client secret properly
577        if !storage
578            .validate_client_credentials(&client_id, request.client_secret.as_deref())
579            .await?
580        {
581            return Err(AuthError::auth_method(
582                "oauth2",
583                "Invalid client credentials",
584            ));
585        }
586
587        // Get and validate authorization code
588        let code = request
589            .code
590            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;
591
592        drop(storage);
593        let mut storage = self.token_storage.write().await;
594        let auth_code = storage
595            .consume_authorization_code(&code)
596            .await?
597            .ok_or_else(|| {
598                AuthError::auth_method("oauth2", "Invalid or expired authorization code")
599            })?;
600
601        // Validate code belongs to this client
602        if auth_code.client_id != client_id {
603            return Err(AuthError::auth_method(
604                "oauth2",
605                "Authorization code does not belong to client",
606            ));
607        }
608
609        // Validate PKCE if required
610        if let Some(challenge) = &auth_code.code_challenge {
611            let verifier = request
612                .code_verifier
613                .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;
614
615            if !self.validate_pkce_challenge(
616                challenge,
617                &verifier,
618                &auth_code.code_challenge_method,
619            )? {
620                return Err(AuthError::auth_method(
621                    "oauth2",
622                    "Invalid PKCE code verifier",
623                ));
624            }
625        }
626
627        // Generate tokens with proper user context
628        let access_token = self
629            .generate_access_token(
630                &auth_code.client_id,
631                Some(&auth_code.user_id), // FIXED: Use actual user ID from auth code
632                &auth_code.scopes,
633            )
634            .await?;
635
636        // Generate refresh token
637        let refresh_token = RefreshToken::new(
638            auth_code.client_id.clone(),
639            auth_code.user_id.clone(), // FIXED: Use actual user ID
640            auth_code.scopes.clone(),  // FIXED: Use authorized scopes from auth code
641            self.config.refresh_token_lifetime,
642        );
643
644        let refresh_token_id = storage.store_refresh_token(refresh_token).await?;
645
646        Ok(TokenResponse {
647            access_token: access_token.access_token,
648            token_type: "Bearer".to_string(),
649            expires_in: self.config.access_token_lifetime.as_secs(),
650            refresh_token: Some(refresh_token_id),
651            scope: Some(auth_code.scopes.join(" ")),
652            id_token: None,
653        })
654    }
655
656    /// Handle refresh token grant with proper validation
657    async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
658        let client_id = request
659            .client_id
660            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
661        // Validate client credentials
662        let storage = self.token_storage.read().await;
663        if !storage
664            .validate_client_credentials(&client_id, request.client_secret.as_deref())
665            .await?
666        {
667            return Err(AuthError::auth_method(
668                "oauth2",
669                "Invalid client credentials",
670            ));
671        }
672
673        // Get and validate refresh token
674        let refresh_token_id = request
675            .refresh_token
676            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
677
678        // CRITICAL FIX: Validate refresh token from storage
679        let stored_token = storage
680            .get_refresh_token(&refresh_token_id)
681            .await?
682            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
683
684        if !stored_token.is_valid() {
685            return Err(AuthError::auth_method(
686                "oauth2",
687                "Refresh token is expired or revoked",
688            ));
689        }
690
691        // Validate token belongs to this client
692        if stored_token.client_id != client_id {
693            return Err(AuthError::auth_method(
694                "oauth2",
695                "Refresh token does not belong to client",
696            ));
697        }
698
699        // Parse requested scopes (must be subset of original)
700        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
701        let authorized_scopes = if requested_scopes.is_empty() {
702            stored_token.scopes.clone() // FIXED: Use original scopes from token
703        } else {
704            self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
705        };
706
707        drop(storage);
708
709        // Generate new access token
710        let access_token = self
711            .generate_access_token(
712                &stored_token.client_id,
713                Some(&stored_token.user_id), // FIXED: Use actual user ID from token
714                &authorized_scopes,
715            )
716            .await?;
717
718        // Generate new refresh token
719        let mut storage = self.token_storage.write().await;
720        storage.revoke_refresh_token(&refresh_token_id).await?; // Revoke old token
721
722        let new_refresh_token = RefreshToken::new(
723            stored_token.client_id.clone(),
724            stored_token.user_id.clone(),
725            authorized_scopes.clone(),
726            self.config.refresh_token_lifetime,
727        );
728
729        let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
730
731        Ok(TokenResponse {
732            access_token: access_token.access_token,
733            token_type: "Bearer".to_string(),
734            expires_in: self.config.access_token_lifetime.as_secs(),
735            refresh_token: Some(new_refresh_token_id),
736            scope: Some(authorized_scopes.join(" ")),
737            id_token: None,
738        })
739    }
740
741    /// Handle client credentials grant with proper validation
742    async fn handle_client_credentials_grant(
743        &self,
744        request: TokenRequest,
745    ) -> Result<TokenResponse> {
746        let client_id = request
747            .client_id
748            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
749        // Validate client credentials
750        let storage = self.token_storage.read().await;
751        let client = storage
752            .get_client_credentials(&client_id)
753            .await?
754            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
755
756        // CRITICAL FIX: Validate client secret properly
757        if !storage
758            .validate_client_credentials(&client_id, request.client_secret.as_deref())
759            .await?
760        {
761            return Err(AuthError::auth_method(
762                "oauth2",
763                "Invalid client credentials",
764            ));
765        }
766
767        if !client.supports_grant_type("client_credentials") {
768            return Err(AuthError::auth_method(
769                "oauth2",
770                "Client does not support client credentials grant",
771            ));
772        }
773
774        // Parse and validate scopes
775        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
776        let authorized_scopes = requested_scopes
777            .iter()
778            .filter(|scope| client.has_scope(scope))
779            .cloned()
780            .collect::<Vec<_>>();
781
782        if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
783            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
784        }
785
786        drop(storage);
787
788        // Generate access token (no user context for client credentials)
789        let access_token = self
790            .generate_access_token(&client_id, None, &authorized_scopes)
791            .await?;
792
793        Ok(TokenResponse {
794            access_token: access_token.access_token,
795            token_type: "Bearer".to_string(),
796            expires_in: self.config.access_token_lifetime.as_secs(),
797            refresh_token: None, // No refresh token for client credentials
798            scope: Some(authorized_scopes.join(" ")),
799            id_token: None,
800        })
801    }
802
803    /// Generate access token with proper validation
804    async fn generate_access_token(
805        &self,
806        client_id: &str,
807        user_id: Option<&str>,
808        scopes: &[String],
809    ) -> Result<AuthToken> {
810        let subject = user_id.unwrap_or(client_id);
811        let mut token = self.token_manager.create_auth_token(
812            subject,
813            crate::types::Scopes::from(
814                scopes
815                    .iter()
816                    .map(|s| s.to_string())
817                    .collect::<Vec<String>>(),
818            ),
819            "oauth2",
820            Some(self.config.access_token_lifetime),
821        )?;
822
823        // Add client_id claim
824        token.add_custom_claim(
825            "client_id".to_string(),
826            serde_json::Value::String(client_id.to_string()),
827        );
828
829        // Add user_id claim if present
830        if let Some(uid) = user_id {
831            token.add_custom_claim(
832                "user_id".to_string(),
833                serde_json::Value::String(uid.to_string()),
834            );
835        }
836
837        Ok(token)
838    }
839
840    /// Parse scopes from scope string
841    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
842        match scope_str {
843            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
844            None => match &self.config.default_scope {
845                Some(default) => Ok(vec![default.clone()]),
846                None => Ok(vec![]),
847            },
848        }
849    }
850
851    /// Authorize scopes based on client and user permissions
852    fn authorize_scopes(
853        &self,
854        client: &EnhancedClientCredentials,
855        user_context: &UserContext,
856        requested_scopes: &[String],
857    ) -> Result<Vec<String>> {
858        let mut authorized = Vec::new();
859
860        for scope in requested_scopes {
861            // Check if client is allowed this scope
862            if client.has_scope(scope) {
863                // Check if user has this scope (if applicable)
864                if user_context.has_scope(scope) {
865                    authorized.push(scope.clone());
866                }
867            }
868        }
869
870        if authorized.is_empty() && !requested_scopes.is_empty() {
871            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
872        }
873
874        Ok(authorized)
875    }
876
877    /// Validate that requested scopes are subset of original scopes
878    fn validate_scope_subset(
879        &self,
880        original_scopes: &[String],
881        requested_scopes: &[String],
882    ) -> Result<Vec<String>> {
883        let mut validated = Vec::new();
884
885        for scope in requested_scopes {
886            if original_scopes.contains(scope) {
887                validated.push(scope.clone());
888            } else {
889                return Err(AuthError::auth_method(
890                    "oauth2",
891                    format!("Requested scope '{}' not in original grant", scope),
892                ));
893            }
894        }
895
896        Ok(validated)
897    }
898
899    /// Validate PKCE code challenge
900    fn validate_pkce_challenge(
901        &self,
902        challenge: &str,
903        verifier: &str,
904        method: &Option<String>,
905    ) -> Result<bool> {
906        let method = method.as_deref().unwrap_or("plain");
907
908        match method {
909            "plain" => Ok(constant_time_compare(
910                challenge.as_bytes(),
911                verifier.as_bytes(),
912            )),
913            "S256" => {
914                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
915                use sha2::{Digest, Sha256};
916
917                let hash = Sha256::digest(verifier.as_bytes());
918                let encoded = URL_SAFE_NO_PAD.encode(hash);
919                Ok(constant_time_compare(
920                    challenge.as_bytes(),
921                    encoded.as_bytes(),
922                ))
923            }
924            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
925        }
926    }
927
928    /// Revoke token (refresh token or access token)
929    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
930        let mut storage = self.token_storage.write().await;
931
932        // Validate client is authorized to revoke this token
933        if client_id.is_empty() {
934            return Err(AuthError::auth_method(
935                "oauth2",
936                "Client ID is required for token revocation",
937            ));
938        }
939
940        // Verify client exists by trying to get its credentials
941        if storage.get_client_credentials(client_id).await.is_err() {
942            return Err(AuthError::auth_method("oauth2", "Invalid client"));
943        }
944
945        // Try to revoke as refresh token first
946        if storage.validate_refresh_token(token).await? {
947            return storage.revoke_refresh_token(token).await;
948        }
949
950        // For access tokens, we would need to maintain a revocation list
951        // This is a simplified implementation
952        Ok(false)
953    }
954
955    /// Clean up expired tokens
956    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
957        let mut storage = self.token_storage.write().await;
958        storage.cleanup_expired_tokens().await
959    }
960
961    /// Add user credentials to the server's token storage.
962    ///
963    /// Use this to register users before calling `authenticate_user`.
964    /// In production this is typically called during server setup or via an
965    /// administrative API; in tests it provides a way to seed known users
966    /// without hardcoding them in the library itself.
967    pub async fn add_user_credentials(
968        &self,
969        creds: crate::server::oauth::oauth2_enhanced_storage::UserCredentials,
970    ) -> Result<()> {
971        let mut storage = self.token_storage.write().await;
972        storage.store_user_credentials(creds).await
973    }
974
975    /// Authenticate user and create session
976    pub async fn authenticate_user(
977        &self,
978        username: &str,
979        password: &str,
980        scopes: Vec<String>,
981    ) -> Result<UserContext> {
982        // CRITICAL SECURITY FIX: Validate credentials against storage
983        let storage = self.token_storage.read().await;
984
985        // Validate username exists and password is correct using storage
986        if !self
987            .validate_user_credentials_against_storage(&storage, username, password)
988            .await?
989        {
990            return Err(AuthError::auth_method(
991                "oauth2",
992                "Invalid username or password",
993            ));
994        }
995
996        // Validate user is authorized for requested scopes
997        let authorized_scopes = self
998            .validate_user_scopes_against_storage(&storage, username, &scopes)
999            .await?;
1000
1001        drop(storage);
1002
1003        // Create user context with validated information
1004        let user_context = UserContext::new(
1005            self.generate_user_id(username).await?,
1006            username.to_string(),
1007            self.get_user_email(username).await?,
1008        )
1009        .with_scopes(authorized_scopes);
1010
1011        let mut session_store = self.session_store.write().await;
1012        session_store.create_session(user_context.clone());
1013
1014        Ok(user_context)
1015    }
1016
1017    /// Validate user credentials against secure storage
1018    async fn validate_user_credentials_against_storage(
1019        &self,
1020        storage: &EnhancedTokenStorage,
1021        username: &str,
1022        password: &str,
1023    ) -> Result<bool> {
1024        // Minimum security requirements - but don't return early to prevent timing attacks
1025        let is_empty = username.is_empty() || password.is_empty();
1026        let is_too_short = password.len() < 8;
1027
1028        // Always perform the expensive bcrypt operation to prevent timing attacks
1029        match storage.get_user_credentials(username).await {
1030            Ok(Some(stored_credentials)) => {
1031                // Use bcrypt to verify password against hash
1032                use bcrypt::verify;
1033                match verify(password, &stored_credentials.password_hash) {
1034                    Ok(is_valid) => {
1035                        // Only return true if all conditions are met
1036                        Ok(is_valid && !is_empty && !is_too_short)
1037                    }
1038                    Err(_) => {
1039                        // Hash verification failed - fail securely
1040                        Ok(false)
1041                    }
1042                }
1043            }
1044            Ok(None) => {
1045                // User not found - still do dummy bcrypt operation to prevent timing attacks
1046                use bcrypt::verify;
1047                let _dummy_result = verify(
1048                    password,
1049                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1050                );
1051                Ok(false)
1052            }
1053            Err(_) => {
1054                // Storage error - still do dummy bcrypt operation to prevent timing attacks
1055                use bcrypt::verify;
1056                let _dummy_result = verify(
1057                    password,
1058                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1059                );
1060                Ok(false)
1061            }
1062        }
1063    }
1064
1065    /// Validate user is authorized for requested scopes using storage
1066    async fn validate_user_scopes_against_storage(
1067        &self,
1068        storage: &EnhancedTokenStorage,
1069        username: &str,
1070        requested_scopes: &[String],
1071    ) -> Result<Vec<String>> {
1072        // Get user permissions from storage
1073        let user_permissions = match storage.get_user_permissions(username).await {
1074            Ok(Some(permissions)) => permissions.scopes,
1075            Ok(None) => {
1076                return Err(AuthError::auth_method(
1077                    "oauth2",
1078                    "User not found in permission store",
1079                ));
1080            }
1081            Err(_) => {
1082                return Err(AuthError::auth_method(
1083                    "oauth2",
1084                    "Failed to retrieve user permissions",
1085                ));
1086            }
1087        };
1088
1089        let mut authorized = Vec::new();
1090        for scope in requested_scopes {
1091            if user_permissions.contains(scope) {
1092                authorized.push(scope.clone());
1093            }
1094        }
1095
1096        // If no scopes requested, give default read scope for valid users
1097        if authorized.is_empty() && !requested_scopes.is_empty() {
1098            return Err(AuthError::auth_method(
1099                "oauth2",
1100                "User not authorized for requested scopes",
1101            ));
1102        }
1103
1104        if authorized.is_empty() {
1105            // Check if user has at least read permission for default scope
1106            if user_permissions.contains(&"read".to_string()) {
1107                authorized.push("read".to_string());
1108            } else {
1109                return Err(AuthError::auth_method(
1110                    "oauth2",
1111                    "User has no authorized scopes",
1112                ));
1113            }
1114        }
1115
1116        Ok(authorized)
1117    }
1118
1119    /// Generate consistent user ID
1120    async fn generate_user_id(&self, username: &str) -> Result<String> {
1121        // In production, this would be the user's UUID from the database
1122        // For now, create a deterministic but unique ID
1123        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
1124        let hash_str = format!("{:x}", hash);
1125        Ok(format!("user_{}", &hash_str[0..16]))
1126    }
1127
1128    /// Get user email from user store
1129    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
1130        let storage = self.token_storage.read().await;
1131        match storage.get_user_credentials(username).await {
1132            Ok(Some(creds)) => Ok(creds.email),
1133            // User not found or storage error — return None rather than a fabricated address.
1134            _ => Ok(None),
1135        }
1136    }
1137
1138    /// Get user context from session
1139    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
1140        let session_store = self.session_store.read().await;
1141        Ok(session_store.get_session(session_id).cloned())
1142    }
1143
1144    /// Invalidate user session
1145    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
1146        let mut session_store = self.session_store.write().await;
1147        Ok(session_store.invalidate_session(session_id))
1148    }
1149}