1use crate::errors::{AuthError, Result};
7use crate::oauth2_enhanced_storage::{
8 EnhancedAuthorizationCode, EnhancedClientCredentials, EnhancedTokenStorage, RefreshToken,
9};
10use crate::security::secure_utils::constant_time_compare;
11use crate::tokens::{AuthToken, TokenManager};
12use crate::user_context::{SessionStore, UserContext};
13use serde::{Deserialize, Serialize};
14use sha2::{Digest, Sha256};
15use std::sync::Arc;
16use std::time::Duration;
17use tokio::sync::RwLock;
18
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
21pub enum GrantType {
22 AuthorizationCode,
23 RefreshToken,
24 ClientCredentials,
25 DeviceCode,
26 TokenExchange,
27}
28
29impl std::fmt::Display for GrantType {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 GrantType::AuthorizationCode => write!(f, "authorization_code"),
33 GrantType::RefreshToken => write!(f, "refresh_token"),
34 GrantType::ClientCredentials => write!(f, "client_credentials"),
35 GrantType::DeviceCode => write!(f, "urn:ietf:params:oauth:grant-type:device_code"),
36 GrantType::TokenExchange => {
37 write!(f, "urn:ietf:params:oauth:grant-type:token-exchange")
38 }
39 }
40 }
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45pub enum ResponseType {
46 Code,
47 Token,
48 IdToken,
49}
50
51#[derive(Debug, Clone)]
53pub struct OAuth2Config {
54 pub issuer: String,
56 pub authorization_code_lifetime: Duration,
58 pub access_token_lifetime: Duration,
60 pub refresh_token_lifetime: Duration,
62 pub device_code_lifetime: Duration,
64 pub default_scope: Option<String>,
66 pub max_scope_lifetime: Duration,
68 pub require_pkce: bool,
70 pub enable_introspection: bool,
72 pub enable_revocation: bool,
74}
75
76impl Default for OAuth2Config {
77 fn default() -> Self {
78 Self {
79 issuer: "https://auth.example.com".to_string(),
80 authorization_code_lifetime: Duration::from_secs(600), 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()),
85 max_scope_lifetime: Duration::from_secs(86400 * 30), require_pkce: true,
87 enable_introspection: true,
88 enable_revocation: true,
89 }
90 }
91}
92
93#[derive(Clone, Serialize, Deserialize, Default)]
95pub struct TokenRequest {
96 pub grant_type: String,
97 pub client_id: String,
98 pub client_secret: Option<String>,
99 pub code: Option<String>,
100 pub redirect_uri: Option<String>,
101 pub refresh_token: Option<String>,
102 pub scope: Option<String>,
103 pub code_verifier: Option<String>,
104 pub username: Option<String>,
105 pub password: Option<String>,
106 pub device_code: Option<String>,
107}
108
109impl std::fmt::Debug for TokenRequest {
110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 let mut d = f.debug_struct("TokenRequest");
112 d.field("grant_type", &self.grant_type);
113 d.field("client_id", &self.client_id);
114 d.field(
115 "client_secret",
116 &crate::utils::redact::redacted(&self.client_secret),
117 );
118 d.field("code", &crate::utils::redact::redacted(&self.code));
119 d.field("redirect_uri", &self.redirect_uri);
120 d.field(
121 "refresh_token",
122 &crate::utils::redact::redacted(&self.refresh_token),
123 );
124 d.field("scope", &self.scope);
125 d.field(
126 "code_verifier",
127 &crate::utils::redact::redacted(&self.code_verifier),
128 );
129 d.field("username", &self.username);
130 d.field("password", &crate::utils::redact::redacted(&self.password));
131 d.field(
132 "device_code",
133 &crate::utils::redact::redacted(&self.device_code),
134 );
135 d.finish()
136 }
137}
138
139#[derive(Clone, Serialize, Deserialize)]
141pub struct TokenResponse {
142 pub access_token: String,
143 pub token_type: String,
144 pub expires_in: u64,
145 pub refresh_token: Option<String>,
146 pub scope: Option<String>,
147 pub id_token: Option<String>,
148}
149
150impl std::fmt::Debug for TokenResponse {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 let mut d = f.debug_struct("TokenResponse");
153 d.field(
154 "access_token",
155 &crate::utils::redact::redacted(&self.access_token),
156 );
157 d.field("token_type", &self.token_type);
158 d.field("expires_in", &self.expires_in);
159 d.field(
160 "refresh_token",
161 &crate::utils::redact::redacted(&self.refresh_token),
162 );
163 d.field("scope", &self.scope);
164 d.field("id_token", &crate::utils::redact::redacted(&self.id_token));
165 d.finish()
166 }
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct AuthorizationRequest {
172 pub client_id: String,
173 pub response_type: String,
174 pub redirect_uri: String,
175 pub scope: Option<String>,
176 pub state: Option<String>,
177 pub code_challenge: Option<String>,
178 pub code_challenge_method: Option<String>,
179 pub nonce: Option<String>,
180}
181
182pub struct OAuth2Server {
184 config: OAuth2Config,
185 token_storage: Arc<RwLock<EnhancedTokenStorage>>,
186 session_store: Arc<RwLock<SessionStore>>,
187 token_manager: Arc<TokenManager>,
188}
189
190impl OAuth2Server {
191 pub async fn new(config: OAuth2Config, token_manager: Arc<TokenManager>) -> Result<Self> {
192 Ok(Self {
193 config,
194 token_storage: Arc::new(RwLock::new(EnhancedTokenStorage::new())),
195 session_store: Arc::new(RwLock::new(SessionStore::new())),
196 token_manager,
197 })
198 }
199
200 pub async fn register_confidential_client(
202 &self,
203 client_id: String,
204 client_secret: &str,
205 redirect_uris: Vec<String>,
206 allowed_scopes: Vec<String>,
207 grant_types: Vec<String>,
208 ) -> Result<()> {
209 if client_secret.len() < 32 {
211 return Err(AuthError::auth_method(
212 "oauth2",
213 "Client secret must be at least 32 characters",
214 ));
215 }
216
217 let credentials = EnhancedClientCredentials::new_confidential(
218 client_id,
219 client_secret,
220 redirect_uris,
221 allowed_scopes,
222 grant_types,
223 )?;
224
225 let mut storage = self.token_storage.write().await;
226 storage.store_client_credentials(credentials).await?;
227
228 Ok(())
229 }
230
231 pub async fn register_public_client(
233 &self,
234 client_id: String,
235 redirect_uris: Vec<String>,
236 allowed_scopes: Vec<String>,
237 grant_types: Vec<String>,
238 ) -> Result<()> {
239 let credentials = EnhancedClientCredentials::new_public(
240 client_id,
241 redirect_uris,
242 allowed_scopes,
243 grant_types,
244 );
245
246 let mut storage = self.token_storage.write().await;
247 storage.store_client_credentials(credentials).await?;
248
249 Ok(())
250 }
251
252 pub async fn create_authorization_code(
254 &self,
255 request: AuthorizationRequest,
256 user_context: UserContext,
257 ) -> Result<EnhancedAuthorizationCode> {
258 let storage = self.token_storage.read().await;
260 let client = storage
261 .get_client_credentials(&request.client_id)
262 .await?
263 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
264
265 if !client.supports_grant_type("authorization_code") {
266 return Err(AuthError::auth_method(
267 "oauth2",
268 "Client does not support authorization code grant",
269 ));
270 }
271
272 if !client.redirect_uris.contains(&request.redirect_uri) {
273 return Err(AuthError::auth_method("oauth2", "Invalid redirect_uri"));
274 }
275
276 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
278 let authorized_scopes = self.authorize_scopes(&client, &user_context, &requested_scopes)?;
279
280 let auth_code = EnhancedAuthorizationCode::new(
282 client.client_id.clone(),
283 user_context.user_id.clone(), request.redirect_uri,
285 authorized_scopes,
286 request.code_challenge,
287 request.code_challenge_method,
288 self.config.authorization_code_lifetime,
289 );
290
291 drop(storage);
293 let mut storage = self.token_storage.write().await;
294 storage.store_authorization_code(auth_code.clone()).await?;
295
296 Ok(auth_code)
297 }
298
299 pub async fn token_exchange(&self, request: TokenRequest) -> Result<TokenResponse> {
301 match request.grant_type.as_str() {
302 "authorization_code" => self.handle_authorization_code_grant(request).await,
303 "refresh_token" => self.handle_refresh_token_grant(request).await,
304 "client_credentials" => self.handle_client_credentials_grant(request).await,
305 _ => Err(AuthError::auth_method("oauth2", "Unsupported grant type")),
306 }
307 }
308
309 async fn handle_authorization_code_grant(
311 &self,
312 request: TokenRequest,
313 ) -> Result<TokenResponse> {
314 let storage = self.token_storage.read().await;
316 let _client = storage
317 .get_client_credentials(&request.client_id)
318 .await?
319 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
320
321 if !storage
323 .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
324 .await?
325 {
326 return Err(AuthError::auth_method(
327 "oauth2",
328 "Invalid client credentials",
329 ));
330 }
331
332 let code = request
334 .code
335 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing authorization code"))?;
336
337 drop(storage);
338 let mut storage = self.token_storage.write().await;
339 let auth_code = storage
340 .consume_authorization_code(&code)
341 .await?
342 .ok_or_else(|| {
343 AuthError::auth_method("oauth2", "Invalid or expired authorization code")
344 })?;
345
346 if auth_code.client_id != request.client_id {
348 return Err(AuthError::auth_method(
349 "oauth2",
350 "Authorization code does not belong to client",
351 ));
352 }
353
354 if let Some(challenge) = &auth_code.code_challenge {
356 let verifier = request
357 .code_verifier
358 .ok_or_else(|| AuthError::auth_method("oauth2", "PKCE code verifier required"))?;
359
360 if !self.validate_pkce_challenge(
361 challenge,
362 &verifier,
363 &auth_code.code_challenge_method,
364 )? {
365 return Err(AuthError::auth_method(
366 "oauth2",
367 "Invalid PKCE code verifier",
368 ));
369 }
370 }
371
372 let access_token = self
374 .generate_access_token(
375 &auth_code.client_id,
376 Some(&auth_code.user_id), &auth_code.scopes,
378 )
379 .await?;
380
381 let refresh_token = RefreshToken::new(
383 auth_code.client_id.clone(),
384 auth_code.user_id.clone(), auth_code.scopes.clone(), self.config.refresh_token_lifetime,
387 );
388
389 let refresh_token_id = storage.store_refresh_token(refresh_token).await?;
390
391 Ok(TokenResponse {
392 access_token: access_token.access_token,
393 token_type: "Bearer".to_string(),
394 expires_in: self.config.access_token_lifetime.as_secs(),
395 refresh_token: Some(refresh_token_id),
396 scope: Some(auth_code.scopes.join(" ")),
397 id_token: None,
398 })
399 }
400
401 async fn handle_refresh_token_grant(&self, request: TokenRequest) -> Result<TokenResponse> {
403 let mut storage = self.token_storage.write().await;
406 if !storage
408 .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
409 .await?
410 {
411 return Err(AuthError::auth_method(
412 "oauth2",
413 "Invalid client credentials",
414 ));
415 }
416
417 let refresh_token_id = request
419 .refresh_token
420 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
421
422 let stored_token = storage
424 .get_refresh_token(&refresh_token_id)
425 .await?
426 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
427
428 if !stored_token.is_valid() {
429 return Err(AuthError::auth_method(
430 "oauth2",
431 "Refresh token is expired or revoked",
432 ));
433 }
434
435 if stored_token.client_id != request.client_id {
437 return Err(AuthError::auth_method(
438 "oauth2",
439 "Refresh token does not belong to client",
440 ));
441 }
442
443 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
445 let authorized_scopes = if requested_scopes.is_empty() {
446 stored_token.scopes.clone() } else {
448 self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
449 };
450
451 let access_token = self
453 .generate_access_token(
454 &stored_token.client_id,
455 Some(&stored_token.user_id), &authorized_scopes,
457 )
458 .await?;
459
460 storage.revoke_refresh_token(&refresh_token_id).await?; let new_refresh_token = RefreshToken::new(
464 stored_token.client_id.clone(),
465 stored_token.user_id.clone(),
466 authorized_scopes.clone(),
467 self.config.refresh_token_lifetime,
468 );
469
470 let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
471
472 Ok(TokenResponse {
473 access_token: access_token.access_token,
474 token_type: "Bearer".to_string(),
475 expires_in: self.config.access_token_lifetime.as_secs(),
476 refresh_token: Some(new_refresh_token_id),
477 scope: Some(authorized_scopes.join(" ")),
478 id_token: None,
479 })
480 }
481
482 async fn handle_client_credentials_grant(
484 &self,
485 request: TokenRequest,
486 ) -> Result<TokenResponse> {
487 let storage = self.token_storage.read().await;
489 let client = storage
490 .get_client_credentials(&request.client_id)
491 .await?
492 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
493
494 if !storage
496 .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
497 .await?
498 {
499 return Err(AuthError::auth_method(
500 "oauth2",
501 "Invalid client credentials",
502 ));
503 }
504
505 if !client.supports_grant_type("client_credentials") {
506 return Err(AuthError::auth_method(
507 "oauth2",
508 "Client does not support client credentials grant",
509 ));
510 }
511
512 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
514 let authorized_scopes = requested_scopes
515 .iter()
516 .filter(|scope| client.has_scope(scope))
517 .cloned()
518 .collect::<Vec<_>>();
519
520 if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
521 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
522 }
523
524 drop(storage);
525
526 let access_token = self
528 .generate_access_token(&request.client_id, None, &authorized_scopes)
529 .await?;
530
531 Ok(TokenResponse {
532 access_token: access_token.access_token,
533 token_type: "Bearer".to_string(),
534 expires_in: self.config.access_token_lifetime.as_secs(),
535 refresh_token: None, scope: Some(authorized_scopes.join(" ")),
537 id_token: None,
538 })
539 }
540
541 async fn generate_access_token(
543 &self,
544 client_id: &str,
545 user_id: Option<&str>,
546 scopes: &[String],
547 ) -> Result<AuthToken> {
548 let subject = user_id.unwrap_or(client_id);
549 let mut token = self.token_manager.create_client_auth_token(
551 subject,
552 client_id,
553 scopes.iter().map(|s| s.to_string()).collect(),
554 "oauth2",
555 Some(self.config.access_token_lifetime),
556 )?;
557
558 token.add_custom_claim(
560 "client_id".to_string(),
561 serde_json::Value::String(client_id.to_string()),
562 );
563
564 if let Some(uid) = user_id {
566 token.add_custom_claim(
567 "user_id".to_string(),
568 serde_json::Value::String(uid.to_string()),
569 );
570 }
571
572 Ok(token)
573 }
574
575 fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
577 match scope_str {
578 Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
579 None => match &self.config.default_scope {
580 Some(default) => Ok(vec![default.clone()]),
581 None => Ok(vec![]),
582 },
583 }
584 }
585
586 fn authorize_scopes(
588 &self,
589 client: &EnhancedClientCredentials,
590 user_context: &UserContext,
591 requested_scopes: &[String],
592 ) -> Result<Vec<String>> {
593 let mut authorized = Vec::new();
594
595 for scope in requested_scopes {
596 if client.has_scope(scope) {
598 if user_context.has_scope(scope) {
600 authorized.push(scope.clone());
601 }
602 }
603 }
604
605 if authorized.is_empty() && !requested_scopes.is_empty() {
606 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
607 }
608
609 Ok(authorized)
610 }
611
612 fn validate_scope_subset(
614 &self,
615 original_scopes: &[String],
616 requested_scopes: &[String],
617 ) -> Result<Vec<String>> {
618 let mut validated = Vec::new();
619
620 for scope in requested_scopes {
621 if original_scopes.contains(scope) {
622 validated.push(scope.clone());
623 } else {
624 return Err(AuthError::auth_method(
625 "oauth2",
626 format!("Requested scope '{}' not in original grant", scope),
627 ));
628 }
629 }
630
631 Ok(validated)
632 }
633
634 fn validate_pkce_challenge(
636 &self,
637 challenge: &str,
638 verifier: &str,
639 method: &Option<String>,
640 ) -> Result<bool> {
641 let method = method.as_deref().unwrap_or("plain");
642
643 match method {
644 "plain" => Ok(constant_time_compare(
645 challenge.as_bytes(),
646 verifier.as_bytes(),
647 )),
648 "S256" => {
649 use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
650 use sha2::{Digest, Sha256};
651
652 let hash = Sha256::digest(verifier.as_bytes());
653 let encoded = URL_SAFE_NO_PAD.encode(hash);
654 Ok(constant_time_compare(
655 challenge.as_bytes(),
656 encoded.as_bytes(),
657 ))
658 }
659 _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
660 }
661 }
662
663 pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
665 let mut storage = self.token_storage.write().await;
666
667 if client_id.is_empty() {
669 return Err(AuthError::auth_method(
670 "oauth2",
671 "Client ID is required for token revocation",
672 ));
673 }
674
675 if storage.get_client_credentials(client_id).await.is_err() {
677 return Err(AuthError::auth_method("oauth2", "Invalid client"));
678 }
679
680 if storage.validate_refresh_token(token).await? {
682 return storage.revoke_refresh_token(token).await;
683 }
684
685 Ok(false)
688 }
689
690 pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
692 let mut storage = self.token_storage.write().await;
693 storage.cleanup_expired_tokens().await
694 }
695
696 pub async fn authenticate_user(
698 &self,
699 username: &str,
700 password: &str,
701 scopes: Vec<String>,
702 ) -> Result<UserContext> {
703 let storage = self.token_storage.read().await;
705
706 if !self
708 .validate_user_credentials_against_storage(&storage, username, password)
709 .await?
710 {
711 return Err(AuthError::auth_method(
712 "oauth2",
713 "Invalid username or password",
714 ));
715 }
716
717 let authorized_scopes = self
719 .validate_user_scopes_against_storage(&storage, username, &scopes)
720 .await?;
721
722 drop(storage);
723
724 let user_context = UserContext::new(
726 self.generate_user_id(username).await?,
727 username.to_string(),
728 self.get_user_email(username).await?,
729 )
730 .with_scopes(authorized_scopes);
731
732 let mut session_store = self.session_store.write().await;
733 session_store.create_session(user_context.clone());
734
735 Ok(user_context)
736 }
737
738 async fn validate_user_credentials_against_storage(
740 &self,
741 storage: &EnhancedTokenStorage,
742 username: &str,
743 password: &str,
744 ) -> Result<bool> {
745 let is_empty = username.is_empty() || password.is_empty();
747 let is_too_short = password.len() < 8;
748
749 match storage.get_user_credentials(username).await {
751 Ok(Some(stored_credentials)) => {
752 use bcrypt::verify;
754 match verify(password, &stored_credentials.password_hash) {
755 Ok(is_valid) => {
756 Ok(is_valid && !is_empty && !is_too_short)
758 }
759 Err(_) => {
760 Ok(false)
762 }
763 }
764 }
765 Ok(None) => {
766 use bcrypt::verify;
768 let _dummy_result = verify(
769 password,
770 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
771 );
772 Ok(false)
773 }
774 Err(_) => {
775 use bcrypt::verify;
777 let _dummy_result = verify(
778 password,
779 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
780 );
781 Ok(false)
782 }
783 }
784 }
785
786 async fn validate_user_scopes_against_storage(
788 &self,
789 storage: &EnhancedTokenStorage,
790 username: &str,
791 requested_scopes: &[String],
792 ) -> Result<Vec<String>> {
793 let user_permissions = match storage.get_user_permissions(username).await {
795 Ok(Some(permissions)) => permissions.scopes,
796 Ok(None) => {
797 return Err(AuthError::auth_method(
798 "oauth2",
799 "User not found in permission store",
800 ));
801 }
802 Err(_) => {
803 return Err(AuthError::auth_method(
804 "oauth2",
805 "Failed to retrieve user permissions",
806 ));
807 }
808 };
809
810 let mut authorized = Vec::new();
811 for scope in requested_scopes {
812 if user_permissions.contains(scope) {
813 authorized.push(scope.clone());
814 }
815 }
816
817 if authorized.is_empty() && !requested_scopes.is_empty() {
819 return Err(AuthError::auth_method(
820 "oauth2",
821 "User not authorized for requested scopes",
822 ));
823 }
824
825 if authorized.is_empty() {
826 if user_permissions.contains(&"read".to_string()) {
828 authorized.push("read".to_string());
829 } else {
830 return Err(AuthError::auth_method(
831 "oauth2",
832 "User has no authorized scopes",
833 ));
834 }
835 }
836
837 Ok(authorized)
838 }
839
840 async fn generate_user_id(&self, username: &str) -> Result<String> {
842 let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
845 let hash_str = format!("{:x}", hash);
846 Ok(format!("user_{}", &hash_str[0..16]))
847 }
848
849 async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
851 Ok(Some(format!("{}@example.com", username)))
853 }
854
855 pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
857 let session_store = self.session_store.read().await;
858 Ok(session_store.get_session(session_id).cloned())
859 }
860
861 pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
863 let mut session_store = self.session_store.write().await;
864 Ok(session_store.invalidate_session(session_id))
865 }
866}