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 {
191 #[cfg(feature = "redis-storage")]
192 crate::config::StorageConfig::Redis { url, key_prefix } => {
193 let redis: Arc<dyn AuthStorage> = Arc::new(
194 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
195 crate::errors::AuthError::configuration(format!(
196 "Failed to create Redis storage: {e}"
197 ))
198 })?,
199 );
200 crate::storage::factory::wrap_with_encryption_if_enabled(
201 redis,
202 &config.storage_encryption,
203 )?
204 }
205 _ => Arc::new(MemoryStorage::new()),
206 };
207
208 let rate_limiter = if config.rate_limiting.enabled {
210 Some(RateLimiter::new(
211 config.rate_limiting.max_requests,
212 config.rate_limiting.window,
213 ))
214 } else {
215 None
216 };
217
218 let mfa_manager = MfaManager::new(storage.clone());
220 let session_manager = SessionManager::new(storage.clone());
221 let user_manager = UserManager::new(
222 storage.clone(),
223 config.security.password_hash_algorithm.clone(),
224 );
225
226 Ok(Self {
227 config,
228 methods: HashMap::new(),
229 token_manager,
230 storage,
231 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
232 rate_limiter,
233 mfa_manager,
234 session_manager,
235 user_manager,
236 initialized: false,
237 })
238 }
239
240 pub fn replace_storage(&mut self, storage: Arc<dyn AuthStorage>) {
245 self.storage = storage.clone();
247
248 self.mfa_manager = MfaManager::new(self.storage.clone());
250 self.session_manager = SessionManager::new(self.storage.clone());
251 self.user_manager = UserManager::new(
252 self.storage.clone(),
253 self.config.security.password_hash_algorithm.clone(),
254 );
255 }
256
257 pub fn new_with_storage(
264 config: AuthConfig,
265 storage: Arc<dyn AuthStorage>,
266 ) -> crate::errors::Result<Self> {
267 crate::storage::factory::check_overridden_storage(&storage, &config.storage_encryption)?;
268 let mut framework = Self::new(config)?;
269 framework.replace_storage(storage);
270 Ok(framework)
271 }
272
273 #[cfg(feature = "smskit")]
280 pub fn new_with_smskit_config(
281 config: AuthConfig,
282 smskit_config: crate::auth_modular::mfa::SmsKitConfig,
283 ) -> Result<Self> {
284 let mut framework = Self::new(config)?;
286
287 framework.mfa_manager = crate::auth_modular::mfa::MfaManager::new_with_smskit_config(
289 framework.storage.clone(),
290 smskit_config,
291 )?;
292
293 Ok(framework)
294 }
295
296 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
303 let name = name.into();
304 info!("Registering authentication method: {}", name);
305
306 if let Err(e) = method.validate_config() {
308 error!("Method '{}' configuration validation failed: {}", name, e);
309 return;
310 }
311
312 self.methods.insert(name, method);
313 }
314
315 pub async fn initialize(&mut self) -> Result<()> {
325 if self.initialized {
326 return Ok(());
327 }
328
329 info!("Initializing authentication framework");
330
331 {
333 let mut checker = self.permission_checker.write().await;
334 checker.create_default_roles();
335 }
336
337 self.cleanup_expired_data().await?;
339
340 self.initialized = true;
341 info!("Authentication framework initialized successfully");
342
343 Ok(())
344 }
345
346 pub async fn authenticate(
361 &self,
362 method_name: &str,
363 credential: Credential,
364 ) -> Result<AuthResult> {
365 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
366 .await
367 }
368
369 pub async fn authenticate_with_metadata(
381 &self,
382 method_name: &str,
383 credential: Credential,
384 metadata: CredentialMetadata,
385 ) -> Result<AuthResult> {
386 use std::time::Instant;
387 use tokio::time::{Duration as TokioDuration, sleep};
388
389 let start_time = Instant::now();
390
391 if !self.initialized {
392 return Err(AuthError::internal("Framework not initialized"));
393 }
394
395 let result = self
397 .authenticate_internal(method_name, credential, metadata)
398 .await;
399
400 let min_duration = TokioDuration::from_millis(100);
402 let elapsed = start_time.elapsed();
403 if elapsed < min_duration {
404 sleep(min_duration - elapsed).await;
405 }
406
407 result
408 }
409
410 async fn authenticate_internal(
412 &self,
413 method_name: &str,
414 credential: Credential,
415 metadata: CredentialMetadata,
416 ) -> Result<AuthResult> {
417 if let Some(ref rate_limiter) = self.rate_limiter {
419 let rate_key = format!(
420 "auth:{}:{}",
421 method_name,
422 metadata.client_ip.as_deref().unwrap_or("unknown")
423 );
424
425 if !rate_limiter.is_allowed(&rate_key) {
426 warn!(
427 "Rate limit exceeded for method '{}' from IP {:?}",
428 method_name, metadata.client_ip
429 );
430 return Err(AuthError::rate_limit("Too many authentication attempts"));
431 }
432 }
433
434 if method_name == "jwt" {
435 return match credential {
436 Credential::Jwt { token } | Credential::Bearer { token } => {
437 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
438 .await
439 }
440 _ => Ok(AuthResult::Failure(
441 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
442 )),
443 };
444 }
445
446 if matches!(method_name, "api_key" | "api-key") {
447 return match credential {
448 Credential::ApiKey { key } => {
449 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
450 .await
451 }
452 _ => Ok(AuthResult::Failure(
453 "API key authentication expects Credential::api_key".to_string(),
454 )),
455 };
456 }
457
458 if method_name == "oauth2" {
459 return self
460 .authenticate_oauth2_builtin(credential, &metadata)
461 .await;
462 }
463
464 let method = self.methods.get(method_name).ok_or_else(|| {
466 AuthError::auth_method(method_name, "Authentication method not found".to_string())
467 })?;
468
469 debug!(
471 "Authentication attempt with method '{}' for credential: {}",
472 method_name,
473 credential.safe_display()
474 );
475
476 let result = method.authenticate(credential, metadata.clone()).await?;
478
479 match &result {
481 MethodResult::Success(token) => {
482 info!(
483 "Authentication successful for user '{}' with method '{}'",
484 token.user_id, method_name
485 );
486
487 self.storage.store_token(token).await?;
489
490 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
492 .await;
493
494 Ok(AuthResult::Success(token.clone()))
495 }
496
497 MethodResult::MfaRequired(challenge) => {
498 info!(
499 "MFA required for user '{}' with method '{}'",
500 challenge.user_id, method_name
501 );
502
503 self.mfa_manager
505 .store_challenge((**challenge).clone())
506 .await?;
507
508 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
510 .await;
511
512 Ok(AuthResult::MfaRequired(challenge.clone()))
513 }
514
515 MethodResult::Failure { reason } => {
516 warn!(
517 "Authentication failed for method '{}': {}",
518 method_name, reason
519 );
520
521 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
523 .await;
524
525 Ok(AuthResult::Failure(reason.clone()))
526 }
527 }
528 }
529
530 async fn authenticate_jwt_builtin(
531 &self,
532 token: &str,
533 metadata: &CredentialMetadata,
534 auth_method: &str,
535 ) -> Result<AuthResult> {
536 if token.is_empty() {
537 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
538 }
539
540 match self.token_manager.validate_jwt_token(token) {
541 Ok(claims) => {
542 let token =
543 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
544 Ok(AuthResult::Success(Box::new(token)))
545 }
546 Err(error) => {
547 if let Some(reason) = Self::credential_failure_reason(&error) {
548 Ok(AuthResult::Failure(reason))
549 } else {
550 Err(error)
551 }
552 }
553 }
554 }
555
556 async fn authenticate_api_key_builtin(
557 &self,
558 api_key: &str,
559 metadata: &CredentialMetadata,
560 auth_method: &str,
561 ) -> Result<AuthResult> {
562 if api_key.is_empty() {
563 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
564 }
565
566 match self.user_manager.validate_api_key(api_key).await {
567 Ok(user) => {
568 let scopes: Vec<String> = if user.roles.is_empty() {
569 vec!["api_user".to_string()]
570 } else {
571 user.roles.to_vec()
572 };
573 let mut token = self
574 .token_manager
575 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
576 .with_roles(user.roles)
577 .with_scopes(scopes);
578 token.metadata.issued_ip = metadata.client_ip.clone();
579 token.metadata.user_agent = metadata.user_agent.clone();
580 Ok(AuthResult::Success(Box::new(token)))
581 }
582 Err(error) => {
583 if let Some(reason) = Self::credential_failure_reason(&error) {
584 Ok(AuthResult::Failure(reason))
585 } else {
586 Err(error)
587 }
588 }
589 }
590 }
591
592 async fn authenticate_oauth2_builtin(
593 &self,
594 credential: Credential,
595 metadata: &CredentialMetadata,
596 ) -> Result<AuthResult> {
597 match credential {
598 Credential::OAuth {
599 authorization_code, ..
600 } => {
601 if authorization_code.is_empty() {
602 return Ok(AuthResult::Failure(
603 "OAuth authorization code cannot be empty".to_string(),
604 ));
605 }
606 Ok(AuthResult::Failure(
607 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
608 .to_string(),
609 ))
610 }
611 Credential::OAuthRefresh { refresh_token } => {
612 if refresh_token.is_empty() {
613 return Ok(AuthResult::Failure(
614 "OAuth refresh token cannot be empty".to_string(),
615 ));
616 }
617 Ok(AuthResult::Failure(
618 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
619 .to_string(),
620 ))
621 }
622 Credential::Jwt { token }
623 | Credential::Bearer { token }
624 | Credential::OpenIdConnect { id_token: token, .. } => {
625 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
626 }
627 _ => Ok(AuthResult::Failure(
628 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
629 .to_string(),
630 )),
631 }
632 }
633
634 fn build_validated_jwt_auth_token(
635 raw_token: &str,
636 claims: crate::tokens::JwtClaims,
637 metadata: &CredentialMetadata,
638 auth_method: &str,
639 ) -> AuthToken {
640 let crate::tokens::JwtClaims {
641 sub,
642 iss,
643 exp,
644 iat,
645 jti,
646 scope,
647 permissions,
648 roles,
649 client_id,
650 ..
651 } = claims;
652
653 let now = chrono::Utc::now();
654 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
655 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
656 .unwrap_or(now + chrono::Duration::hours(1));
657 let lifetime = (expires_at - now)
658 .to_std()
659 .unwrap_or_else(|_| std::time::Duration::from_secs(1));
660 let scopes = if scope.trim().is_empty() {
661 Vec::new()
662 } else {
663 scope.split_whitespace().map(str::to_string).collect()
664 };
665
666 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
667 .with_scopes(scopes)
668 .with_permissions(permissions.unwrap_or_default())
669 .with_roles(roles.unwrap_or_default());
670 token.token_id = jti;
671 token.subject = Some(sub);
672 token.issuer = Some(iss);
673 token.issued_at = issued_at;
674 token.expires_at = expires_at;
675 token.metadata.issued_ip = metadata.client_ip.clone();
676 token.metadata.user_agent = metadata.user_agent.clone();
677 if let Some(client_id) = client_id {
678 token.client_id = Some(client_id);
679 }
680 token
681 }
682
683 fn credential_failure_reason(error: &AuthError) -> Option<String> {
684 match error {
685 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
686 AuthError::Validation { message } => Some(message.clone()),
687 AuthError::UserNotFound => Some("User not found".to_string()),
688 _ => None,
689 }
690 }
691
692 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
699 debug!("Completing MFA for challenge '{}'", challenge.id);
700
701 let stored_challenge = self
703 .mfa_manager
704 .get_challenge(&challenge.id)
705 .await?
706 .ok_or(MfaError::ChallengeExpired)?;
707
708 if stored_challenge.is_expired() {
709 self.mfa_manager.remove_challenge(&challenge.id).await?;
710 return Err(MfaError::ChallengeExpired.into());
711 }
712
713 let is_valid = match &stored_challenge.mfa_type {
715 crate::methods::MfaType::Totp => {
716 self.mfa_manager
717 .totp
718 .verify_code(&stored_challenge.user_id, mfa_code)
719 .await?
720 }
721 crate::methods::MfaType::Sms { .. } => {
722 self.mfa_manager
723 .sms
724 .verify_code(&challenge.id, mfa_code)
725 .await?
726 }
727 crate::methods::MfaType::Email { .. } => {
728 self.mfa_manager
729 .email
730 .verify_code(&challenge.id, mfa_code)
731 .await?
732 }
733 crate::methods::MfaType::BackupCode => {
734 self.mfa_manager
735 .backup_codes
736 .verify_code(&stored_challenge.user_id, mfa_code)
737 .await?
738 }
739 _ => false,
740 };
741
742 if !is_valid {
743 return Err(MfaError::InvalidCode.into());
744 }
745
746 self.mfa_manager.remove_challenge(&challenge.id).await?;
748
749 let user_key = format!("user:{}", challenge.user_id);
751 let scopes = if let Ok(Some(data)) = self.storage.get_kv(&user_key).await {
752 serde_json::from_slice::<serde_json::Value>(&data)
753 .ok()
754 .and_then(|v| {
755 v.get("roles").and_then(|r| {
756 r.as_array().map(|arr| {
757 arr.iter()
758 .filter_map(|v| v.as_str().map(String::from))
759 .collect::<Vec<_>>()
760 })
761 })
762 })
763 .unwrap_or_else(|| vec!["user".to_string()])
764 } else {
765 vec!["user".to_string()]
766 };
767
768 let token =
770 self.token_manager
771 .create_auth_token(&challenge.user_id, scopes, "mfa", None)?;
772
773 self.storage.store_token(&token).await?;
775
776 info!(
777 "MFA completed successfully for user '{}'",
778 challenge.user_id
779 );
780
781 Ok(token)
782 }
783
784 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
791 if !self.initialized {
792 return Err(AuthError::internal("Framework not initialized"));
793 }
794
795 if !token.is_valid() {
797 return Ok(false);
798 }
799
800 self.token_manager.validate_auth_token(token)?;
802
803 if let Some(stored_token) = self.storage.get_token(&token.token_id).await? {
805 let mut updated_token = stored_token;
807 updated_token.mark_used();
808 self.storage.update_token(&updated_token).await?;
809
810 Ok(true)
811 } else {
812 Ok(false)
813 }
814 }
815
816 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
824 if !self.validate_token(token).await? {
825 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
826 }
827
828 self.user_manager.get_user_info(&token.user_id).await
829 }
830
831 pub async fn check_permission(
838 &self,
839 token: &AuthToken,
840 action: &str,
841 resource: &str,
842 ) -> Result<bool> {
843 if !self.validate_token(token).await? {
844 return Ok(false);
845 }
846
847 let permission = Permission::new(action, resource);
848 let mut checker = self.permission_checker.write().await;
849 checker.check_token_permission(token, &permission)
850 }
851
852 pub fn token_manager(&self) -> &TokenManager {
859 &self.token_manager
860 }
861
862 pub fn mfa_manager(&self) -> &MfaManager {
869 &self.mfa_manager
870 }
871
872 pub fn session_manager(&self) -> &SessionManager {
879 &self.session_manager
880 }
881
882 pub fn user_manager(&self) -> &UserManager {
889 &self.user_manager
890 }
891
892 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
899 self.mfa_manager.sms.initiate_challenge(user_id).await
900 }
901
902 pub async fn send_sms_code(&self, challenge_id: &str, phone_number: &str) -> Result<()> {
909 self.mfa_manager
910 .sms
911 .send_code(challenge_id, phone_number)
912 .await
913 }
914
915 pub async fn generate_sms_code(&self, challenge_id: &str) -> Result<String> {
922 self.mfa_manager.sms.generate_code(challenge_id).await
923 }
924
925 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
932 self.mfa_manager.sms.verify_code(challenge_id, code).await
933 }
934
935 pub async fn cleanup_expired_data(&self) -> Result<()> {
942 debug!("Cleaning up expired data");
943
944 self.storage.cleanup_expired().await?;
946
947 self.mfa_manager.cleanup_expired_challenges().await?;
949
950 self.session_manager.cleanup_expired_sessions().await?;
952
953 if let Some(ref rate_limiter) = self.rate_limiter {
955 let _ = rate_limiter.cleanup().ok();
956 }
957
958 Ok(())
959 }
960
961 pub async fn get_stats(&self) -> Result<AuthStats> {
969 let mut stats = AuthStats::default();
970
971 for method in self.methods.keys() {
972 stats.registered_methods.push(method.clone());
973 }
974
975 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
976
977 stats.tokens_issued = self.storage.count_active_sessions().await.unwrap_or(0) as u64;
979
980 Ok(stats)
981 }
982
983 async fn log_audit_event(
985 &self,
986 event_type: &str,
987 user_id: &str,
988 method: &str,
989 metadata: &CredentialMetadata,
990 ) {
991 if self.config.audit.enabled {
992 let should_log = match event_type {
993 "auth_success" => self.config.audit.log_success,
994 "auth_failure" => self.config.audit.log_failures,
995 "mfa_required" => self.config.audit.log_success,
996 _ => true,
997 };
998
999 if should_log {
1000 info!(
1001 target: "auth_audit",
1002 event_type = event_type,
1003 user_id = user_id,
1004 method = method,
1005 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1006 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1007 timestamp = chrono::Utc::now().to_rfc3339(),
1008 "Authentication event"
1009 );
1010 }
1011 }
1012 }
1013}
1014
1015#[derive(Debug, Clone, Default)]
1017pub struct AuthStats {
1018 pub registered_methods: Vec<String>,
1020
1021 pub active_mfa_challenges: u64,
1023
1024 pub tokens_issued: u64,
1026
1027 pub auth_attempts: u64,
1029}
1030
1031#[cfg(test)]
1032mod tests {
1033 use super::*;
1034 use crate::authentication::credentials::Credential;
1035 use crate::config::{AuthConfig, SecurityConfig};
1036 use std::time::Duration;
1037
1038 async fn initialized_framework(config: AuthConfig) -> AuthFramework {
1039 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1040 framework
1041 .initialize()
1042 .await
1043 .expect("framework initialization should succeed");
1044 framework
1045 }
1046
1047 fn test_config() -> AuthConfig {
1048 AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!")
1049 }
1050
1051 #[tokio::test]
1052 async fn test_modular_framework_initialization() {
1053 let config = AuthConfig::new().security(SecurityConfig {
1054 min_password_length: 8,
1055 require_password_complexity: false,
1056 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1057 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1058 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1059 secure_cookies: false,
1060 cookie_same_site: crate::config::CookieSameSite::Lax,
1061 csrf_protection: false,
1062 session_timeout: Duration::from_secs(3600),
1063 previous_secret_key: None,
1064 });
1065 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1066
1067 assert!(framework.initialize().await.is_ok());
1068 assert!(framework.initialized);
1069 }
1070
1071 #[tokio::test]
1072 async fn test_mfa_manager_access() {
1073 let config = AuthConfig::new().security(SecurityConfig {
1074 min_password_length: 8,
1075 require_password_complexity: false,
1076 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1077 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1078 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1079 secure_cookies: false,
1080 cookie_same_site: crate::config::CookieSameSite::Lax,
1081 csrf_protection: false,
1082 session_timeout: Duration::from_secs(3600),
1083 previous_secret_key: None,
1084 });
1085 let framework = AuthFramework::new(config).expect("test config should be valid");
1086
1087 let _mfa_manager = framework.mfa_manager();
1089 let _session_manager = framework.session_manager();
1090 let _user_manager = framework.user_manager();
1091 }
1092
1093 #[tokio::test]
1094 async fn test_authenticate_with_metadata_enforces_minimum_duration() {
1095 let framework = initialized_framework(test_config()).await;
1096 let start = std::time::Instant::now();
1097
1098 let result = framework
1099 .authenticate_with_metadata(
1100 "oauth2",
1101 Credential::oauth_refresh(""),
1102 CredentialMetadata::new(),
1103 )
1104 .await
1105 .expect("empty refresh token should return failure, not error");
1106
1107 assert!(
1108 start.elapsed() >= std::time::Duration::from_millis(90),
1109 "timing floor should add a noticeable delay"
1110 );
1111 assert!(matches!(result, AuthResult::Failure(_)));
1112 }
1113
1114 #[tokio::test]
1115 async fn test_authenticate_oauth2_refresh_empty_returns_failure() {
1116 let framework = initialized_framework(test_config()).await;
1117
1118 let result = framework
1119 .authenticate("oauth2", Credential::oauth_refresh(""))
1120 .await
1121 .expect("empty refresh token should return failure, not error");
1122
1123 match result {
1124 AuthResult::Failure(reason) => {
1125 assert!(reason.contains("refresh token cannot be empty"));
1126 }
1127 _ => panic!("expected failure result for empty OAuth refresh token"),
1128 }
1129 }
1130
1131 #[tokio::test]
1132 async fn test_authenticate_oauth2_openid_connect_routes_to_jwt_validation() {
1133 let framework = initialized_framework(test_config()).await;
1134 let jwt = framework
1135 .token_manager()
1136 .create_jwt_token("oidc-user", vec!["openid".to_string()], None)
1137 .expect("jwt creation should succeed");
1138
1139 let result = framework
1140 .authenticate("oauth2", Credential::openid_connect(jwt))
1141 .await
1142 .expect("valid OIDC credential should authenticate");
1143
1144 match result {
1145 AuthResult::Success(token) => {
1146 assert_eq!(token.user_id, "oidc-user");
1147 assert_eq!(token.auth_method, "oauth2");
1148 }
1149 _ => panic!("expected success result for OpenID Connect credential"),
1150 }
1151 }
1152
1153 #[tokio::test]
1154 async fn test_authenticate_oauth2_unsupported_credential_returns_failure() {
1155 let framework = initialized_framework(test_config()).await;
1156
1157 let result = framework
1158 .authenticate("oauth2", Credential::password("alice", "secret"))
1159 .await
1160 .expect("unsupported credential should return failure, not error");
1161
1162 match result {
1163 AuthResult::Failure(reason) => {
1164 assert!(reason.contains("OAuth2 authentication expects"));
1165 }
1166 _ => panic!("expected failure result for unsupported OAuth2 credential"),
1167 }
1168 }
1169
1170 #[tokio::test]
1171 async fn test_rate_limiting_without_client_ip_uses_shared_unknown_bucket() {
1172 let config = AuthConfig::new()
1173 .secret("test_secret_key_32_bytes_long!!!!")
1174 .rate_limiting(crate::config::RateLimitConfig {
1175 enabled: true,
1176 max_requests: 1,
1177 window: Duration::from_secs(60),
1178 burst: 0,
1179 });
1180 let framework = initialized_framework(config).await;
1181
1182 let first = framework
1183 .authenticate_with_metadata(
1184 "oauth2",
1185 Credential::oauth_code("first-code"),
1186 CredentialMetadata::new(),
1187 )
1188 .await
1189 .expect("first request should pass rate limiting");
1190 assert!(matches!(first, AuthResult::Failure(_)));
1191
1192 let second = framework
1193 .authenticate_with_metadata(
1194 "oauth2",
1195 Credential::oauth_code("second-code"),
1196 CredentialMetadata::new(),
1197 )
1198 .await;
1199 assert!(second.is_err(), "second request should be rate limited");
1200 assert!(
1201 second
1202 .unwrap_err()
1203 .to_string()
1204 .contains("Too many authentication attempts")
1205 );
1206 }
1207
1208 #[tokio::test]
1209 async fn test_complete_mfa_missing_challenge_returns_expired_error() {
1210 let framework = initialized_framework(test_config()).await;
1211 let challenge = MfaChallenge::new(
1212 crate::methods::MfaType::BackupCode,
1213 "user-123",
1214 Duration::from_secs(60),
1215 );
1216
1217 let result = framework.complete_mfa(challenge, "123456").await;
1218 assert!(result.is_err());
1219 assert!(result.unwrap_err().to_string().contains("expired"));
1220 }
1221
1222 #[tokio::test]
1223 async fn test_complete_mfa_expired_challenge_is_removed() {
1224 let framework = initialized_framework(test_config()).await;
1225 let mut challenge = MfaChallenge::new(
1226 crate::methods::MfaType::BackupCode,
1227 "user-123",
1228 Duration::from_secs(60),
1229 );
1230 challenge.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1231 framework
1232 .mfa_manager
1233 .store_challenge(challenge.clone())
1234 .await
1235 .expect("storing challenge should succeed");
1236
1237 let result = framework.complete_mfa(challenge.clone(), "123456").await;
1238 assert!(result.is_err());
1239 assert!(result.unwrap_err().to_string().contains("expired"));
1240 assert!(
1241 framework
1242 .mfa_manager
1243 .get_challenge(&challenge.id)
1244 .await
1245 .expect("challenge lookup should succeed")
1246 .is_none()
1247 );
1248 }
1249
1250 #[tokio::test]
1251 async fn test_validate_token_returns_false_for_expired_token() {
1252 let framework = initialized_framework(test_config()).await;
1253 let mut token = framework
1254 .token_manager()
1255 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1256 .expect("token creation should succeed");
1257 token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1258
1259 let valid = framework
1260 .validate_token(&token)
1261 .await
1262 .expect("expired token should return false, not error");
1263 assert!(!valid);
1264 }
1265
1266 #[tokio::test]
1267 async fn test_validate_token_returns_false_when_not_in_storage() {
1268 let framework = initialized_framework(test_config()).await;
1269 let token = framework
1270 .token_manager()
1271 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1272 .expect("token creation should succeed");
1273
1274 let valid = framework
1275 .validate_token(&token)
1276 .await
1277 .expect("missing stored token should return false, not error");
1278 assert!(!valid);
1279 }
1280
1281 #[cfg(feature = "redis-storage")]
1289 #[test]
1290 fn redis_construction_fails_closed_without_an_encryption_key() {
1291 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
1292 unsafe {
1295 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
1296 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
1297 }
1298
1299 let mut config = test_config();
1300 config.storage = crate::config::StorageConfig::Redis {
1301 url: "redis://127.0.0.1:1/".to_string(),
1302 key_prefix: "test:".to_string(),
1303 };
1304 let result = AuthFramework::new(config);
1307 assert!(
1308 result.is_err(),
1309 "constructing this modular framework with Redis storage and no encryption key \
1310 configured must fail closed, not silently build unwrapped (unencrypted) storage"
1311 );
1312 }
1313}