1pub mod authorization_manager;
62pub mod mfa;
63pub mod session_manager;
64pub mod user_manager;
65
66use crate::authentication::credentials::{Credential, CredentialMetadata};
67use crate::config::AuthConfig;
68use crate::errors::{AuthError, MfaError, Result};
69use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
70use crate::permissions::{Permission, PermissionChecker};
71use crate::storage::{AuthStorage, MemoryStorage};
72use crate::tokens::{AuthToken, TokenManager};
73use crate::utils::rate_limit::RateLimiter;
74use std::collections::HashMap;
75use std::sync::Arc;
76use tokio::sync::RwLock;
77use tracing::{debug, error, info, warn};
78
79pub use authorization_manager::AuthorizationManager;
80pub use mfa::MfaManager;
81pub use session_manager::SessionManager;
82pub use user_manager::{UserInfo, UserManager};
83
84pub use crate::auth::AuthResult;
86
87pub struct AuthFramework {
89 config: AuthConfig,
91
92 methods: HashMap<String, AuthMethodEnum>,
94
95 token_manager: TokenManager,
97
98 storage: Arc<dyn AuthStorage>,
100
101 permission_checker: Arc<RwLock<PermissionChecker>>,
103
104 rate_limiter: Option<RateLimiter>,
106
107 mfa_manager: MfaManager,
109
110 session_manager: SessionManager,
112
113 user_manager: UserManager,
115
116 initialized: bool,
118}
119
120impl AuthFramework {
121 pub fn new(config: AuthConfig) -> crate::errors::Result<Self> {
135 Self::try_new(config)
136 }
137
138 pub fn try_new(config: AuthConfig) -> crate::errors::Result<Self> {
148 config.validate().map_err(|e| {
150 crate::errors::AuthError::configuration(format!("Invalid configuration: {e}"))
151 })?;
152
153 let token_manager = if let Some(secret) = &config.security.secret_key {
155 if secret.len() < 32 {
156 tracing::warn!(
157 "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
158 );
159 }
160 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
161 } else if let Some(secret) = &config.secret {
162 if secret.len() < 32 {
163 tracing::warn!(
164 "JWT secret is shorter than 32 characters. Consider using a longer secret for better security."
165 );
166 }
167 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
168 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
169 if jwt_secret.len() < 32 {
170 tracing::warn!(
171 "JWT_SECRET is shorter than 32 characters. Consider using a longer secret for better security."
172 );
173 }
174 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
175 } else {
176 return Err(crate::errors::AuthError::configuration(
177 "JWT secret not set! Please set JWT_SECRET env variable or provide in config.\n\
178 For security reasons, no default secret is provided.\n\
179 Generate a secure secret with: openssl rand -base64 32",
180 ));
181 };
182
183 let storage: Arc<dyn AuthStorage> = match &config.storage {
192 #[cfg(feature = "redis-storage")]
193 crate::config::StorageConfig::Redis { url, key_prefix } => {
194 let redis: Arc<dyn AuthStorage> = Arc::new(
195 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
196 crate::errors::AuthError::configuration(format!(
197 "Failed to create Redis storage: {e}"
198 ))
199 })?,
200 );
201 crate::storage::factory::wrap_with_encryption_if_enabled(
202 redis,
203 &config.storage_encryption,
204 )?
205 }
206 _ => Arc::new(MemoryStorage::new()),
207 };
208
209 let rate_limiter = if config.rate_limiting.enabled {
211 Some(RateLimiter::new(
212 config.rate_limiting.max_requests,
213 config.rate_limiting.window,
214 ))
215 } else {
216 None
217 };
218
219 let mfa_manager = MfaManager::new(storage.clone());
221 let session_manager = SessionManager::new(storage.clone());
222 let user_manager = UserManager::new(
223 storage.clone(),
224 config.security.password_hash_algorithm.clone(),
225 );
226
227 Ok(Self {
228 config,
229 methods: HashMap::new(),
230 token_manager,
231 storage,
232 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
233 rate_limiter,
234 mfa_manager,
235 session_manager,
236 user_manager,
237 initialized: false,
238 })
239 }
240
241 pub fn replace_storage(&mut self, storage: Arc<dyn AuthStorage>) {
246 self.storage = storage.clone();
248
249 self.mfa_manager = MfaManager::new(self.storage.clone());
251 self.session_manager = SessionManager::new(self.storage.clone());
252 self.user_manager = UserManager::new(
253 self.storage.clone(),
254 self.config.security.password_hash_algorithm.clone(),
255 );
256 }
257
258 pub fn new_with_storage(
265 config: AuthConfig,
266 storage: Arc<dyn AuthStorage>,
267 ) -> crate::errors::Result<Self> {
268 crate::storage::factory::check_overridden_storage(&storage, &config.storage_encryption)?;
269 let mut framework = Self::new(config)?;
270 framework.replace_storage(storage);
271 Ok(framework)
272 }
273
274 #[cfg(feature = "smskit")]
281 pub fn new_with_smskit_config(
282 config: AuthConfig,
283 smskit_config: crate::auth_modular::mfa::SmsKitConfig,
284 ) -> Result<Self> {
285 let mut framework = Self::new(config)?;
287
288 framework.mfa_manager = crate::auth_modular::mfa::MfaManager::new_with_smskit_config(
290 framework.storage.clone(),
291 smskit_config,
292 )?;
293
294 Ok(framework)
295 }
296
297 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
304 let name = name.into();
305 info!("Registering authentication method: {}", name);
306
307 if let Err(e) = method.validate_config() {
309 error!("Method '{}' configuration validation failed: {}", name, e);
310 return;
311 }
312
313 self.methods.insert(name, method);
314 }
315
316 pub async fn initialize(&mut self) -> Result<()> {
326 if self.initialized {
327 return Ok(());
328 }
329
330 info!("Initializing authentication framework");
331
332 {
334 let mut checker = self.permission_checker.write().await;
335 checker.create_default_roles();
336 }
337
338 self.cleanup_expired_data().await?;
340
341 self.initialized = true;
342 info!("Authentication framework initialized successfully");
343
344 Ok(())
345 }
346
347 pub async fn authenticate(
362 &self,
363 method_name: &str,
364 credential: Credential,
365 ) -> Result<AuthResult> {
366 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
367 .await
368 }
369
370 pub async fn authenticate_with_metadata(
382 &self,
383 method_name: &str,
384 credential: Credential,
385 metadata: CredentialMetadata,
386 ) -> Result<AuthResult> {
387 use std::time::Instant;
388 use tokio::time::{Duration as TokioDuration, sleep};
389
390 let start_time = Instant::now();
391
392 if !self.initialized {
393 return Err(AuthError::internal("Framework not initialized"));
394 }
395
396 let result = self
398 .authenticate_internal(method_name, credential, metadata)
399 .await;
400
401 let min_duration = TokioDuration::from_millis(100);
403 let elapsed = start_time.elapsed();
404 if elapsed < min_duration {
405 sleep(min_duration - elapsed).await;
406 }
407
408 result
409 }
410
411 async fn authenticate_internal(
413 &self,
414 method_name: &str,
415 credential: Credential,
416 metadata: CredentialMetadata,
417 ) -> Result<AuthResult> {
418 if let Some(ref rate_limiter) = self.rate_limiter {
420 let rate_key = format!(
421 "auth:{}:{}",
422 method_name,
423 metadata.client_ip.as_deref().unwrap_or("unknown")
424 );
425
426 if !rate_limiter.is_allowed(&rate_key) {
427 warn!(
428 "Rate limit exceeded for method '{}' from IP {:?}",
429 method_name, metadata.client_ip
430 );
431 return Err(AuthError::rate_limit("Too many authentication attempts"));
432 }
433 }
434
435 if method_name == "jwt" {
436 return match credential {
437 Credential::Jwt { token } | Credential::Bearer { token } => {
438 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
439 .await
440 }
441 _ => Ok(AuthResult::Failure(
442 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
443 )),
444 };
445 }
446
447 if matches!(method_name, "api_key" | "api-key") {
448 return match credential {
449 Credential::ApiKey { key } => {
450 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
451 .await
452 }
453 _ => Ok(AuthResult::Failure(
454 "API key authentication expects Credential::api_key".to_string(),
455 )),
456 };
457 }
458
459 if method_name == "oauth2" {
460 return self
461 .authenticate_oauth2_builtin(credential, &metadata)
462 .await;
463 }
464
465 let method = self.methods.get(method_name).ok_or_else(|| {
467 AuthError::auth_method(method_name, "Authentication method not found".to_string())
468 })?;
469
470 debug!(
472 "Authentication attempt with method '{}' for credential: {}",
473 method_name,
474 credential.safe_display()
475 );
476
477 let result = method.authenticate(credential, metadata.clone()).await?;
479
480 match &result {
482 MethodResult::Success(token) => {
483 info!(
484 "Authentication successful for user '{}' with method '{}'",
485 token.user_id, method_name
486 );
487
488 self.storage.store_token(token).await?;
490
491 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
493 .await;
494
495 Ok(AuthResult::Success(token.clone()))
496 }
497
498 MethodResult::MfaRequired(challenge) => {
499 info!(
500 "MFA required for user '{}' with method '{}'",
501 challenge.user_id, method_name
502 );
503
504 self.mfa_manager
506 .store_challenge((**challenge).clone())
507 .await?;
508
509 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
511 .await;
512
513 Ok(AuthResult::MfaRequired(challenge.clone()))
514 }
515
516 MethodResult::Failure { reason } => {
517 warn!(
518 "Authentication failed for method '{}': {}",
519 method_name, reason
520 );
521
522 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
524 .await;
525
526 Ok(AuthResult::Failure(reason.clone()))
527 }
528 }
529 }
530
531 async fn authenticate_jwt_builtin(
532 &self,
533 token: &str,
534 metadata: &CredentialMetadata,
535 auth_method: &str,
536 ) -> Result<AuthResult> {
537 if token.is_empty() {
538 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
539 }
540
541 match crate::auth::validate_access_jwt_with(
542 &self.token_manager,
543 self.storage.as_ref(),
544 token,
545 false,
546 false,
547 )
548 .await
549 {
550 Ok(claims) => {
551 let token =
552 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
553 Ok(AuthResult::Success(Box::new(token)))
554 }
555 Err(error) => {
556 if let Some(reason) = Self::credential_failure_reason(&error) {
557 Ok(AuthResult::Failure(reason))
558 } else {
559 Err(error)
560 }
561 }
562 }
563 }
564
565 async fn authenticate_api_key_builtin(
566 &self,
567 api_key: &str,
568 metadata: &CredentialMetadata,
569 auth_method: &str,
570 ) -> Result<AuthResult> {
571 if api_key.is_empty() {
572 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
573 }
574
575 match self.user_manager.validate_api_key(api_key).await {
576 Ok(user) => {
577 let scopes: Vec<String> = if user.roles.is_empty() {
578 vec!["api_user".to_string()]
579 } else {
580 user.roles.to_vec()
581 };
582 let mut token = self
583 .token_manager
584 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
585 .with_roles(user.roles)
586 .with_scopes(scopes);
587 token.metadata.issued_ip = metadata.client_ip.clone();
588 token.metadata.user_agent = metadata.user_agent.clone();
589 Ok(AuthResult::Success(Box::new(token)))
590 }
591 Err(error) => {
592 if let Some(reason) = Self::credential_failure_reason(&error) {
593 Ok(AuthResult::Failure(reason))
594 } else {
595 Err(error)
596 }
597 }
598 }
599 }
600
601 async fn authenticate_oauth2_builtin(
602 &self,
603 credential: Credential,
604 metadata: &CredentialMetadata,
605 ) -> Result<AuthResult> {
606 match credential {
607 Credential::OAuth {
608 authorization_code, ..
609 } => {
610 if authorization_code.is_empty() {
611 return Ok(AuthResult::Failure(
612 "OAuth authorization code cannot be empty".to_string(),
613 ));
614 }
615 Ok(AuthResult::Failure(
616 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
617 .to_string(),
618 ))
619 }
620 Credential::OAuthRefresh { refresh_token } => {
621 if refresh_token.is_empty() {
622 return Ok(AuthResult::Failure(
623 "OAuth refresh token cannot be empty".to_string(),
624 ));
625 }
626 Ok(AuthResult::Failure(
627 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
628 .to_string(),
629 ))
630 }
631 Credential::Jwt { token }
632 | Credential::Bearer { token }
633 | Credential::OpenIdConnect { id_token: token, .. } => {
634 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
635 }
636 _ => Ok(AuthResult::Failure(
637 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
638 .to_string(),
639 )),
640 }
641 }
642
643 fn build_validated_jwt_auth_token(
644 raw_token: &str,
645 claims: crate::tokens::JwtClaims,
646 metadata: &CredentialMetadata,
647 auth_method: &str,
648 ) -> AuthToken {
649 let crate::tokens::JwtClaims {
650 sub,
651 iss,
652 exp,
653 iat,
654 jti,
655 scope,
656 permissions,
657 roles,
658 client_id,
659 ..
660 } = claims;
661
662 let now = chrono::Utc::now();
663 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
664 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
665 .unwrap_or(now + chrono::Duration::hours(1));
666 let lifetime = (expires_at - now)
667 .to_std()
668 .unwrap_or_else(|_| std::time::Duration::from_secs(1));
669 let scopes = if scope.trim().is_empty() {
670 Vec::new()
671 } else {
672 scope.split_whitespace().map(str::to_string).collect()
673 };
674
675 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
676 .with_scopes(scopes)
677 .with_permissions(permissions.unwrap_or_default())
678 .with_roles(roles.unwrap_or_default());
679 token.token_id = jti;
680 token.subject = Some(sub);
681 token.issuer = Some(iss);
682 token.issued_at = issued_at;
683 token.expires_at = expires_at;
684 token.metadata.issued_ip = metadata.client_ip.clone();
685 token.metadata.user_agent = metadata.user_agent.clone();
686 if let Some(client_id) = client_id {
687 token.client_id = Some(client_id);
688 }
689 token
690 }
691
692 fn credential_failure_reason(error: &AuthError) -> Option<String> {
693 match error {
694 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
695 AuthError::Validation { message } => Some(message.clone()),
696 AuthError::UserNotFound => Some("User not found".to_string()),
697 _ => None,
698 }
699 }
700
701 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
708 debug!("Completing MFA for challenge '{}'", challenge.id);
709
710 let stored_challenge = self
712 .mfa_manager
713 .begin_attempt(&challenge.id)
714 .await?
715 .ok_or(MfaError::ChallengeExpired)?;
716
717 let is_valid = match &stored_challenge.mfa_type {
719 crate::methods::MfaType::Totp => {
720 self.mfa_manager
721 .totp
722 .verify_code(&stored_challenge.user_id, mfa_code)
723 .await?
724 }
725 crate::methods::MfaType::Sms { .. } => {
726 self.mfa_manager
727 .sms
728 .verify_code(&challenge.id, mfa_code)
729 .await?
730 }
731 crate::methods::MfaType::Email { .. } => {
732 self.mfa_manager
733 .email
734 .verify_code(&challenge.id, mfa_code)
735 .await?
736 }
737 crate::methods::MfaType::BackupCode => {
738 self.mfa_manager
739 .backup_codes
740 .verify_code(&stored_challenge.user_id, mfa_code)
741 .await?
742 }
743 _ => false,
744 };
745
746 if !is_valid {
747 if stored_challenge.attempts >= stored_challenge.max_attempts {
748 self.mfa_manager.remove_challenge(&challenge.id).await?;
749 }
750 return Err(MfaError::InvalidCode.into());
751 }
752
753 self.mfa_manager.remove_challenge(&challenge.id).await?;
755
756 let user_key = format!("user:{}", stored_challenge.user_id);
758 let scopes = if let Ok(Some(data)) = self.storage.get_kv(&user_key).await {
759 serde_json::from_slice::<serde_json::Value>(&data)
760 .ok()
761 .and_then(|v| {
762 v.get("roles").and_then(|r| {
763 r.as_array().map(|arr| {
764 arr.iter()
765 .filter_map(|v| v.as_str().map(String::from))
766 .collect::<Vec<_>>()
767 })
768 })
769 })
770 .unwrap_or_else(|| vec!["user".to_string()])
771 } else {
772 vec!["user".to_string()]
773 };
774
775 let token =
777 self.token_manager
778 .create_auth_token(&stored_challenge.user_id, scopes, "mfa", None)?;
779
780 self.storage.store_token(&token).await?;
782
783 info!(
784 "MFA completed successfully for user '{}'",
785 stored_challenge.user_id
786 );
787
788 Ok(token)
789 }
790
791 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
798 if !self.initialized {
799 return Err(AuthError::internal("Framework not initialized"));
800 }
801
802 if !token.is_valid() {
804 return Ok(false);
805 }
806
807 self.token_manager.validate_auth_token(token)?;
809
810 if !crate::auth::token_value_matches_jwt(&self.token_manager, token) {
812 return Ok(false);
813 }
814
815 if crate::auth::access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token)
817 .await?
818 {
819 return Ok(false);
820 }
821
822 if let Some(stored_token) = self.storage.get_token(&token.token_id).await?
824 && !stored_token.is_revoked()
825 {
826 let mut updated_token = stored_token;
828 updated_token.mark_used();
829 self.storage.update_token(&updated_token).await?;
830
831 Ok(true)
832 } else {
833 Ok(false)
834 }
835 }
836
837 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
845 if !self.validate_token(token).await? {
846 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
847 }
848
849 self.user_manager.get_user_info(&token.user_id).await
850 }
851
852 pub async fn check_permission(
859 &self,
860 token: &AuthToken,
861 action: &str,
862 resource: &str,
863 ) -> Result<bool> {
864 if !self.validate_token(token).await? {
865 return Ok(false);
866 }
867
868 let permission = Permission::new(action, resource);
869 let mut checker = self.permission_checker.write().await;
870 let proof = crate::tokens::ValidatedToken::new(token.clone());
871 checker.check_validated_permission(&proof, &permission)
872 }
873
874 pub fn token_manager(&self) -> &TokenManager {
881 &self.token_manager
882 }
883
884 pub fn mfa_manager(&self) -> &MfaManager {
891 &self.mfa_manager
892 }
893
894 pub fn session_manager(&self) -> &SessionManager {
901 &self.session_manager
902 }
903
904 pub fn user_manager(&self) -> &UserManager {
911 &self.user_manager
912 }
913
914 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
921 self.mfa_manager.sms.initiate_challenge(user_id).await
922 }
923
924 pub async fn send_sms_code(&self, challenge_id: &str, phone_number: &str) -> Result<()> {
931 self.mfa_manager
932 .sms
933 .send_code(challenge_id, phone_number)
934 .await
935 }
936
937 pub async fn generate_sms_code(&self, challenge_id: &str) -> Result<String> {
944 self.mfa_manager.sms.generate_code(challenge_id).await
945 }
946
947 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
954 self.mfa_manager.sms.verify_code(challenge_id, code).await
955 }
956
957 pub async fn cleanup_expired_data(&self) -> Result<()> {
964 debug!("Cleaning up expired data");
965
966 self.storage.cleanup_expired().await?;
968
969 self.mfa_manager.cleanup_expired_challenges().await?;
971
972 self.session_manager.cleanup_expired_sessions().await?;
974
975 if let Some(ref rate_limiter) = self.rate_limiter {
977 let _ = rate_limiter.cleanup().ok();
978 }
979
980 Ok(())
981 }
982
983 pub async fn get_stats(&self) -> Result<AuthStats> {
991 let mut stats = AuthStats::default();
992
993 for method in self.methods.keys() {
994 stats.registered_methods.push(method.clone());
995 }
996
997 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
998
999 stats.tokens_issued = self.storage.count_active_sessions().await.unwrap_or(0) as u64;
1001
1002 Ok(stats)
1003 }
1004
1005 async fn log_audit_event(
1007 &self,
1008 event_type: &str,
1009 user_id: &str,
1010 method: &str,
1011 metadata: &CredentialMetadata,
1012 ) {
1013 if self.config.audit.enabled {
1014 let should_log = match event_type {
1015 "auth_success" => self.config.audit.log_success,
1016 "auth_failure" => self.config.audit.log_failures,
1017 "mfa_required" => self.config.audit.log_success,
1018 _ => true,
1019 };
1020
1021 if should_log {
1022 info!(
1023 target: "auth_audit",
1024 event_type = event_type,
1025 user_id = user_id,
1026 method = method,
1027 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1028 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1029 timestamp = chrono::Utc::now().to_rfc3339(),
1030 "Authentication event"
1031 );
1032 }
1033 }
1034 }
1035}
1036
1037#[derive(Debug, Clone, Default)]
1039pub struct AuthStats {
1040 pub registered_methods: Vec<String>,
1042
1043 pub active_mfa_challenges: u64,
1045
1046 pub tokens_issued: u64,
1048
1049 pub auth_attempts: u64,
1051}
1052
1053#[cfg(test)]
1054mod tests {
1055 use super::*;
1056 use crate::authentication::credentials::Credential;
1057 use crate::config::{AuthConfig, SecurityConfig};
1058 use std::time::Duration;
1059
1060 async fn initialized_framework(config: AuthConfig) -> AuthFramework {
1061 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1062 framework
1063 .initialize()
1064 .await
1065 .expect("framework initialization should succeed");
1066 framework
1067 }
1068
1069 fn test_config() -> AuthConfig {
1070 AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!")
1071 }
1072
1073 #[tokio::test]
1074 async fn test_modular_framework_initialization() {
1075 let config = AuthConfig::new().security(SecurityConfig {
1076 min_password_length: 8,
1077 require_password_complexity: false,
1078 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1079 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1080 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1081 secure_cookies: false,
1082 cookie_same_site: crate::config::CookieSameSite::Lax,
1083 csrf_protection: false,
1084 session_timeout: Duration::from_secs(3600),
1085 previous_secret_key: None,
1086 });
1087 let mut framework = AuthFramework::new(config).expect("test config should be valid");
1088
1089 assert!(framework.initialize().await.is_ok());
1090 assert!(framework.initialized);
1091 }
1092
1093 #[tokio::test]
1094 async fn test_mfa_manager_access() {
1095 let config = AuthConfig::new().security(SecurityConfig {
1096 min_password_length: 8,
1097 require_password_complexity: false,
1098 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
1099 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
1100 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
1101 secure_cookies: false,
1102 cookie_same_site: crate::config::CookieSameSite::Lax,
1103 csrf_protection: false,
1104 session_timeout: Duration::from_secs(3600),
1105 previous_secret_key: None,
1106 });
1107 let framework = AuthFramework::new(config).expect("test config should be valid");
1108
1109 let _mfa_manager = framework.mfa_manager();
1111 let _session_manager = framework.session_manager();
1112 let _user_manager = framework.user_manager();
1113 }
1114
1115 #[tokio::test]
1116 async fn test_authenticate_with_metadata_enforces_minimum_duration() {
1117 let framework = initialized_framework(test_config()).await;
1118 let start = std::time::Instant::now();
1119
1120 let result = framework
1121 .authenticate_with_metadata(
1122 "oauth2",
1123 Credential::oauth_refresh(""),
1124 CredentialMetadata::new(),
1125 )
1126 .await
1127 .expect("empty refresh token should return failure, not error");
1128
1129 assert!(
1130 start.elapsed() >= std::time::Duration::from_millis(90),
1131 "timing floor should add a noticeable delay"
1132 );
1133 assert!(matches!(result, AuthResult::Failure(_)));
1134 }
1135
1136 #[tokio::test]
1137 async fn test_authenticate_oauth2_refresh_empty_returns_failure() {
1138 let framework = initialized_framework(test_config()).await;
1139
1140 let result = framework
1141 .authenticate("oauth2", Credential::oauth_refresh(""))
1142 .await
1143 .expect("empty refresh token should return failure, not error");
1144
1145 match result {
1146 AuthResult::Failure(reason) => {
1147 assert!(reason.contains("refresh token cannot be empty"));
1148 }
1149 _ => panic!("expected failure result for empty OAuth refresh token"),
1150 }
1151 }
1152
1153 #[tokio::test]
1154 async fn test_authenticate_oauth2_openid_connect_routes_to_jwt_validation() {
1155 let framework = initialized_framework(test_config()).await;
1156 let jwt = framework
1157 .token_manager()
1158 .create_jwt_token("oidc-user", vec!["openid".to_string()], None)
1159 .expect("jwt creation should succeed");
1160
1161 let result = framework
1162 .authenticate("oauth2", Credential::openid_connect(jwt))
1163 .await
1164 .expect("valid OIDC credential should authenticate");
1165
1166 match result {
1167 AuthResult::Success(token) => {
1168 assert_eq!(token.user_id, "oidc-user");
1169 assert_eq!(token.auth_method, "oauth2");
1170 }
1171 _ => panic!("expected success result for OpenID Connect credential"),
1172 }
1173 }
1174
1175 #[tokio::test]
1176 async fn test_authenticate_oauth2_unsupported_credential_returns_failure() {
1177 let framework = initialized_framework(test_config()).await;
1178
1179 let result = framework
1180 .authenticate("oauth2", Credential::password("alice", "secret"))
1181 .await
1182 .expect("unsupported credential should return failure, not error");
1183
1184 match result {
1185 AuthResult::Failure(reason) => {
1186 assert!(reason.contains("OAuth2 authentication expects"));
1187 }
1188 _ => panic!("expected failure result for unsupported OAuth2 credential"),
1189 }
1190 }
1191
1192 #[tokio::test]
1193 async fn test_rate_limiting_without_client_ip_uses_shared_unknown_bucket() {
1194 let config = AuthConfig::new()
1195 .secret("test_secret_key_32_bytes_long!!!!")
1196 .rate_limiting(crate::config::RateLimitConfig {
1197 enabled: true,
1198 max_requests: 1,
1199 window: Duration::from_secs(60),
1200 burst: 0,
1201 });
1202 let framework = initialized_framework(config).await;
1203
1204 let first = framework
1205 .authenticate_with_metadata(
1206 "oauth2",
1207 Credential::oauth_code("first-code"),
1208 CredentialMetadata::new(),
1209 )
1210 .await
1211 .expect("first request should pass rate limiting");
1212 assert!(matches!(first, AuthResult::Failure(_)));
1213
1214 let second = framework
1215 .authenticate_with_metadata(
1216 "oauth2",
1217 Credential::oauth_code("second-code"),
1218 CredentialMetadata::new(),
1219 )
1220 .await;
1221 assert!(second.is_err(), "second request should be rate limited");
1222 assert!(
1223 second
1224 .unwrap_err()
1225 .to_string()
1226 .contains("Too many authentication attempts")
1227 );
1228 }
1229
1230 #[tokio::test]
1231 async fn test_complete_mfa_missing_challenge_returns_expired_error() {
1232 let framework = initialized_framework(test_config()).await;
1233 let challenge = MfaChallenge::new(
1234 crate::methods::MfaType::BackupCode,
1235 "user-123",
1236 Duration::from_secs(60),
1237 );
1238
1239 let result = framework.complete_mfa(challenge, "123456").await;
1240 assert!(result.is_err());
1241 assert!(result.unwrap_err().to_string().contains("expired"));
1242 }
1243
1244 #[tokio::test]
1245 async fn test_complete_mfa_expired_challenge_is_removed() {
1246 let framework = initialized_framework(test_config()).await;
1247 let mut challenge = MfaChallenge::new(
1248 crate::methods::MfaType::BackupCode,
1249 "user-123",
1250 Duration::from_secs(60),
1251 );
1252 challenge.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1253 framework
1254 .mfa_manager
1255 .store_challenge(challenge.clone())
1256 .await
1257 .expect("storing challenge should succeed");
1258
1259 let result = framework.complete_mfa(challenge.clone(), "123456").await;
1260 assert!(result.is_err());
1261 assert!(result.unwrap_err().to_string().contains("expired"));
1262 assert!(
1263 framework
1264 .mfa_manager
1265 .get_challenge(&challenge.id)
1266 .await
1267 .expect("challenge lookup should succeed")
1268 .is_none()
1269 );
1270 }
1271
1272 #[tokio::test]
1273 async fn test_validate_token_returns_false_for_expired_token() {
1274 let framework = initialized_framework(test_config()).await;
1275 let mut token = framework
1276 .token_manager()
1277 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1278 .expect("token creation should succeed");
1279 token.expires_at = chrono::Utc::now() - chrono::Duration::seconds(1);
1280
1281 let valid = framework
1282 .validate_token(&token)
1283 .await
1284 .expect("expired token should return false, not error");
1285 assert!(!valid);
1286 }
1287
1288 #[tokio::test]
1289 async fn test_validate_token_returns_false_when_not_in_storage() {
1290 let framework = initialized_framework(test_config()).await;
1291 let token = framework
1292 .token_manager()
1293 .create_auth_token("user-123", vec!["read".to_string()], "jwt", None)
1294 .expect("token creation should succeed");
1295
1296 let valid = framework
1297 .validate_token(&token)
1298 .await
1299 .expect("missing stored token should return false, not error");
1300 assert!(!valid);
1301 }
1302
1303 #[cfg(feature = "redis-storage")]
1311 #[test]
1312 fn redis_construction_fails_closed_without_an_encryption_key() {
1313 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
1314 unsafe {
1317 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
1318 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
1319 }
1320
1321 let mut config = test_config();
1322 config.storage = crate::config::StorageConfig::Redis {
1323 url: "redis://127.0.0.1:1/".to_string(),
1324 key_prefix: "test:".to_string(),
1325 };
1326 let result = AuthFramework::new(config);
1329 assert!(
1330 result.is_err(),
1331 "constructing this modular framework with Redis storage and no encryption key \
1332 configured must fail closed, not silently build unwrapped (unencrypted) storage"
1333 );
1334 }
1335}