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(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 std::fmt::Debug for TokenRequest {
276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
277        let mut d = f.debug_struct("TokenRequest");
278        d.field("grant_type", &self.grant_type);
279        d.field("client_id", &self.client_id);
280        d.field(
281            "client_secret",
282            &crate::utils::redact::redacted(&self.client_secret),
283        );
284        d.field("code", &crate::utils::redact::redacted(&self.code));
285        d.field("redirect_uri", &self.redirect_uri);
286        d.field(
287            "refresh_token",
288            &crate::utils::redact::redacted(&self.refresh_token),
289        );
290        d.field("scope", &self.scope);
291        d.field(
292            "code_verifier",
293            &crate::utils::redact::redacted(&self.code_verifier),
294        );
295        d.field("username", &self.username);
296        d.field("password", &crate::utils::redact::redacted(&self.password));
297        d.field(
298            "device_code",
299            &crate::utils::redact::redacted(&self.device_code),
300        );
301        d.field("resource", &self.resource);
302        d.finish()
303    }
304}
305
306impl TokenRequest {
307    /// Create a token request for the **authorization_code** grant.
308    pub fn authorization_code(code: impl Into<String>) -> Self {
309        Self {
310            grant_type: "authorization_code".to_string(),
311            code: Some(code.into()),
312            ..Default::default()
313        }
314    }
315
316    /// Create a token request for the **refresh_token** grant.
317    pub fn refresh(token: impl Into<String>) -> Self {
318        Self {
319            grant_type: "refresh_token".to_string(),
320            refresh_token: Some(token.into()),
321            ..Default::default()
322        }
323    }
324
325    /// Create a token request for the **client_credentials** grant.
326    pub fn client_credentials(
327        client_id: impl Into<String>,
328        client_secret: impl Into<String>,
329    ) -> Self {
330        Self {
331            grant_type: "client_credentials".to_string(),
332            client_id: Some(client_id.into()),
333            client_secret: Some(client_secret.into()),
334            ..Default::default()
335        }
336    }
337
338    /// Set the client ID.
339    pub fn client_id(mut self, id: impl Into<String>) -> Self {
340        self.client_id = Some(id.into());
341        self
342    }
343
344    /// Set the client secret.
345    pub fn client_secret(mut self, secret: impl Into<String>) -> Self {
346        self.client_secret = Some(secret.into());
347        self
348    }
349
350    /// Set the redirect URI.
351    pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
352        self.redirect_uri = Some(uri.into());
353        self
354    }
355
356    /// Set the PKCE code verifier.
357    pub fn code_verifier(mut self, verifier: impl Into<String>) -> Self {
358        self.code_verifier = Some(verifier.into());
359        self
360    }
361
362    /// Set the requested scope.
363    pub fn scope(mut self, scope: impl Into<String>) -> Self {
364        self.scope = Some(scope.into());
365        self
366    }
367
368    /// Set RFC 8707 resource indicators.
369    pub fn resource(mut self, uris: Vec<String>) -> Self {
370        self.resource = Some(uris);
371        self
372    }
373}
374
375/// Token response structure
376#[derive(Clone, Serialize, Deserialize)]
377pub struct TokenResponse {
378    pub access_token: String,
379    pub token_type: String,
380    pub expires_in: u64,
381    pub refresh_token: Option<String>,
382    pub scope: Option<String>,
383    pub id_token: Option<String>,
384}
385
386impl std::fmt::Debug for TokenResponse {
387    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
388        let mut d = f.debug_struct("TokenResponse");
389        d.field(
390            "access_token",
391            &crate::utils::redact::redacted(&self.access_token),
392        );
393        d.field("token_type", &self.token_type);
394        d.field("expires_in", &self.expires_in);
395        d.field(
396            "refresh_token",
397            &crate::utils::redact::redacted(&self.refresh_token),
398        );
399        d.field("scope", &self.scope);
400        d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
401        d.finish()
402    }
403}
404
405/// Authorization request structure
406///
407/// Use [`AuthorizationRequest::new`] for a concise starting point:
408///
409/// ```rust,no_run
410/// use auth_framework::server::oauth::oauth2_server::AuthorizationRequest;
411///
412/// let req = AuthorizationRequest::new("client123", "code", "https://app.example.com/cb")
413///     .scope("openid profile")
414///     .state("random_state")
415///     .pkce("challenge", "S256");
416/// ```
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct AuthorizationRequest {
419    pub client_id: String,
420    pub response_type: String,
421    pub redirect_uri: String,
422    pub scope: Option<String>,
423    pub state: Option<String>,
424    pub code_challenge: Option<String>,
425    pub code_challenge_method: Option<String>,
426    pub nonce: Option<String>,
427    /// RFC 8707 Resource Indicators — target resource URI(s).
428    #[serde(default)]
429    pub resource: Option<Vec<String>>,
430}
431
432impl AuthorizationRequest {
433    /// Create a new authorization request with the required fields.
434    pub fn new(
435        client_id: impl Into<String>,
436        response_type: impl Into<String>,
437        redirect_uri: impl Into<String>,
438    ) -> Self {
439        Self {
440            client_id: client_id.into(),
441            response_type: response_type.into(),
442            redirect_uri: redirect_uri.into(),
443            scope: None,
444            state: None,
445            code_challenge: None,
446            code_challenge_method: None,
447            nonce: None,
448            resource: None,
449        }
450    }
451
452    /// Set the requested scope.
453    pub fn scope(mut self, scope: impl Into<String>) -> Self {
454        self.scope = Some(scope.into());
455        self
456    }
457
458    /// Set the OAuth state parameter.
459    pub fn state(mut self, state: impl Into<String>) -> Self {
460        self.state = Some(state.into());
461        self
462    }
463
464    /// Set the PKCE code challenge and method.
465    pub fn pkce(mut self, challenge: impl Into<String>, method: impl Into<String>) -> Self {
466        self.code_challenge = Some(challenge.into());
467        self.code_challenge_method = Some(method.into());
468        self
469    }
470
471    /// Set the nonce.
472    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
473        self.nonce = Some(nonce.into());
474        self
475    }
476
477    /// Set RFC 8707 resource indicators.
478    pub fn resource(mut self, uris: Vec<String>) -> Self {
479        self.resource = Some(uris);
480        self
481    }
482}
483
484/// OAuth 2.0 Authorization Server
485pub struct OAuth2Server {
486    config: OAuth2Config,
487    token_storage: Arc<RwLock<EnhancedTokenStorage>>,
488    session_store: Arc<RwLock<SessionStore>>,
489    token_manager: Arc<TokenManager>,
490    audit: Option<Arc<dyn crate::audit::AuditStorage>>,
491}
492
493impl OAuth2Server {
494    pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
495        Ok(Self {
496            config,
497            token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
498            session_store: Arc::new(RwLock::new(SessionStore::new())),
499            token_manager,
500            audit: None,
501        })
502    }
503
504    /// Record `client_credentials` grants (issued or refused) in `storage`. Without it the grant
505    /// leaves no audit record. The record names the client and the scopes asked for and granted,
506    /// and never a secret or a token.
507    pub fn with_audit_storage(mut self, storage: Arc<dyn crate::audit::AuditStorage>) -> Self {
508        self.audit = Some(storage);
509        self
510    }
511
512    /// Register a confidential client with proper secret validation
513    pub async fn register_confidential_client(
514        &self,
515        client_id: String,
516        client_secret: &str,
517        redirect_uris: Vec<String>,
518        allowed_scopes: Vec<String>,
519        grant_types: Vec<String>,
520    ) -> Result<()> {
521        // Validate client secret strength
522        if client_secret.len() < 32 {
523            return Err(AuthError::auth_method(
524                "oauth2",
525                "Client secret must be at least 32 characters",
526            ));
527        }
528
529        let credentials = EnhancedClientCredentials::new_confidential(
530            client_id,
531            client_secret,
532            redirect_uris,
533            allowed_scopes,
534            grant_types,
535        )?;
536
537        let mut storage = self.token_storage.write().await;
538        storage.store_client_credentials(credentials).await?;
539
540        Ok(())
541    }
542
543    /// Register a public client (PKCE required)
544    pub async fn register_public_client(
545        &self,
546        client_id: String,
547        redirect_uris: Vec<String>,
548        allowed_scopes: Vec<String>,
549        grant_types: Vec<String>,
550    ) -> Result<()> {
551        let credentials = EnhancedClientCredentials::new_public(
552            client_id,
553            redirect_uris,
554            allowed_scopes,
555            grant_types,
556        );
557
558        let mut storage = self.token_storage.write().await;
559        storage.store_client_credentials(credentials).await?;
560
561        Ok(())
562    }
563
564    /// Create authorization code with proper user context
565    pub async fn create_authorization_code(
566        &self,
567        request: AuthorizationRequest,
568        user_context: UserContext,
569    ) -> Result<EnhancedAuthorizationCode> {
570        // Validate client exists and supports authorization code flow
571        let storage = self.token_storage.read().await;
572        let client = storage
573            .get_client_credentials(&request.client_id)
574            .await?
575            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
576
577        if !client.supports_grant_type("authorization_code") {
578            return Err(AuthError::auth_method(
579                "oauth2",
580                "Client does not support authorization code grant",
581            ));
582        }
583
584        if !client.redirect_uris.contains(&request.redirect_uri) {
585            return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
586        }
587
588        // Parse and validate scopes
589        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
590        let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
591
592        // Create authorization code with proper user context
593        let auth_code = EnhancedAuthorizationCode::new(
594            client.client_id.clone(),
595            user_context.user_id.clone(), // FIXED: Use real user ID from context
596            request.redirect_uri,
597            authorized_scopes,
598            request.code_challenge,
599            request.code_challenge_method,
600            self.config.authorization_code_lifetime,
601        );
602
603        // Store authorization code
604        drop(storage);
605        let mut storage = self.token_storage.write().await;
606        storage.store_authorization_code(auth_code.clone()).await?;
607
608        Ok(auth_code)
609    }
610
611    /// Handle token exchange with comprehensive validation
612    pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
613        match request.grant_type.as_str() {
614            "authorization_code" => self.handle_authorization_code_grant(request).await,
615            "refresh_token" => self.handle_refresh_token_grant(request).await,
616            "client_credentials" => {
617                let client_id = request.client_id.clone();
618                let requested = request.scope.clone();
619                let result = self.handle_client_credentials_grant(request).await;
620                self.audit_client_credentials(client_id.as_deref(), requested.as_deref(), &result)
621                    .await;
622                result
623            }
624            _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
625        }
626    }
627
628    /// Handle authorization code grant with proper validation
629    async fn handle_authorization_code_grant(
630        &self,
631        request: TokenRequest,
632    ) -> Result<TokenResponse> {
633        let client_id = request
634            .client_id
635            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
636        // Validate client credentials FIRST
637        let storage = self.token_storage.read().await;
638        let _client = storage
639            .get_client_credentials(&client_id)
640            .await?
641            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
642
643        // CRITICAL FIX: Validate client secret properly
644        if !storage
645            .validate_client_credentials(&client_id, request.client_secret.as_deref())
646            .await?
647        {
648            return Err(AuthError::auth_method(
649                "oauth2",
650                "Invalid client credentials",
651            ));
652        }
653
654        // Get and validate authorization code
655        let code = request
656            .code
657            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;
658
659        drop(storage);
660        let mut storage = self.token_storage.write().await;
661        let auth_code = storage
662            .consume_authorization_code(&code)
663            .await?
664            .ok_or_else(|| {
665                AuthError::auth_method("oauth2", "Invalid or expired authorization code")
666            })?;
667
668        // Validate code belongs to this client
669        if auth_code.client_id != client_id {
670            return Err(AuthError::auth_method(
671                "oauth2",
672                "Authorization code does not belong to client",
673            ));
674        }
675
676        // Validate PKCE if required
677        if let Some(challenge) = &auth_code.code_challenge {
678            let verifier = request
679                .code_verifier
680                .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;
681
682            if !self.validate_pkce_challenge(
683                challenge,
684                &verifier,
685                &auth_code.code_challenge_method,
686            )? {
687                return Err(AuthError::auth_method(
688                    "oauth2",
689                    "Invalid PKCE code verifier",
690                ));
691            }
692        }
693
694        // Generate tokens with proper user context
695        let access_token = self
696            .generate_access_token(
697                &auth_code.client_id,
698                Some(&auth_code.user_id), // FIXED: Use actual user ID from auth code
699                &auth_code.scopes,
700            )
701            .await?;
702
703        // Generate refresh token
704        let refresh_token = RefreshToken::new(
705            auth_code.client_id.clone(),
706            auth_code.user_id.clone(), // FIXED: Use actual user ID
707            auth_code.scopes.clone(),  // FIXED: Use authorized scopes from auth code
708            self.config.refresh_token_lifetime,
709        );
710
711        let refresh_token_id = storage.store_refresh_token(refresh_token).await?;
712
713        Ok(TokenResponse {
714            access_token: access_token.access_token,
715            token_type: "Bearer".to_string(),
716            expires_in: self.config.access_token_lifetime.as_secs(),
717            refresh_token: Some(refresh_token_id),
718            scope: Some(auth_code.scopes.join(" ")),
719            id_token: None,
720        })
721    }
722
723    /// Handle refresh token grant with proper validation
724    async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
725        let client_id = request
726            .client_id
727            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
728        // One write lock from the validity check to the revoke: a refresh token rotates exactly
729        // once even when many requests present it at the same time (RFC 6749 section 10.4).
730        let mut storage = self.token_storage.write().await;
731        // Validate client credentials
732        if !storage
733            .validate_client_credentials(&client_id, request.client_secret.as_deref())
734            .await?
735        {
736            return Err(AuthError::auth_method(
737                "oauth2",
738                "Invalid client credentials",
739            ));
740        }
741
742        // Get and validate refresh token
743        let refresh_token_id = request
744            .refresh_token
745            .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
746
747        // CRITICAL FIX: Validate refresh token from storage
748        let stored_token = storage
749            .get_refresh_token(&refresh_token_id)
750            .await?
751            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
752
753        if !stored_token.is_valid() {
754            return Err(AuthError::auth_method(
755                "oauth2",
756                "Refresh token is expired or revoked",
757            ));
758        }
759
760        // Validate token belongs to this client
761        if stored_token.client_id != client_id {
762            return Err(AuthError::auth_method(
763                "oauth2",
764                "Refresh token does not belong to client",
765            ));
766        }
767
768        // Parse requested scopes (must be subset of original)
769        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
770        let authorized_scopes = if requested_scopes.is_empty() {
771            stored_token.scopes.clone() // FIXED: Use original scopes from token
772        } else {
773            self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
774        };
775
776        // Generate new access token
777        let access_token = self
778            .generate_access_token(
779                &stored_token.client_id,
780                Some(&stored_token.user_id), // FIXED: Use actual user ID from token
781                &authorized_scopes,
782            )
783            .await?;
784
785        // Generate new refresh token
786        storage.revoke_refresh_token(&refresh_token_id).await?; // Revoke old token
787
788        let new_refresh_token = RefreshToken::new(
789            stored_token.client_id.clone(),
790            stored_token.user_id.clone(),
791            authorized_scopes.clone(),
792            self.config.refresh_token_lifetime,
793        );
794
795        let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
796
797        Ok(TokenResponse {
798            access_token: access_token.access_token,
799            token_type: "Bearer".to_string(),
800            expires_in: self.config.access_token_lifetime.as_secs(),
801            refresh_token: Some(new_refresh_token_id),
802            scope: Some(authorized_scopes.join(" ")),
803            id_token: None,
804        })
805    }
806
807    /// Record a `client_credentials` grant: who asked, for which scopes, and whether it was issued.
808    /// A failure to store the record is logged and does not change the grant's outcome. The client
809    /// secret and the token are never recorded, and neither is the reason text of a refusal, which
810    /// could echo what the caller sent.
811    async fn audit_client_credentials(
812        &self,
813        client_id: Option<&str>,
814        requested_scope: Option<&str>,
815        result: &Result<TokenResponse>,
816    ) {
817        use crate::audit::{AuditEvent, AuditEventType, EventOutcome, RiskLevel};
818        let Some(audit) = &self.audit else { return };
819        let granted = result.is_ok();
820        let mut event = AuditEvent::builder(
821            AuditEventType::TokenIssued,
822            if granted {
823                "client_credentials grant issued an access token"
824            } else {
825                "client_credentials grant refused"
826            },
827        )
828        .outcome(if granted {
829            EventOutcome::Success
830        } else {
831            EventOutcome::Failure
832        })
833        .risk_level(if granted {
834            RiskLevel::Low
835        } else {
836            RiskLevel::Medium
837        })
838        .with_actor("oauth_client", client_id.unwrap_or("unidentified"))
839        .detail("grant_type", "client_credentials")
840        .detail("requested_scope", requested_scope.unwrap_or(""));
841        if let Ok(response) = result {
842            event = event.detail("granted_scope", response.scope.clone().unwrap_or_default());
843        }
844        let mut event = event.build();
845        if event.id.is_empty() {
846            event.id = uuid::Uuid::new_v4().to_string();
847        }
848        if event.timestamp == std::time::SystemTime::UNIX_EPOCH {
849            event.timestamp = std::time::SystemTime::now();
850        }
851        if let Err(e) = audit.store_event(&event).await {
852            tracing::warn!("Could not record the client_credentials audit event: {e}");
853        }
854    }
855
856    /// Handle client credentials grant with proper validation
857    async fn handle_client_credentials_grant(
858        &self,
859        request: TokenRequest,
860    ) -> Result<TokenResponse> {
861        let client_id = request
862            .client_id
863            .ok_or_else(|| AuthError::auth_method("oauth2", "client_id is required"))?;
864        // Validate client credentials
865        let storage = self.token_storage.read().await;
866        let client = storage
867            .get_client_credentials(&client_id)
868            .await?
869            .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
870
871        // CRITICAL FIX: Validate client secret properly
872        if !storage
873            .validate_client_credentials(&client_id, request.client_secret.as_deref())
874            .await?
875        {
876            return Err(AuthError::auth_method(
877                "oauth2",
878                "Invalid client credentials",
879            ));
880        }
881
882        if !client.supports_grant_type("client_credentials") {
883            return Err(AuthError::auth_method(
884                "oauth2",
885                "Client does not support client credentials grant",
886            ));
887        }
888
889        // Parse and validate scopes
890        let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
891        let authorized_scopes = requested_scopes
892            .iter()
893            .filter(|scope| client.has_scope(scope))
894            .cloned()
895            .collect::<Vec<_>>();
896
897        if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
898            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
899        }
900
901        drop(storage);
902
903        // Generate access token (no user context for client credentials)
904        let access_token = self
905            .generate_access_token(&client_id, None, &authorized_scopes)
906            .await?;
907
908        Ok(TokenResponse {
909            access_token: access_token.access_token,
910            token_type: "Bearer".to_string(),
911            expires_in: self.config.access_token_lifetime.as_secs(),
912            refresh_token: None, // No refresh token for client credentials
913            scope: Some(authorized_scopes.join(" ")),
914            id_token: None,
915        })
916    }
917
918    /// Generate access token with proper validation
919    async fn generate_access_token(
920        &self,
921        client_id: &str,
922        user_id: Option<&str>,
923        scopes: &[String],
924    ) -> Result<AuthToken> {
925        let subject = user_id.unwrap_or(client_id);
926        let scope_list = crate::types::Scopes::from(
927            scopes
928                .iter()
929                .map(|s| s.to_string())
930                .collect::<Vec<String>>(),
931        );
932        // A token issued on a user's behalf carries the client in the signed JWT, so it is a
933        // delegated-access token; a client-credentials token (subject = the client) is not.
934        let mut token = if user_id.is_some() {
935            self.token_manager.create_client_auth_token(
936                subject,
937                scope_list,
938                "oauth2",
939                client_id,
940                Some(self.config.access_token_lifetime),
941            )?
942        } else {
943            self.token_manager.create_auth_token(
944                subject,
945                scope_list,
946                "oauth2",
947                Some(self.config.access_token_lifetime),
948            )?
949        };
950
951        // Add client_id claim
952        token.add_custom_claim(
953            "client_id".to_string(),
954            serde_json::Value::String(client_id.to_string()),
955        );
956
957        // Add user_id claim if present
958        if let Some(uid) = user_id {
959            token.add_custom_claim(
960                "user_id".to_string(),
961                serde_json::Value::String(uid.to_string()),
962            );
963        }
964
965        Ok(token)
966    }
967
968    /// Parse scopes from scope string
969    fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
970        match scope_str {
971            Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
972            None => match &self.config.default_scope {
973                Some(default) => Ok(vec![default.clone()]),
974                None => Ok(vec![]),
975            },
976        }
977    }
978
979    /// Authorize scopes based on client and user permissions
980    fn authorize_scopes(
981        &self,
982        client: &EnhancedClientCredentials,
983        user_context: &UserContext,
984        requested_scopes: &[String],
985    ) -> Result<Vec<String>> {
986        let mut authorized = Vec::new();
987
988        for scope in requested_scopes {
989            // Check if client is allowed this scope
990            if client.has_scope(scope) {
991                // Check if user has this scope (if applicable)
992                if user_context.has_scope(scope) {
993                    authorized.push(scope.clone());
994                }
995            }
996        }
997
998        if authorized.is_empty() && !requested_scopes.is_empty() {
999            return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
1000        }
1001
1002        Ok(authorized)
1003    }
1004
1005    /// Validate that requested scopes are subset of original scopes
1006    fn validate_scope_subset(
1007        &self,
1008        original_scopes: &[String],
1009        requested_scopes: &[String],
1010    ) -> Result<Vec<String>> {
1011        let mut validated = Vec::new();
1012
1013        for scope in requested_scopes {
1014            if original_scopes.contains(scope) {
1015                validated.push(scope.clone());
1016            } else {
1017                return Err(AuthError::auth_method(
1018                    "oauth2",
1019                    format!("Requested scope '{}' not in original grant", scope),
1020                ));
1021            }
1022        }
1023
1024        Ok(validated)
1025    }
1026
1027    /// Validate PKCE code challenge
1028    fn validate_pkce_challenge(
1029        &self,
1030        challenge: &str,
1031        verifier: &str,
1032        method: &Option<String>,
1033    ) -> Result<bool> {
1034        let method = method.as_deref().unwrap_or("plain");
1035
1036        match method {
1037            "plain" => Ok(constant_time_compare(
1038                challenge.as_bytes(),
1039                verifier.as_bytes(),
1040            )),
1041            "S256" => {
1042                use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
1043                use sha2::{Digest, Sha256};
1044
1045                let hash = Sha256::digest(verifier.as_bytes());
1046                let encoded = URL_SAFE_NO_PAD.encode(hash);
1047                Ok(constant_time_compare(
1048                    challenge.as_bytes(),
1049                    encoded.as_bytes(),
1050                ))
1051            }
1052            _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
1053        }
1054    }
1055
1056    /// Revoke token (refresh token or access token)
1057    pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
1058        let mut storage = self.token_storage.write().await;
1059
1060        // Validate client is authorized to revoke this token
1061        if client_id.is_empty() {
1062            return Err(AuthError::auth_method(
1063                "oauth2",
1064                "Client ID is required for token revocation",
1065            ));
1066        }
1067
1068        // Verify client exists by trying to get its credentials
1069        if storage.get_client_credentials(client_id).await.is_err() {
1070            return Err(AuthError::auth_method("oauth2", "Invalid client"));
1071        }
1072
1073        // Try to revoke as refresh token first
1074        if storage.validate_refresh_token(token).await? {
1075            return storage.revoke_refresh_token(token).await;
1076        }
1077
1078        // For access tokens, we would need to maintain a revocation list
1079        // This is a simplified implementation
1080        Ok(false)
1081    }
1082
1083    /// Clean up expired tokens
1084    pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
1085        let mut storage = self.token_storage.write().await;
1086        storage.cleanup_expired_tokens().await
1087    }
1088
1089    /// Add user credentials to the server's token storage.
1090    ///
1091    /// Use this to register users before calling `authenticate_user`.
1092    /// In production this is typically called during server setup or via an
1093    /// administrative API; in tests it provides a way to seed known users
1094    /// without hardcoding them in the library itself.
1095    pub async fn add_user_credentials(
1096        &self,
1097        creds: crate::server::oauth::oauth2_enhanced_storage::UserCredentials,
1098    ) -> Result<()> {
1099        let mut storage = self.token_storage.write().await;
1100        storage.store_user_credentials(creds).await
1101    }
1102
1103    /// Authenticate user and create session
1104    pub async fn authenticate_user(
1105        &self,
1106        username: &str,
1107        password: &str,
1108        scopes: Vec<String>,
1109    ) -> Result<UserContext> {
1110        // CRITICAL SECURITY FIX: Validate credentials against storage
1111        let storage = self.token_storage.read().await;
1112
1113        // Validate username exists and password is correct using storage
1114        if !self
1115            .validate_user_credentials_against_storage(&storage, username, password)
1116            .await?
1117        {
1118            return Err(AuthError::auth_method(
1119                "oauth2",
1120                "Invalid username or password",
1121            ));
1122        }
1123
1124        // Validate user is authorized for requested scopes
1125        let authorized_scopes = self
1126            .validate_user_scopes_against_storage(&storage, username, &scopes)
1127            .await?;
1128
1129        drop(storage);
1130
1131        // Create user context with validated information
1132        let user_context = UserContext::new(
1133            self.generate_user_id(username).await?,
1134            username.to_string(),
1135            self.get_user_email(username).await?,
1136        )
1137        .with_scopes(authorized_scopes);
1138
1139        let mut session_store = self.session_store.write().await;
1140        let _ = session_store.create_session(user_context.clone()); // the id is already in `user_context`
1141
1142        Ok(user_context)
1143    }
1144
1145    /// Validate user credentials against secure storage
1146    async fn validate_user_credentials_against_storage(
1147        &self,
1148        storage: &EnhancedTokenStorage,
1149        username: &str,
1150        password: &str,
1151    ) -> Result<bool> {
1152        // Minimum security requirements - but don't return early to prevent timing attacks
1153        let is_empty = username.is_empty() || password.is_empty();
1154        let is_too_short = password.len() < 8;
1155
1156        // Always perform the expensive bcrypt operation to prevent timing attacks
1157        match storage.get_user_credentials(username).await {
1158            Ok(Some(stored_credentials)) => {
1159                // Use bcrypt to verify password against hash
1160                use bcrypt::verify;
1161                match verify(password, &stored_credentials.password_hash) {
1162                    Ok(is_valid) => {
1163                        // Only return true if all conditions are met
1164                        Ok(is_valid && !is_empty && !is_too_short)
1165                    }
1166                    Err(_) => {
1167                        // Hash verification failed - fail securely
1168                        Ok(false)
1169                    }
1170                }
1171            }
1172            Ok(None) => {
1173                // User not found - still do dummy bcrypt operation to prevent timing attacks
1174                use bcrypt::verify;
1175                let _dummy_result = verify(
1176                    password,
1177                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1178                );
1179                Ok(false)
1180            }
1181            Err(_) => {
1182                // Storage error - still do dummy bcrypt operation to prevent timing attacks
1183                use bcrypt::verify;
1184                let _dummy_result = verify(
1185                    password,
1186                    "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
1187                );
1188                Ok(false)
1189            }
1190        }
1191    }
1192
1193    /// Validate user is authorized for requested scopes using storage
1194    async fn validate_user_scopes_against_storage(
1195        &self,
1196        storage: &EnhancedTokenStorage,
1197        username: &str,
1198        requested_scopes: &[String],
1199    ) -> Result<Vec<String>> {
1200        // Get user permissions from storage
1201        let user_permissions = match storage.get_user_permissions(username).await {
1202            Ok(Some(permissions)) => permissions.scopes,
1203            Ok(None) => {
1204                return Err(AuthError::auth_method(
1205                    "oauth2",
1206                    "User not found in permission store",
1207                ));
1208            }
1209            Err(_) => {
1210                return Err(AuthError::auth_method(
1211                    "oauth2",
1212                    "Failed to retrieve user permissions",
1213                ));
1214            }
1215        };
1216
1217        let mut authorized = Vec::new();
1218        for scope in requested_scopes {
1219            if user_permissions.contains(scope) {
1220                authorized.push(scope.clone());
1221            }
1222        }
1223
1224        // If no scopes requested, give default read scope for valid users
1225        if authorized.is_empty() && !requested_scopes.is_empty() {
1226            return Err(AuthError::auth_method(
1227                "oauth2",
1228                "User not authorized for requested scopes",
1229            ));
1230        }
1231
1232        if authorized.is_empty() {
1233            // Check if user has at least read permission for default scope
1234            if user_permissions.contains(&"read".to_string()) {
1235                authorized.push("read".to_string());
1236            } else {
1237                return Err(AuthError::auth_method(
1238                    "oauth2",
1239                    "User has no authorized scopes",
1240                ));
1241            }
1242        }
1243
1244        Ok(authorized)
1245    }
1246
1247    /// Generate consistent user ID
1248    async fn generate_user_id(&self, username: &str) -> Result<String> {
1249        // In production, this would be the user's UUID from the database
1250        // For now, create a deterministic but unique ID
1251        let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
1252        let hash_str = hex::encode(hash);
1253        Ok(format!("user_{}", &hash_str[0..16]))
1254    }
1255
1256    /// Get user email from user store
1257    async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
1258        let storage = self.token_storage.read().await;
1259        match storage.get_user_credentials(username).await {
1260            Ok(Some(creds)) => Ok(creds.email),
1261            // User not found or storage error — return None rather than a fabricated address.
1262            _ => Ok(None),
1263        }
1264    }
1265
1266    /// Get user context from session
1267    pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
1268        let session_store = self.session_store.read().await;
1269        Ok(session_store.get_session(session_id).cloned())
1270    }
1271
1272    /// Invalidate user session
1273    pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
1274        let mut session_store = self.session_store.write().await;
1275        Ok(session_store.invalidate_session(session_id))
1276    }
1277}