1use 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#[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#[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#[derive(Debug, Clone)]
97pub struct OAuth2Config {
98 pub issuer: String,
100 pub authorization_code_lifetime: Duration,
102 pub access_token_lifetime: Duration,
104 pub refresh_token_lifetime: Duration,
106 pub device_code_lifetime: Duration,
108 pub default_scope: Option<String>,
110 pub max_scope_lifetime: Duration,
112 pub require_pkce: bool,
114 pub enable_introspection: bool,
116 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), access_token_lifetime: Duration::from_secs(3600), refresh_token_lifetime: Duration::from_secs(86400 * 7), device_code_lifetime: Duration::from_secs(600), default_scope: Some("read".to_string()),
129 max_scope_lifetime: Duration::from_secs(86400 * 30), require_pkce: true,
131 enable_introspection: true,
132 enable_revocation: true,
133 }
134 }
135}
136
137impl OAuth2Config {
138 pub fn builder() -> OAuth2ConfigBuilder {
153 OAuth2ConfigBuilder::default()
154 }
155}
156
157#[derive(Debug, Clone, Default)]
162pub struct OAuth2ConfigBuilder {
163 config: OAuth2Config,
164}
165
166impl OAuth2ConfigBuilder {
167 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
169 self.config.issuer = issuer.into();
170 self
171 }
172
173 pub fn authorization_code_lifetime(mut self, lifetime: Duration) -> Self {
175 self.config.authorization_code_lifetime = lifetime;
176 self
177 }
178
179 pub fn access_token_lifetime(mut self, lifetime: Duration) -> Self {
181 self.config.access_token_lifetime = lifetime;
182 self
183 }
184
185 pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
187 self.config.refresh_token_lifetime = lifetime;
188 self
189 }
190
191 pub fn device_code_lifetime(mut self, lifetime: Duration) -> Self {
193 self.config.device_code_lifetime = lifetime;
194 self
195 }
196
197 pub fn default_scope(mut self, scope: impl Into<String>) -> Self {
199 self.config.default_scope = Some(scope.into());
200 self
201 }
202
203 pub fn max_scope_lifetime(mut self, lifetime: Duration) -> Self {
205 self.config.max_scope_lifetime = lifetime;
206 self
207 }
208
209 pub fn require_pkce(mut self, require: bool) -> Self {
211 self.config.require_pkce = require;
212 self
213 }
214
215 pub fn enable_introspection(mut self, enable: bool) -> Self {
217 self.config.enable_introspection = enable;
218 self
219 }
220
221 pub fn enable_revocation(mut self, enable: bool) -> Self {
223 self.config.enable_revocation = enable;
224 self
225 }
226
227 pub fn build(self) -> OAuth2Config {
229 self.config
230 }
231}
232
233#[derive(Clone, Serialize, Deserialize, Default)]
255pub struct TokenRequest {
256 pub grant_type: String,
257 #[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 #[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 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 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 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 pub fn client_id(mut self, id: impl Into<String>) -> Self {
340 self.client_id = Some(id.into());
341 self
342 }
343
344 pub fn client_secret(mut self, secret: impl Into<String>) -> Self {
346 self.client_secret = Some(secret.into());
347 self
348 }
349
350 pub fn redirect_uri(mut self, uri: impl Into<String>) -> Self {
352 self.redirect_uri = Some(uri.into());
353 self
354 }
355
356 pub fn code_verifier(mut self, verifier: impl Into<String>) -> Self {
358 self.code_verifier = Some(verifier.into());
359 self
360 }
361
362 pub fn scope(mut self, scope: impl Into<String>) -> Self {
364 self.scope = Some(scope.into());
365 self
366 }
367
368 pub fn resource(mut self, uris: Vec<String>) -> Self {
370 self.resource = Some(uris);
371 self
372 }
373}
374
375#[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#[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 #[serde(default)]
429 pub resource: Option<Vec<String>>,
430}
431
432impl AuthorizationRequest {
433 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 pub fn scope(mut self, scope: impl Into<String>) -> Self {
454 self.scope = Some(scope.into());
455 self
456 }
457
458 pub fn state(mut self, state: impl Into<String>) -> Self {
460 self.state = Some(state.into());
461 self
462 }
463
464 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 pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
473 self.nonce = Some(nonce.into());
474 self
475 }
476
477 pub fn resource(mut self, uris: Vec<String>) -> Self {
479 self.resource = Some(uris);
480 self
481 }
482}
483
484pub 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 pub fn with_audit_storage(mut self, storage: Arc<dyn crate::audit::AuditStorage>) -> Self {
508 self.audit = Some(storage);
509 self
510 }
511
512 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 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 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 pub async fn create_authorization_code(
566 &self,
567 request: AuthorizationRequest,
568 user_context: UserContext,
569 ) -> Result<EnhancedAuthorizationCode> {
570 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 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
590 let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
591
592 let auth_code = EnhancedAuthorizationCode::new(
594 client.client_id.clone(),
595 user_context.user_id.clone(), request.redirect_uri,
597 authorized_scopes,
598 request.code_challenge,
599 request.code_challenge_method,
600 self.config.authorization_code_lifetime,
601 );
602
603 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 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 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 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 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 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 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 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 let access_token = self
696 .generate_access_token(
697 &auth_code.client_id,
698 Some(&auth_code.user_id), &auth_code.scopes,
700 )
701 .await?;
702
703 let refresh_token = RefreshToken::new(
705 auth_code.client_id.clone(),
706 auth_code.user_id.clone(), auth_code.scopes.clone(), 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 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 let mut storage = self.token_storage.write().await;
731 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 let refresh_token_id = request
744 .refresh_token
745 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
746
747 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 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 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
770 let authorized_scopes = if requested_scopes.is_empty() {
771 stored_token.scopes.clone() } else {
773 self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
774 };
775
776 let access_token = self
778 .generate_access_token(
779 &stored_token.client_id,
780 Some(&stored_token.user_id), &authorized_scopes,
782 )
783 .await?;
784
785 storage.revoke_refresh_token(&refresh_token_id).await?; 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 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 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 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 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 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 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, scope: Some(authorized_scopes.join(" ")),
914 id_token: None,
915 })
916 }
917
918 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 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 token.add_custom_claim(
953 "client_id".to_string(),
954 serde_json::Value::String(client_id.to_string()),
955 );
956
957 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 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 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 if client.has_scope(scope) {
991 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 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 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 pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
1058 let mut storage = self.token_storage.write().await;
1059
1060 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 if storage.get_client_credentials(client_id).await.is_err() {
1070 return Err(AuthError::auth_method("oauth2", "Invalid client"));
1071 }
1072
1073 if storage.validate_refresh_token(token).await? {
1075 return storage.revoke_refresh_token(token).await;
1076 }
1077
1078 Ok(false)
1081 }
1082
1083 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 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 pub async fn authenticate_user(
1105 &self,
1106 username: &str,
1107 password: &str,
1108 scopes: Vec<String>,
1109 ) -> Result<UserContext> {
1110 let storage = self.token_storage.read().await;
1112
1113 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 let authorized_scopes = self
1126 .validate_user_scopes_against_storage(&storage, username, &scopes)
1127 .await?;
1128
1129 drop(storage);
1130
1131 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()); Ok(user_context)
1143 }
1144
1145 async fn validate_user_credentials_against_storage(
1147 &self,
1148 storage: &EnhancedTokenStorage,
1149 username: &str,
1150 password: &str,
1151 ) -> Result<bool> {
1152 let is_empty = username.is_empty() || password.is_empty();
1154 let is_too_short = password.len() < 8;
1155
1156 match storage.get_user_credentials(username).await {
1158 Ok(Some(stored_credentials)) => {
1159 use bcrypt::verify;
1161 match verify(password, &stored_credentials.password_hash) {
1162 Ok(is_valid) => {
1163 Ok(is_valid && !is_empty && !is_too_short)
1165 }
1166 Err(_) => {
1167 Ok(false)
1169 }
1170 }
1171 }
1172 Ok(None) => {
1173 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 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 async fn validate_user_scopes_against_storage(
1195 &self,
1196 storage: &EnhancedTokenStorage,
1197 username: &str,
1198 requested_scopes: &[String],
1199 ) -> Result<Vec<String>> {
1200 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 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 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 async fn generate_user_id(&self, username: &str) -> Result<String> {
1249 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 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 _ => Ok(None),
1263 }
1264 }
1265
1266 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 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}