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 storage = self.token_storage.read().await;
405 if !storage
406 .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
407 .await?
408 {
409 return Err(AuthError::auth_method(
410 "oauth2",
411 "Invalid client credentials",
412 ));
413 }
414
415 let refresh_token_id = request
417 .refresh_token
418 .ok_or_else(|| AuthError::auth_method("oauth2", "Missing refresh token"))?;
419
420 let stored_token = storage
422 .get_refresh_token(&refresh_token_id)
423 .await?
424 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid refresh token"))?;
425
426 if !stored_token.is_valid() {
427 return Err(AuthError::auth_method(
428 "oauth2",
429 "Refresh token is expired or revoked",
430 ));
431 }
432
433 if stored_token.client_id != request.client_id {
435 return Err(AuthError::auth_method(
436 "oauth2",
437 "Refresh token does not belong to client",
438 ));
439 }
440
441 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
443 let authorized_scopes = if requested_scopes.is_empty() {
444 stored_token.scopes.clone() } else {
446 self.validate_scope_subset(&stored_token.scopes, &requested_scopes)?
447 };
448
449 drop(storage);
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 let mut storage = self.token_storage.write().await;
462 storage.revoke_refresh_token(&refresh_token_id).await?; let new_refresh_token = RefreshToken::new(
465 stored_token.client_id.clone(),
466 stored_token.user_id.clone(),
467 authorized_scopes.clone(),
468 self.config.refresh_token_lifetime,
469 );
470
471 let new_refresh_token_id = storage.store_refresh_token(new_refresh_token).await?;
472
473 Ok(TokenResponse {
474 access_token: access_token.access_token,
475 token_type: "Bearer".to_string(),
476 expires_in: self.config.access_token_lifetime.as_secs(),
477 refresh_token: Some(new_refresh_token_id),
478 scope: Some(authorized_scopes.join(" ")),
479 id_token: None,
480 })
481 }
482
483 async fn handle_client_credentials_grant(
485 &self,
486 request: TokenRequest,
487 ) -> Result<TokenResponse> {
488 let storage = self.token_storage.read().await;
490 let client = storage
491 .get_client_credentials(&request.client_id)
492 .await?
493 .ok_or_else(|| AuthError::auth_method("oauth2", "Invalid client_id"))?;
494
495 if !storage
497 .validate_client_credentials(&request.client_id, request.client_secret.as_deref())
498 .await?
499 {
500 return Err(AuthError::auth_method(
501 "oauth2",
502 "Invalid client credentials",
503 ));
504 }
505
506 if !client.supports_grant_type("client_credentials") {
507 return Err(AuthError::auth_method(
508 "oauth2",
509 "Client does not support client credentials grant",
510 ));
511 }
512
513 let requested_scopes = self.parse_scopes(request.scope.as_deref())?;
515 let authorized_scopes = requested_scopes
516 .iter()
517 .filter(|scope| client.has_scope(scope))
518 .cloned()
519 .collect::<Vec<_>>();
520
521 if authorized_scopes.is_empty() && !requested_scopes.is_empty() {
522 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
523 }
524
525 drop(storage);
526
527 let access_token = self
529 .generate_access_token(&request.client_id, None, &authorized_scopes)
530 .await?;
531
532 Ok(TokenResponse {
533 access_token: access_token.access_token,
534 token_type: "Bearer".to_string(),
535 expires_in: self.config.access_token_lifetime.as_secs(),
536 refresh_token: None, scope: Some(authorized_scopes.join(" ")),
538 id_token: None,
539 })
540 }
541
542 async fn generate_access_token(
544 &self,
545 client_id: &str,
546 user_id: Option<&str>,
547 scopes: &[String],
548 ) -> Result<AuthToken> {
549 let subject = user_id.unwrap_or(client_id);
550 let mut token = self.token_manager.create_auth_token(
551 subject,
552 scopes.iter().map(|s| s.to_string()).collect(),
553 "oauth2",
554 Some(self.config.access_token_lifetime),
555 )?;
556
557 token.add_custom_claim(
559 "client_id".to_string(),
560 serde_json::Value::String(client_id.to_string()),
561 );
562
563 if let Some(uid) = user_id {
565 token.add_custom_claim(
566 "user_id".to_string(),
567 serde_json::Value::String(uid.to_string()),
568 );
569 }
570
571 Ok(token)
572 }
573
574 fn parse_scopes(&self, scope_str: Option<&str>) -> Result<Vec<String>> {
576 match scope_str {
577 Some(scopes) => Ok(scopes.split_whitespace().map(|s| s.to_string()).collect()),
578 None => match &self.config.default_scope {
579 Some(default) => Ok(vec![default.clone()]),
580 None => Ok(vec![]),
581 },
582 }
583 }
584
585 fn authorize_scopes(
587 &self,
588 client: &EnhancedClientCredentials,
589 user_context: &UserContext,
590 requested_scopes: &[String],
591 ) -> Result<Vec<String>> {
592 let mut authorized = Vec::new();
593
594 for scope in requested_scopes {
595 if client.has_scope(scope) {
597 if user_context.has_scope(scope) {
599 authorized.push(scope.clone());
600 }
601 }
602 }
603
604 if authorized.is_empty() && !requested_scopes.is_empty() {
605 return Err(AuthError::auth_method("oauth2", "No authorized scopes"));
606 }
607
608 Ok(authorized)
609 }
610
611 fn validate_scope_subset(
613 &self,
614 original_scopes: &[String],
615 requested_scopes: &[String],
616 ) -> Result<Vec<String>> {
617 let mut validated = Vec::new();
618
619 for scope in requested_scopes {
620 if original_scopes.contains(scope) {
621 validated.push(scope.clone());
622 } else {
623 return Err(AuthError::auth_method(
624 "oauth2",
625 format!("Requested scope '{}' not in original grant", scope),
626 ));
627 }
628 }
629
630 Ok(validated)
631 }
632
633 fn validate_pkce_challenge(
635 &self,
636 challenge: &str,
637 verifier: &str,
638 method: &Option<String>,
639 ) -> Result<bool> {
640 let method = method.as_deref().unwrap_or("plain");
641
642 match method {
643 "plain" => Ok(constant_time_compare(
644 challenge.as_bytes(),
645 verifier.as_bytes(),
646 )),
647 "S256" => {
648 use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
649 use sha2::{Digest, Sha256};
650
651 let hash = Sha256::digest(verifier.as_bytes());
652 let encoded = URL_SAFE_NO_PAD.encode(hash);
653 Ok(constant_time_compare(
654 challenge.as_bytes(),
655 encoded.as_bytes(),
656 ))
657 }
658 _ => Err(AuthError::auth_method("oauth2", "Unsupported PKCE method")),
659 }
660 }
661
662 pub async fn revoke_token(&self, token: &str, client_id: &str) -> Result<bool> {
664 let mut storage = self.token_storage.write().await;
665
666 if client_id.is_empty() {
668 return Err(AuthError::auth_method(
669 "oauth2",
670 "Client ID is required for token revocation",
671 ));
672 }
673
674 if storage.get_client_credentials(client_id).await.is_err() {
676 return Err(AuthError::auth_method("oauth2", "Invalid client"));
677 }
678
679 if storage.validate_refresh_token(token).await? {
681 return storage.revoke_refresh_token(token).await;
682 }
683
684 Ok(false)
687 }
688
689 pub async fn cleanup_expired_tokens(&self) -> Result<usize> {
691 let mut storage = self.token_storage.write().await;
692 storage.cleanup_expired_tokens().await
693 }
694
695 pub async fn authenticate_user(
697 &self,
698 username: &str,
699 password: &str,
700 scopes: Vec<String>,
701 ) -> Result<UserContext> {
702 let storage = self.token_storage.read().await;
704
705 if !self
707 .validate_user_credentials_against_storage(&storage, username, password)
708 .await?
709 {
710 return Err(AuthError::auth_method(
711 "oauth2",
712 "Invalid username or password",
713 ));
714 }
715
716 let authorized_scopes = self
718 .validate_user_scopes_against_storage(&storage, username, &scopes)
719 .await?;
720
721 drop(storage);
722
723 let user_context = UserContext::new(
725 self.generate_user_id(username).await?,
726 username.to_string(),
727 self.get_user_email(username).await?,
728 )
729 .with_scopes(authorized_scopes);
730
731 let mut session_store = self.session_store.write().await;
732 session_store.create_session(user_context.clone());
733
734 Ok(user_context)
735 }
736
737 async fn validate_user_credentials_against_storage(
739 &self,
740 storage: &EnhancedTokenStorage,
741 username: &str,
742 password: &str,
743 ) -> Result<bool> {
744 let is_empty = username.is_empty() || password.is_empty();
746 let is_too_short = password.len() < 8;
747
748 match storage.get_user_credentials(username).await {
750 Ok(Some(stored_credentials)) => {
751 use bcrypt::verify;
753 match verify(password, &stored_credentials.password_hash) {
754 Ok(is_valid) => {
755 Ok(is_valid && !is_empty && !is_too_short)
757 }
758 Err(_) => {
759 Ok(false)
761 }
762 }
763 }
764 Ok(None) => {
765 use bcrypt::verify;
767 let _dummy_result = verify(
768 password,
769 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
770 );
771 Ok(false)
772 }
773 Err(_) => {
774 use bcrypt::verify;
776 let _dummy_result = verify(
777 password,
778 "$2b$12$K2CtDP7zMH7VgxScmHTa/.EUm5nd9.xnZM8Cl/p9RMb5QZaJUHgBm",
779 );
780 Ok(false)
781 }
782 }
783 }
784
785 async fn validate_user_scopes_against_storage(
787 &self,
788 storage: &EnhancedTokenStorage,
789 username: &str,
790 requested_scopes: &[String],
791 ) -> Result<Vec<String>> {
792 let user_permissions = match storage.get_user_permissions(username).await {
794 Ok(Some(permissions)) => permissions.scopes,
795 Ok(None) => {
796 return Err(AuthError::auth_method(
797 "oauth2",
798 "User not found in permission store",
799 ));
800 }
801 Err(_) => {
802 return Err(AuthError::auth_method(
803 "oauth2",
804 "Failed to retrieve user permissions",
805 ));
806 }
807 };
808
809 let mut authorized = Vec::new();
810 for scope in requested_scopes {
811 if user_permissions.contains(scope) {
812 authorized.push(scope.clone());
813 }
814 }
815
816 if authorized.is_empty() && !requested_scopes.is_empty() {
818 return Err(AuthError::auth_method(
819 "oauth2",
820 "User not authorized for requested scopes",
821 ));
822 }
823
824 if authorized.is_empty() {
825 if user_permissions.contains(&"read".to_string()) {
827 authorized.push("read".to_string());
828 } else {
829 return Err(AuthError::auth_method(
830 "oauth2",
831 "User has no authorized scopes",
832 ));
833 }
834 }
835
836 Ok(authorized)
837 }
838
839 async fn generate_user_id(&self, username: &str) -> Result<String> {
841 let hash = Sha256::digest(format!("user_id_{}", username).as_bytes());
844 let hash_str = format!("{:x}", hash);
845 Ok(format!("user_{}", &hash_str[0..16]))
846 }
847
848 async fn get_user_email(&self, username: &str) -> Result<Option<String>> {
850 Ok(Some(format!("{}@example.com", username)))
852 }
853
854 pub async fn get_user_context(&self, session_id: &str) -> Result<Option<UserContext>> {
856 let session_store = self.session_store.read().await;
857 Ok(session_store.get_session(session_id).cloned())
858 }
859
860 pub async fn invalidate_session(&self, session_id: &str) -> Result<bool> {
862 let mut session_store = self.session_store.write().await;
863 Ok(session_store.invalidate_session(session_id))
864 }
865}