1pub mod authorization_manager;
61pub mod mfa;
62pub mod session_manager;
63pub mod user_manager;
64
65use crate::authentication::credentials::{Credential, CredentialMetadata};
66use crate::config::AuthConfig;
67use crate::errors::{AuthError, MfaError, Result};
68use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
69use crate::permissions::{Permission, PermissionChecker};
70use crate::storage::{AuthStorage, MemoryStorage};
71use crate::tokens::{AuthToken, TokenManager};
72use crate::utils::rate_limit::RateLimiter;
73use std::collections::HashMap;
74use std::sync::Arc;
75use tokio::sync::RwLock;
76use tracing::{debug, error, info, warn};
77
78pub use authorization_manager::AuthorizationManager;
79pub use mfa::MfaManager;
80pub use session_manager::SessionManager;
81pub use user_manager::{UserInfo, UserManager};
82
83pub use crate::auth::AuthResult;
85
86pub struct AuthFramework {
88 config: AuthConfig,
90
91 methods: HashMap<String, AuthMethodEnum>,
93
94 token_manager: TokenManager,
96
97 storage: Arc<dyn AuthStorage>,
99
100 permission_checker: Arc<RwLock<PermissionChecker>>,
102
103 rate_limiter: Option<RateLimiter>,
105
106 mfa_manager: MfaManager,
108
109 session_manager: SessionManager,
111
112 user_manager: UserManager,
114
115 initialized: bool,
117}
118
119impl AuthFramework {
120 pub fn new(config: AuthConfig) -> crate::errors::Result<Self> {
134 Self::try_new(config)
135 }
136
137 pub fn try_new(config: AuthConfig) -> crate::errors::Result<Self> {
147 config.validate().map_err(|e| {
149 crate::errors::AuthError::configuration(format!("Invalid configuration: {e}"))
150 })?;
151
152 let token_manager = if let Some(secret) = &config.security.secret_key {
154 if secret.len() < 32 {
155 tracing::warn!(
156 "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
157 );
158 }
159 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
160 } else if let Some(secret) = &config.secret {
161 if secret.len() < 32 {
162 tracing::warn!(
163 "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
164 );
165 }
166 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
167 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
168 if jwt_secret.len() < 32 {
169 tracing::warn!(
170 "JWT_SECRET is shorter than 32 characters. Consider using a longer secret for better security."
171 );
172 }
173 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
174 } else {
175 return Err(crate::errors::AuthError::configuration(
176 "JWT secret not set! Please set JWT_SECRET env variable or provide in config.\n\
177 For security reasons, no default secret is provided.\n\
178 Generate a secure secret with: openssl rand -base64 32",
179 ));
180 };
181
182 let storage: Arc<dyn AuthStorage> = match &config.storage {
184 #[cfg(feature = "redis-storage")]
185 crate::config::StorageConfig::Redis { url, key_prefix } => Arc::new(
186 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
187 crate::errors::AuthError::configuration(format!(
188 "Failed to create Redis storage: {e}"
189 ))
190 })?,
191 ),
192 _ => Arc::new(MemoryStorage::new()),
193 };
194
195 let rate_limiter = if config.rate_limiting.enabled {
197 Some(RateLimiter::new(
198 config.rate_limiting.max_requests,
199 config.rate_limiting.window,
200 ))
201 } else {
202 None
203 };
204
205 let mfa_manager = MfaManager::new(storage.clone());
207 let session_manager = SessionManager::new(storage.clone());
208 let user_manager = UserManager::new(storage.clone());
209
210 Ok(Self {
211 config,
212 methods: HashMap::new(),
213 token_manager,
214 storage,
215 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
216 rate_limiter,
217 mfa_manager,
218 session_manager,
219 user_manager,
220 initialized: false,
221 })
222 }
223
224 pub fn replace_storage(&mut self, storage: Arc<dyn AuthStorage>) {
229 self.storage = storage.clone();
231
232 self.mfa_manager = MfaManager::new(self.storage.clone());
234 self.session_manager = SessionManager::new(self.storage.clone());
235 self.user_manager = UserManager::new(self.storage.clone());
236 }
237
238 pub fn new_with_storage(
245 config: AuthConfig,
246 storage: Arc<dyn AuthStorage>,
247 ) -> crate::errors::Result<Self> {
248 let mut framework = Self::new(config)?;
249 framework.replace_storage(storage);
250 Ok(framework)
251 }
252
253 #[cfg(feature = "smskit")]
260 pub fn new_with_smskit_config(
261 config: AuthConfig,
262 smskit_config: crate::auth_modular::mfa::SmsKitConfig,
263 ) -> Result<Self> {
264 let mut framework = Self::new(config)?;
266
267 framework.mfa_manager = crate::auth_modular::mfa::MfaManager::new_with_smskit_config(
269 framework.storage.clone(),
270 smskit_config,
271 )?;
272
273 Ok(framework)
274 }
275
276 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
283 let name = name.into();
284 info!("Registering authentication method: {}", name);
285
286 if let Err(e) = method.validate_config() {
288 error!("Method '{}' configuration validation failed: {}", name, e);
289 return;
290 }
291
292 self.methods.insert(name, method);
293 }
294
295 pub async fn initialize(&mut self) -> Result<()> {
305 if self.initialized {
306 return Ok(());
307 }
308
309 info!("Initializing authentication framework");
310
311 {
313 let mut checker = self.permission_checker.write().await;
314 checker.create_default_roles();
315 }
316
317 self.cleanup_expired_data().await?;
319
320 self.initialized = true;
321 info!("Authentication framework initialized successfully");
322
323 Ok(())
324 }
325
326 pub async fn authenticate(
341 &self,
342 method_name: &str,
343 credential: Credential,
344 ) -> Result<AuthResult> {
345 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
346 .await
347 }
348
349 pub async fn authenticate_with_metadata(
361 &self,
362 method_name: &str,
363 credential: Credential,
364 metadata: CredentialMetadata,
365 ) -> Result<AuthResult> {
366 use std::time::Instant;
367 use tokio::time::{Duration as TokioDuration, sleep};
368
369 let start_time = Instant::now();
370
371 if !self.initialized {
372 return Err(AuthError::internal("Framework not initialized"));
373 }
374
375 let result = self
377 .authenticate_internal(method_name, credential, metadata)
378 .await;
379
380 let min_duration = TokioDuration::from_millis(100);
382 let elapsed = start_time.elapsed();
383 if elapsed < min_duration {
384 sleep(min_duration - elapsed).await;
385 }
386
387 result
388 }
389
390 async fn authenticate_internal(
392 &self,
393 method_name: &str,
394 credential: Credential,
395 metadata: CredentialMetadata,
396 ) -> Result<AuthResult> {
397 if let Some(ref rate_limiter) = self.rate_limiter {
399 let rate_key = format!(
400 "auth:{}:{}",
401 method_name,
402 metadata.client_ip.as_deref().unwrap_or("unknown")
403 );
404
405 if !rate_limiter.is_allowed(&rate_key) {
406 warn!(
407 "Rate limit exceeded for method '{}' from IP {:?}",
408 method_name, metadata.client_ip
409 );
410 return Err(AuthError::rate_limit("Too many authentication attempts"));
411 }
412 }
413
414 if method_name == "jwt" {
415 return match credential {
416 Credential::Jwt { token } | Credential::Bearer { token } => {
417 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
418 .await
419 }
420 _ => Ok(AuthResult::Failure(
421 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
422 )),
423 };
424 }
425
426 if matches!(method_name, "api_key" | "api-key") {
427 return match credential {
428 Credential::ApiKey { key } => {
429 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
430 .await
431 }
432 _ => Ok(AuthResult::Failure(
433 "API key authentication expects Credential::api_key".to_string(),
434 )),
435 };
436 }
437
438 if method_name == "oauth2" {
439 return self
440 .authenticate_oauth2_builtin(credential, &metadata)
441 .await;
442 }
443
444 let method = self.methods.get(method_name).ok_or_else(|| {
446 AuthError::auth_method(method_name, "Authentication method not found".to_string())
447 })?;
448
449 debug!(
451 "Authentication attempt with method '{}' for credential: {}",
452 method_name,
453 credential.safe_display()
454 );
455
456 let result = method.authenticate(credential, metadata.clone()).await?;
458
459 match &result {
461 MethodResult::Success(token) => {
462 info!(
463 "Authentication successful for user '{}' with method '{}'",
464 token.user_id, method_name
465 );
466
467 self.storage.store_token(token).await?;
469
470 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
472 .await;
473
474 Ok(AuthResult::Success(token.clone()))
475 }
476
477 MethodResult::MfaRequired(challenge) => {
478 info!(
479 "MFA required for user '{}' with method '{}'",
480 challenge.user_id, method_name
481 );
482
483 self.mfa_manager
485 .store_challenge((**challenge).clone())
486 .await?;
487
488 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
490 .await;
491
492 Ok(AuthResult::MfaRequired(challenge.clone()))
493 }
494
495 MethodResult::Failure { reason } => {
496 warn!(
497 "Authentication failed for method '{}': {}",
498 method_name, reason
499 );
500
501 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
503 .await;
504
505 Ok(AuthResult::Failure(reason.clone()))
506 }
507 }
508 }
509
510 async fn authenticate_jwt_builtin(
511 &self,
512 token: &str,
513 metadata: &CredentialMetadata,
514 auth_method: &str,
515 ) -> Result<AuthResult> {
516 if token.is_empty() {
517 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
518 }
519
520 let validated = if auth_method == "jwt" {
523 self.token_manager.validate_session_jwt_token(token)
524 } else {
525 self.token_manager.validate_jwt_token(token)
526 };
527 match validated {
528 Ok(claims) => {
529 let token =
530 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
531 Ok(AuthResult::Success(Box::new(token)))
532 }
533 Err(error) => {
534 if let Some(reason) = Self::credential_failure_reason(&error) {
535 Ok(AuthResult::Failure(reason))
536 } else {
537 Err(error)
538 }
539 }
540 }
541 }
542
543 async fn authenticate_api_key_builtin(
544 &self,
545 api_key: &str,
546 metadata: &CredentialMetadata,
547 auth_method: &str,
548 ) -> Result<AuthResult> {
549 if api_key.is_empty() {
550 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
551 }
552
553 match self.user_manager.validate_api_key(api_key).await {
554 Ok(user) => {
555 let scopes: Vec<String> = if user.roles.is_empty() {
556 vec!["api_user".to_string()]
557 } else {
558 user.roles.to_vec()
559 };
560 let mut token = self
561 .token_manager
562 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
563 .with_roles(user.roles)
564 .with_scopes(scopes);
565 token.metadata.issued_ip = metadata.client_ip.clone();
566 token.metadata.user_agent = metadata.user_agent.clone();
567 Ok(AuthResult::Success(Box::new(token)))
568 }
569 Err(error) => {
570 if let Some(reason) = Self::credential_failure_reason(&error) {
571 Ok(AuthResult::Failure(reason))
572 } else {
573 Err(error)
574 }
575 }
576 }
577 }
578
579 async fn authenticate_oauth2_builtin(
580 &self,
581 credential: Credential,
582 metadata: &CredentialMetadata,
583 ) -> Result<AuthResult> {
584 match credential {
585 Credential::OAuth {
586 authorization_code, ..
587 } => {
588 if authorization_code.is_empty() {
589 return Ok(AuthResult::Failure(
590 "OAuth authorization code cannot be empty".to_string(),
591 ));
592 }
593 Ok(AuthResult::Failure(
594 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
595 .to_string(),
596 ))
597 }
598 Credential::OAuthRefresh { refresh_token } => {
599 if refresh_token.is_empty() {
600 return Ok(AuthResult::Failure(
601 "OAuth refresh token cannot be empty".to_string(),
602 ));
603 }
604 Ok(AuthResult::Failure(
605 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
606 .to_string(),
607 ))
608 }
609 Credential::Jwt { token }
610 | Credential::Bearer { token }
611 | Credential::OpenIdConnect { id_token: token, .. } => {
612 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
613 }
614 _ => Ok(AuthResult::Failure(
615 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
616 .to_string(),
617 )),
618 }
619 }
620
621 fn build_validated_jwt_auth_token(
622 raw_token: &str,
623 claims: crate::tokens::JwtClaims,
624 metadata: &CredentialMetadata,
625 auth_method: &str,
626 ) -> AuthToken {
627 let crate::tokens::JwtClaims {
628 sub,
629 iss,
630 exp,
631 iat,
632 jti,
633 scope,
634 permissions,
635 roles,
636 client_id,
637 ..
638 } = claims;
639
640 let now = chrono::Utc::now();
641 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
642 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
643 .unwrap_or(now + chrono::Duration::hours(1));
644 let lifetime = (expires_at - now)
645 .to_std()
646 .unwrap_or_else(|_| std::time::Duration::from_secs(1));
647 let scopes = if scope.trim().is_empty() {
648 Vec::new()
649 } else {
650 scope.split_whitespace().map(str::to_string).collect()
651 };
652
653 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
654 .with_scopes(scopes)
655 .with_permissions(permissions.unwrap_or_default())
656 .with_roles(roles.unwrap_or_default());
657 token.token_id = jti;
658 token.subject = Some(sub);
659 token.issuer = Some(iss);
660 token.issued_at = issued_at;
661 token.expires_at = expires_at;
662 token.metadata.issued_ip = metadata.client_ip.clone();
663 token.metadata.user_agent = metadata.user_agent.clone();
664 if let Some(client_id) = client_id {
665 token.client_id = Some(client_id);
666 }
667 token
668 }
669
670 fn credential_failure_reason(error: &AuthError) -> Option<String> {
671 match error {
672 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
673 AuthError::Validation { message } => Some(message.clone()),
674 AuthError::UserNotFound => Some("User not found".to_string()),
675 _ => None,
676 }
677 }
678
679 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
686 debug!("Completing MFA for challenge '{}'", challenge.id);
687
688 let stored_challenge = self
690 .mfa_manager
691 .get_challenge(&challenge.id)
692 .await?
693 .ok_or(MfaError::ChallengeExpired)?;
694
695 if stored_challenge.is_expired() {
696 self.mfa_manager.remove_challenge(&challenge.id).await?;
697 return Err(MfaError::ChallengeExpired.into());
698 }
699
700 let is_valid = match &stored_challenge.mfa_type {
702 crate::methods::MfaType::Totp => {
703 self.mfa_manager
704 .totp
705 .verify_code(&stored_challenge.user_id, mfa_code)
706 .await?
707 }
708 crate::methods::MfaType::Sms { .. } => {
709 self.mfa_manager
710 .sms
711 .verify_code(&challenge.id, mfa_code)
712 .await?
713 }
714 crate::methods::MfaType::Email { .. } => {
715 self.mfa_manager
716 .email
717 .verify_code(&challenge.id, mfa_code)
718 .await?
719 }
720 crate::methods::MfaType::BackupCode => {
721 self.mfa_manager
722 .backup_codes
723 .verify_code(&stored_challenge.user_id, mfa_code)
724 .await?
725 }
726 _ => false,
727 };
728
729 if !is_valid {
730 return Err(MfaError::InvalidCode.into());
731 }
732
733 self.mfa_manager.remove_challenge(&challenge.id).await?;
735
736 let user_key = format!("user:{}", challenge.user_id);
738 let scopes = if let Ok(Some(data)) = self.storage.get_kv(&user_key).await {
739 serde_json::from_slice::<serde_json::Value>(&data)
740 .ok()
741 .and_then(|v| {
742 v.get("roles").and_then(|r| {
743 r.as_array().map(|arr| {
744 arr.iter()
745 .filter_map(|v| v.as_str().map(String::from))
746 .collect::<Vec<_>>()
747 })
748 })
749 })
750 .unwrap_or_else(|| vec!["user".to_string()])
751 } else {
752 vec!["user".to_string()]
753 };
754
755 let token =
757 self.token_manager
758 .create_auth_token(&challenge.user_id, scopes, "mfa", None)?;
759
760 self.storage.store_token(&token).await?;
762
763 info!(
764 "MFA completed successfully for user '{}'",
765 challenge.user_id
766 );
767
768 Ok(token)
769 }
770
771 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
778 if !self.initialized {
779 return Err(AuthError::internal("Framework not initialized"));
780 }
781
782 if !token.is_valid() {
784 return Ok(false);
785 }
786
787 self.token_manager.validate_auth_token(token)?;
789
790 if let Some(stored_token) = self.storage.get_token(&token.token_id).await? {
792 let mut updated_token = stored_token;
794 updated_token.mark_used();
795 self.storage.update_token(&updated_token).await?;
796
797 Ok(true)
798 } else {
799 Ok(false)
800 }
801 }
802
803 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
811 if !self.validate_token(token).await? {
812 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
813 }
814
815 self.user_manager.get_user_info(&token.user_id).await
816 }
817
818 pub async fn check_permission(
825 &self,
826 token: &AuthToken,
827 action: &str,
828 resource: &str,
829 ) -> Result<bool> {
830 if !self.validate_token(token).await? {
831 return Ok(false);
832 }
833
834 let permission = Permission::new(action, resource);
835 let mut checker = self.permission_checker.write().await;
836 checker.check_token_permission(token, &permission)
837 }
838
839 pub fn token_manager(&self) -> &TokenManager {
846 &self.token_manager
847 }
848
849 pub fn mfa_manager(&self) -> &MfaManager {
856 &self.mfa_manager
857 }
858
859 pub fn session_manager(&self) -> &SessionManager {
866 &self.session_manager
867 }
868
869 pub fn user_manager(&self) -> &UserManager {
876 &self.user_manager
877 }
878
879 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
886 self.mfa_manager.sms.initiate_challenge(user_id).await
887 }
888
889 pub async fn send_sms_code(&self, challenge_id: &str, phone_number: &str) -> Result<()> {
896 self.mfa_manager
897 .sms
898 .send_code(challenge_id, phone_number)
899 .await
900 }
901
902 pub async fn generate_sms_code(&self, challenge_id: &str) -> Result<String> {
909 self.mfa_manager.sms.generate_code(challenge_id).await
910 }
911
912 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
919 self.mfa_manager.sms.verify_code(challenge_id, code).await
920 }
921
922 pub async fn cleanup_expired_data(&self) -> Result<()> {
929 debug!("Cleaning up expired data");
930
931 self.storage.cleanup_expired().await?;
933
934 self.mfa_manager.cleanup_expired_challenges().await?;
936
937 self.session_manager.cleanup_expired_sessions().await?;
939
940 if let Some(ref rate_limiter) = self.rate_limiter {
942 let _ = rate_limiter.cleanup().ok();
943 }
944
945 Ok(())
946 }
947
948 pub async fn get_stats(&self) -> Result<AuthStats> {
956 let mut stats = AuthStats::default();
957
958 for method in self.methods.keys() {
959 stats.registered_methods.push(method.clone());
960 }
961
962 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
963
964 stats.tokens_issued = self.storage.count_active_sessions().await.unwrap_or(0) as u64;
966
967 Ok(stats)
968 }
969
970 async fn log_audit_event(
972 &self,
973 event_type: &str,
974 user_id: &str,
975 method: &str,
976 metadata: &CredentialMetadata,
977 ) {
978 if self.config.audit.enabled {
979 let should_log = match event_type {
980 "auth_success" => self.config.audit.log_success,
981 "auth_failure" => self.config.audit.log_failures,
982 "mfa_required" => self.config.audit.log_success,
983 _ => true,
984 };
985
986 if should_log {
987 info!(
988 target: "auth_audit",
989 event_type = event_type,
990 user_id = user_id,
991 method = method,
992 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
993 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
994 timestamp = chrono::Utc::now().to_rfc3339(),
995 "Authentication event"
996 );
997 }
998 }
999 }
1000}
1001
1002#[derive(Debug, Clone, Default)]
1004pub struct AuthStats {
1005 pub registered_methods: Vec<String>,
1007
1008 pub active_mfa_challenges: u64,
1010
1011 pub tokens_issued: u64,
1013
1014 pub auth_attempts: u64,
1016}
1017
1018#[cfg(test)]
1019mod tests {
1020 use super::*;
1021 use crate::authentication::credentials::Credential;
1022 use crate::config::{AuthConfig, SecurityConfig};
1023 use std::time::Duration;
1024
1025 async fn initialized_framework(config: AuthConfig) -> AuthFramework {
1026 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1027 framework
1028 .initialize()
1029 .await
1030 .expect("framework initialization should succeed");
1031 framework
1032 }
1033
1034 fn test_config() -> AuthConfig {
1035 AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!")
1036 }
1037
1038 #[tokio::test]
1039 async fn test_modular_framework_initialization() {
1040 let config = AuthConfig::new().security(SecurityConfig {
1041 min_password_length: 8,
1042 require_password_complexity: false,
1043 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1044 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1045 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
1046 secure_cookies: false,
1047 cookie_same_site: crate::config::CookieSameSite::Lax,
1048 csrf_protection: false,
1049 session_timeout: Duration::from_secs(3600),
1050 previous_secret_key: None,
1051 });
1052 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1053
1054 assert!(framework.initialize().await.is_ok());
1055 assert!(framework.initialized);
1056 }
1057
1058 #[tokio::test]
1059 async fn test_mfa_manager_access() {
1060 let config = AuthConfig::new().security(SecurityConfig {
1061 min_password_length: 8,
1062 require_password_complexity: false,
1063 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1064 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1065 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
1066 secure_cookies: false,
1067 cookie_same_site: crate::config::CookieSameSite::Lax,
1068 csrf_protection: false,
1069 session_timeout: Duration::from_secs(3600),
1070 previous_secret_key: None,
1071 });
1072 let framework = AuthFramework::new(config).expect("test config should be valid");
1073
1074 let _mfa_manager = framework.mfa_manager();
1076 let _session_manager = framework.session_manager();
1077 let _user_manager = framework.user_manager();
1078 }
1079
1080 #[tokio::test]
1081 async fn test_authenticate_with_metadata_enforces_minimum_duration() {
1082 let framework = initialized_framework(test_config()).await;
1083 let start = std::time::Instant::now();
1084
1085 let result = framework
1086 .authenticate_with_metadata(
1087 "oauth2",
1088 Credential::oauth_refresh(""),
1089 CredentialMetadata::new(),
1090 )
1091 .await
1092 .expect("empty refresh token should return failure, not error");
1093
1094 assert!(
1095 start.elapsed() >= std::time::Duration::from_millis(90),
1096 "timing floor should add a noticeable delay"
1097 );
1098 assert!(matches!(result, AuthResult::Failure(_)));
1099 }
1100
1101 #[tokio::test]
1102 async fn test_authenticate_oauth2_refresh_empty_returns_failure() {
1103 let framework = initialized_framework(test_config()).await;
1104
1105 let result = framework
1106 .authenticate("oauth2", Credential::oauth_refresh(""))
1107 .await
1108 .expect("empty refresh token should return failure, not error");
1109
1110 match result {
1111 AuthResult::Failure(reason) => {
1112 assert!(reason.contains("refresh token cannot be empty"));
1113 }
1114 _ => panic!("expected failure result for empty OAuth refresh token"),
1115 }
1116 }
1117
1118 #[tokio::test]
1119 async fn test_authenticate_oauth2_openid_connect_routes_to_jwt_validation() {
1120 let framework = initialized_framework(test_config()).await;
1121 let jwt = framework
1122 .token_manager()
1123 .create_jwt_token("oidc-user", vec!["openid".to_string()], None)
1124 .expect("jwt creation should succeed");
1125
1126 let result = framework
1127 .authenticate("oauth2", Credential::openid_connect(jwt))
1128 .await
1129 .expect("valid OIDC credential should authenticate");
1130
1131 match result {
1132 AuthResult::Success(token) => {
1133 assert_eq!(token.user_id, "oidc-user");
1134 assert_eq!(token.auth_method, "oauth2");
1135 }
1136 _ => panic!("expected success result for OpenID Connect credential"),
1137 }
1138 }
1139
1140 #[tokio::test]
1141 async fn test_authenticate_oauth2_unsupported_credential_returns_failure() {
1142 let framework = initialized_framework(test_config()).await;
1143
1144 let result = framework
1145 .authenticate("oauth2", Credential::password("alice", "secret"))
1146 .await
1147 .expect("unsupported credential should return failure, not error");
1148
1149 match result {
1150 AuthResult::Failure(reason) => {
1151 assert!(reason.contains("OAuth2 authentication expects"));
1152 }
1153 _ => panic!("expected failure result for unsupported OAuth2 credential"),
1154 }
1155 }
1156
1157 #[tokio::test]
1158 async fn test_rate_limiting_without_client_ip_uses_shared_unknown_bucket() {
1159 let config = AuthConfig::new()
1160 .secret("test_secret_key_32_bytes_long!!!!")
1161 .rate_limiting(crate::config::RateLimitConfig {
1162 enabled: true,
1163 max_requests: 1,
1164 window: Duration::from_secs(60),
1165 burst: 0,
1166 });
1167 let framework = initialized_framework(config).await;
1168
1169 let first = framework
1170 .authenticate_with_metadata(
1171 "oauth2",
1172 Credential::oauth_code("first-code"),
1173 CredentialMetadata::new(),
1174 )
1175 .await
1176 .expect("first request should pass rate limiting");
1177 assert!(matches!(first, AuthResult::Failure(_)));
1178
1179 let second = framework
1180 .authenticate_with_metadata(
1181 "oauth2",
1182 Credential::oauth_code("second-code"),
1183 CredentialMetadata::new(),
1184 )
1185 .await;
1186 assert!(second.is_err(), "second request should be rate limited");
1187 assert!(
1188 second
1189 .unwrap_err()
1190 .to_string()
1191 .contains("Too many authentication attempts")
1192 );
1193 }
1194
1195 #[tokio::test]
1196 async fn test_complete_mfa_missing_challenge_returns_expired_error() {
1197 let framework = initialized_framework(test_config()).await;
1198 let challenge = MfaChallenge::new(
1199 crate::methods::MfaType::BackupCode,
1200 "user-123",
1201 Duration::from_secs(60),
1202 );
1203
1204 let result = framework.complete_mfa(challenge, "123456").await;
1205 assert!(result.is_err());
1206 assert!(result.unwrap_err().to_string().contains("expired"));
1207 }
1208
1209 #[tokio::test]
1210 async fn test_complete_mfa_expired_challenge_is_removed() {
1211 let framework = initialized_framework(test_config()).await;
1212 let mut challenge = MfaChallenge::new(
1213 crate::methods::MfaType::BackupCode,
1214 "user-123",
1215 Duration::from_secs(60),
1216 );
1217 challenge.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1218 framework
1219 .mfa_manager
1220 .store_challenge(challenge.clone())
1221 .await
1222 .expect("storing challenge should succeed");
1223
1224 let result = framework.complete_mfa(challenge.clone(), "123456").await;
1225 assert!(result.is_err());
1226 assert!(result.unwrap_err().to_string().contains("expired"));
1227 assert!(
1228 framework
1229 .mfa_manager
1230 .get_challenge(&challenge.id)
1231 .await
1232 .expect("challenge lookup should succeed")
1233 .is_none()
1234 );
1235 }
1236
1237 #[tokio::test]
1238 async fn test_validate_token_returns_false_for_expired_token() {
1239 let framework = initialized_framework(test_config()).await;
1240 let mut token = framework
1241 .token_manager()
1242 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1243 .expect("token creation should succeed");
1244 token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1245
1246 let valid = framework
1247 .validate_token(&token)
1248 .await
1249 .expect("expired token should return false, not error");
1250 assert!(!valid);
1251 }
1252
1253 #[tokio::test]
1254 async fn test_validate_token_returns_false_when_not_in_storage() {
1255 let framework = initialized_framework(test_config()).await;
1256 let token = framework
1257 .token_manager()
1258 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1259 .expect("token creation should succeed");
1260
1261 let valid = framework
1262 .validate_token(&token)
1263 .await
1264 .expect("missing stored token should return false, not error");
1265 assert!(!valid);
1266 }
1267}