1use crate::auth_operations::{
4 AuditLogQuery, DelegationRequest, PermissionContext, SessionCreateRequest, UserListQuery,
5};
6use crate::authentication::credentials::{Credential, CredentialMetadata};
7use crate::config::AuthConfig;
8use crate::distributed::DistributedSessionStore;
9use crate::errors::{AuthError, MfaError, Result};
10use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
11use crate::permissions::PermissionChecker;
12use crate::storage::{AuthStorage, MemoryStorage, SessionData};
13use crate::tokens::{AuthToken, TokenManager};
14use crate::utils::rate_limit::RateLimiter;
15use std::collections::HashMap;
16use std::sync::Arc;
17use std::time::Duration;
18use tokio::sync::RwLock;
19use tracing::{debug, error, info, warn};
20
21#[derive(Debug, Clone)]
23pub enum AuthResult {
24 Success(Box<AuthToken>),
26
27 MfaRequired(Box<MfaChallenge>),
29
30 Failure(String),
32}
33
34#[derive(Debug, Clone)]
36pub struct UserInfo {
37 pub id: String,
39
40 pub username: String,
42
43 pub email: Option<String>,
45
46 pub name: Option<String>,
48
49 pub roles: crate::types::Roles,
51
52 pub active: bool,
54
55 pub email_verified: bool,
57
58 pub attributes: crate::types::UserAttributes,
60}
61
62#[inline]
71fn is_test_env() -> bool {
72 if std::env::var("ENVIRONMENT").as_deref() == Ok("production") {
74 return false;
75 }
76 cfg!(test)
77 || std::env::var("RUST_TEST").is_ok()
78 || std::env::var("ENVIRONMENT").as_deref() == Ok("test")
79}
80
81pub struct AuthFramework {
141 config: AuthConfig,
143
144 methods: HashMap<String, AuthMethodEnum>,
146
147 token_manager: TokenManager,
149
150 storage: Arc<dyn AuthStorage>,
152
153 authorization_manager: crate::auth_modular::authorization_manager::AuthorizationManager,
155
156 rate_limiter: Option<RateLimiter>,
158
159 monitoring_manager: Arc<crate::monitoring::MonitoringManager>,
161
162 audit_manager: Arc<crate::audit::AuditLogger<Arc<dyn crate::audit::AuditStorage>>>,
167
168 #[cfg(feature = "api-server")]
170 security_manager: Arc<crate::api::SecurityManager>,
171
172 pub(crate) runtime_config: Arc<tokio::sync::RwLock<crate::config::RuntimeConfig>>,
174
175 user_manager: crate::auth_modular::user_manager::UserManager,
177
178 session_manager: crate::auth_modular::session_manager::SessionManager,
180
181 mfa_manager: crate::auth_modular::mfa::MfaManager,
183
184 initialized: bool,
186
187 storage_overridden: bool,
189 storage_from_caller: bool,
194}
195
196pub use crate::auth_operations::{
197 AdminOperations, AuditOperations, AuthorizationOperations, MaintenanceOperations,
198 MfaOperations, MonitoringOperations, SessionOperations, TokenOperations, UserOperations,
199};
200
201fn resolve_jwt_secret_bytes(config: &AuthConfig) -> Result<Vec<u8>> {
207 if let Some(secret) = &config.security.secret_key {
208 if secret.len() < 32 && !is_test_env() {
209 return Err(AuthError::configuration(
210 "JWT secret must be at least 32 characters for production security",
211 ));
212 }
213 return Ok(secret.as_bytes().to_vec());
214 }
215 if let Some(secret) = &config.secret {
216 if secret.len() < 32 && !is_test_env() {
217 return Err(AuthError::configuration(
218 "JWT secret must be at least 32 characters for production security",
219 ));
220 }
221 return Ok(secret.as_bytes().to_vec());
222 }
223 if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
224 if jwt_secret.len() < 32 && !is_test_env() {
225 return Err(AuthError::configuration(
226 "JWT_SECRET must be at least 32 characters for production security",
227 ));
228 }
229 return Ok(jwt_secret.as_bytes().to_vec());
230 }
231 Err(AuthError::configuration(
232 "JWT secret not configured! Please set JWT_SECRET environment variable or provide in configuration.\n\
233 For security reasons, no default secret is provided.\n\
234 Generate a secure secret with: openssl rand -base64 32",
235 ))
236}
237
238impl AuthFramework {
239 pub fn users(&self) -> UserOperations<'_> {
241 UserOperations { framework: self }
242 }
243
244 pub fn sessions(&self) -> SessionOperations<'_> {
246 SessionOperations { framework: self }
247 }
248
249 pub fn tokens(&self) -> TokenOperations<'_> {
251 TokenOperations { framework: self }
252 }
253
254 pub fn authorization(&self) -> AuthorizationOperations<'_> {
256 AuthorizationOperations { framework: self }
257 }
258
259 pub fn mfa(&self) -> MfaOperations<'_> {
261 MfaOperations { framework: self }
262 }
263
264 pub fn monitoring(&self) -> MonitoringOperations<'_> {
266 MonitoringOperations { framework: self }
267 }
268
269 pub fn audit(&self) -> AuditOperations<'_> {
271 AuditOperations { framework: self }
272 }
273
274 pub fn maintenance(&self) -> MaintenanceOperations<'_> {
276 MaintenanceOperations { framework: self }
277 }
278
279 pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
281 self.runtime_config.read().await.clone()
282 }
283
284 #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
285 #[doc(hidden)]
286 pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
287 self.runtime_config().await
288 }
289
290 pub async fn update_runtime_config(
295 &self,
296 update: crate::config::RuntimeConfig,
297 ) -> Result<crate::config::RuntimeConfig> {
298 if update.token_lifetime_secs == 0 {
300 return Err(AuthError::config("token_lifetime_secs must be > 0"));
301 }
302 if update.refresh_token_lifetime_secs == 0 {
303 return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
304 }
305 if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
306 return Err(AuthError::config(
307 "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
308 ));
309 }
310 if update.min_password_length == 0 {
311 return Err(AuthError::config("min_password_length must be > 0"));
312 }
313 let mut cfg = self.runtime_config.write().await;
314 *cfg = update.clone();
315 Ok(update)
316 }
317
318 pub fn admin(&self) -> AdminOperations<'_> {
320 AdminOperations { framework: self }
321 }
322
323 pub fn new(config: AuthConfig) -> Self {
331 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
333 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
334 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
335
336 let ephemeral_secret = {
342 let rng = ring::rand::SystemRandom::new();
343 let mut buf = [0u8; 32];
344 ring::rand::SecureRandom::fill(&rng, &mut buf)
345 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
346 buf
347 };
348 let token_manager =
349 TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
350
351 let user_manager = crate::auth_modular::user_manager::UserManager::new(
352 storage.clone(),
353 config.security.password_hash_algorithm.clone(),
354 );
355 let session_manager =
356 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
357 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
358 let authorization_manager =
359 crate::auth_modular::authorization_manager::AuthorizationManager::new(
360 Arc::new(RwLock::new(PermissionChecker::new())),
361 storage.clone(),
362 );
363
364 Self {
365 config,
366 methods: HashMap::new(),
367 token_manager,
368 storage,
369 authorization_manager,
370 rate_limiter: None, monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
372 crate::monitoring::MonitoringConfig::default(),
373 )),
374 audit_manager,
375 #[cfg(feature = "api-server")]
376 security_manager: Arc::new(crate::api::SecurityManager::new()),
377 runtime_config: Arc::new(tokio::sync::RwLock::new(
378 crate::config::RuntimeConfig::default(),
379 )),
380 user_manager,
381 session_manager,
382 mfa_manager,
383 initialized: false,
384 storage_overridden: false,
385 storage_from_caller: false,
386 }
387 }
388
389 pub fn new_validated(config: AuthConfig) -> Result<Self> {
394 config.validate().map_err(|e| {
396 AuthError::configuration(format!("Configuration validation failed: {}", e))
397 })?;
398
399 let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
401
402 let mut token_manager =
403 TokenManager::new_hmac(¤t_secret_bytes, "auth-framework", "auth-framework");
404
405 if let Some(prev_secret) = &config.security.previous_secret_key {
407 token_manager =
409 TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
410 token_manager.rotate_hmac_key(¤t_secret_bytes);
411 }
412
413 let storage: Arc<dyn AuthStorage> = match &config.storage {
422 #[cfg(feature = "redis-storage")]
423 crate::config::StorageConfig::Redis { url, key_prefix } => {
424 let redis: Arc<dyn AuthStorage> = Arc::new(
425 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
426 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
427 })?,
428 );
429 crate::storage::factory::wrap_with_encryption_if_enabled(
430 redis,
431 &config.storage_encryption,
432 )?
433 }
434 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
435 };
436
437 let rate_limiter = if config.rate_limiting.enabled {
439 Some(RateLimiter::new(
440 config.rate_limiting.max_requests,
441 config.rate_limiting.window,
442 ))
443 } else {
444 None
445 };
446
447 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
449 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
450
451 let user_manager = crate::auth_modular::user_manager::UserManager::new(
452 storage.clone(),
453 config.security.password_hash_algorithm.clone(),
454 );
455 let session_manager =
456 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
457 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
458 let authorization_manager =
459 crate::auth_modular::authorization_manager::AuthorizationManager::new(
460 Arc::new(RwLock::new(PermissionChecker::new())),
461 storage.clone(),
462 );
463
464 Ok(Self {
465 config: config.clone(),
466 methods: HashMap::new(),
467 token_manager,
468 storage,
469 authorization_manager,
470 rate_limiter,
471 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
472 crate::monitoring::MonitoringConfig::default(),
473 )),
474 audit_manager,
475 #[cfg(feature = "api-server")]
476 security_manager: Arc::new(crate::api::SecurityManager::new()),
477 runtime_config: Arc::new(tokio::sync::RwLock::new(
478 crate::config::RuntimeConfig::from_auth_config(&config),
479 )),
480 user_manager,
481 session_manager,
482 mfa_manager,
483 initialized: false,
484 storage_overridden: false,
485 storage_from_caller: false,
486 })
487 }
488
489 pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
496 self.storage = storage.clone();
497 self.user_manager = crate::auth_modular::user_manager::UserManager::new(
498 storage.clone(),
499 self.config.security.password_hash_algorithm.clone(),
500 );
501 self.session_manager =
502 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
503 self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
504 self.authorization_manager =
505 crate::auth_modular::authorization_manager::AuthorizationManager::new(
506 Arc::new(RwLock::new(PermissionChecker::new())),
507 storage,
508 );
509 self.storage_overridden = true;
510 self.storage_from_caller = true;
511 }
512
513 pub(crate) fn replace_storage_from_factory(
517 &mut self,
518 storage: std::sync::Arc<dyn AuthStorage>,
519 ) {
520 self.replace_storage(storage);
521 self.storage_from_caller = false;
522 }
523
524 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
531 self.session_manager.set_distributed_store(store);
532 }
533
534 pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
536 let mut framework = Self::new(config);
537 framework.replace_storage(storage);
538 framework
539 }
540
541 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
543 let name = name.into();
544 info!("Registering authentication method: {}", name);
545
546 if let Err(e) = method.validate_config() {
548 error!("Method '{}' configuration validation failed: {}", name, e);
549 return;
550 }
551
552 self.methods.insert(name, method);
553 }
554
555 fn require_initialized(&self) -> Result<()> {
561 if self.initialized {
562 Ok(())
563 } else {
564 Err(AuthError::configuration(
565 "Framework not initialized. Call `initialize().await` first, \
566 or use `AuthFramework::builder().build().await` which initializes automatically.",
567 ))
568 }
569 }
570
571 pub async fn initialize(&mut self) -> Result<()> {
581 if self.initialized {
582 return Ok(());
583 }
584
585 info!("Initializing authentication framework");
586
587 self.config.validate().map_err(|e| {
589 AuthError::configuration(format!("Configuration validation failed: {}", e))
590 })?;
591
592 let token_manager = match resolve_jwt_secret_bytes(&self.config) {
594 Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
595 Err(_) => {
596 if Self::is_production_environment() {
597 return Err(AuthError::configuration(
598 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
599 Generate a secure secret with: openssl rand -base64 32\n\
600 Set it with: export JWT_SECRET=\"your-secret-here\"",
601 ));
602 }
603 warn!("No JWT secret configured, using development-only default");
604 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
605 warn!("This configuration is NOT SECURE and should only be used in development!");
606 self.token_manager.clone()
607 }
608 };
609
610 self.token_manager = token_manager;
612
613 if self.storage_from_caller {
617 crate::storage::factory::check_overridden_storage(
618 &self.storage,
619 &self.config.storage_encryption,
620 )?;
621 }
622
623 if !self.storage_overridden {
625 let storage = crate::storage::factory::build_storage_backend_with_encryption(
626 &self.config.storage,
627 None,
628 &self.config.storage_encryption,
629 )
630 .await?;
631 self.replace_storage(storage);
632 self.storage_overridden = false;
633 self.storage_from_caller = false;
634 }
635
636 if self.config.rate_limiting.enabled {
638 self.rate_limiter = Some(RateLimiter::new(
639 self.config.rate_limiting.max_requests,
640 self.config.rate_limiting.window,
641 ));
642 }
643
644 self.authorization_manager.create_default_roles().await;
646
647 self.authorization_manager.load_persisted_roles().await?;
649
650 self.cleanup_expired_data().await?;
652
653 self.initialized = true;
654 info!("Authentication framework initialized successfully");
655
656 Ok(())
657 }
658
659 pub async fn authenticate(
687 &self,
688 method_name: &str,
689 credential: Credential,
690 ) -> Result<AuthResult> {
691 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
692 .await
693 }
694
695 pub async fn authenticate_with_metadata(
697 &self,
698 method_name: &str,
699 credential: Credential,
700 metadata: CredentialMetadata,
701 ) -> Result<AuthResult> {
702 use std::time::Instant;
703 use tokio::time::{Duration as TokioDuration, sleep};
704
705 let start_time = Instant::now();
706
707 self.monitoring_manager.record_auth_request().await;
709
710 self.require_initialized()?;
711
712 let result = self
714 .authenticate_internal(method_name, credential, metadata)
715 .await;
716
717 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
720 if elapsed < min_duration {
721 sleep(min_duration - elapsed).await;
722 }
723
724 if let Ok(ref auth_result) = result {
726 match auth_result {
727 AuthResult::Success(token) => {
728 self.monitoring_manager
729 .record_auth_success(&token.user_id, elapsed)
730 .await;
731 }
732 AuthResult::Failure(reason) => {
733 self.monitoring_manager
734 .record_auth_failure(None, reason)
735 .await;
736 }
737 _ => {} }
739 }
740
741 result
742 }
743
744 async fn authenticate_internal(
746 &self,
747 method_name: &str,
748 credential: Credential,
749 metadata: CredentialMetadata,
750 ) -> Result<AuthResult> {
751 if let Some(ref rate_limiter) = self.rate_limiter {
753 let rate_key = format!(
754 "auth:{}:{}",
755 method_name,
756 metadata.client_ip.as_deref().unwrap_or("unknown")
757 );
758
759 if !rate_limiter.is_allowed(&rate_key) {
760 warn!(
761 "Rate limit exceeded for method '{}' from IP {:?}",
762 method_name, metadata.client_ip
763 );
764 return Err(AuthError::rate_limit("Too many authentication attempts"));
765 }
766 }
767
768 if method_name == "password"
772 && let Credential::Password {
773 ref username,
774 ref password,
775 } = credential
776 {
777 return self
778 .authenticate_password_builtin(username, password, &metadata)
779 .await;
780 }
781
782 if method_name == "jwt" {
783 return match credential {
784 Credential::Jwt { token } | Credential::Bearer { token } => {
785 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
786 .await
787 }
788 _ => Ok(AuthResult::Failure(
789 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
790 )),
791 };
792 }
793
794 if matches!(method_name, "api_key" | "api-key") {
795 return match credential {
796 Credential::ApiKey { key } => {
797 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
798 .await
799 }
800 _ => Ok(AuthResult::Failure(
801 "API key authentication expects Credential::api_key".to_string(),
802 )),
803 };
804 }
805
806 if method_name == "oauth2" {
807 return self
808 .authenticate_oauth2_builtin(credential, &metadata)
809 .await;
810 }
811
812 let method = self.methods.get(method_name).ok_or_else(|| {
814 AuthError::auth_method(method_name, "Authentication method not found".to_string())
815 })?;
816
817 debug!(
819 "Authentication attempt with method '{}' for credential: {}",
820 method_name,
821 credential.safe_display()
822 );
823
824 let result = method.authenticate(credential, metadata.clone()).await?;
826
827 match &result {
829 MethodResult::Success(token) => {
830 info!(
831 "Authentication successful for user '{}' with method '{}'",
832 token.user_id, method_name
833 );
834
835 self.storage.store_token(token).await?;
837
838 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
840 .await;
841
842 Ok(AuthResult::Success(token.clone()))
843 }
844
845 MethodResult::MfaRequired(challenge) => {
846 info!(
847 "MFA required for user '{}' with method '{}'",
848 challenge.user_id, method_name
849 );
850
851 self.guard_and_store_mfa_challenge((**challenge).clone())
853 .await?;
854
855 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
857 .await;
858
859 Ok(AuthResult::MfaRequired(challenge.clone()))
860 }
861
862 MethodResult::Failure { reason } => {
863 warn!(
864 "Authentication failed for method '{}': {}",
865 method_name, reason
866 );
867
868 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
870 .await;
871
872 Ok(AuthResult::Failure(reason.clone()))
873 }
874 }
875 }
876
877 async fn authenticate_jwt_builtin(
878 &self,
879 token: &str,
880 metadata: &CredentialMetadata,
881 auth_method: &str,
882 ) -> Result<AuthResult> {
883 if token.is_empty() {
884 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
885 }
886
887 match self.token_manager.validate_jwt_token(token) {
888 Ok(claims) => {
889 let token =
890 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
891 Ok(AuthResult::Success(Box::new(token)))
892 }
893 Err(error) => {
894 if let Some(reason) = Self::credential_failure_reason(&error) {
895 Ok(AuthResult::Failure(reason))
896 } else {
897 Err(error)
898 }
899 }
900 }
901 }
902
903 async fn authenticate_api_key_builtin(
904 &self,
905 api_key: &str,
906 metadata: &CredentialMetadata,
907 auth_method: &str,
908 ) -> Result<AuthResult> {
909 if api_key.is_empty() {
910 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
911 }
912
913 match self.validate_api_key(api_key).await {
914 Ok(user) => {
915 let scopes: Vec<String> = if user.roles.is_empty() {
916 vec!["api_user".to_string()]
917 } else {
918 user.roles.to_vec()
919 };
920 let mut token = self
921 .token_manager
922 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
923 .with_roles(user.roles)
924 .with_scopes(scopes);
925 token.metadata.issued_ip = metadata.client_ip.clone();
926 token.metadata.user_agent = metadata.user_agent.clone();
927 Ok(AuthResult::Success(Box::new(token)))
928 }
929 Err(error) => {
930 if let Some(reason) = Self::credential_failure_reason(&error) {
931 Ok(AuthResult::Failure(reason))
932 } else {
933 Err(error)
934 }
935 }
936 }
937 }
938
939 async fn authenticate_oauth2_builtin(
940 &self,
941 credential: Credential,
942 metadata: &CredentialMetadata,
943 ) -> Result<AuthResult> {
944 match credential {
945 Credential::OAuth {
946 authorization_code, ..
947 } => {
948 if authorization_code.is_empty() {
949 return Ok(AuthResult::Failure(
950 "OAuth authorization code cannot be empty".to_string(),
951 ));
952 }
953 Ok(AuthResult::Failure(
954 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
955 .to_string(),
956 ))
957 }
958 Credential::OAuthRefresh { refresh_token } => {
959 if refresh_token.is_empty() {
960 return Ok(AuthResult::Failure(
961 "OAuth refresh token cannot be empty".to_string(),
962 ));
963 }
964 Ok(AuthResult::Failure(
965 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
966 .to_string(),
967 ))
968 }
969 Credential::Jwt { token }
970 | Credential::Bearer { token }
971 | Credential::OpenIdConnect { id_token: token, .. } => {
972 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
973 }
974 _ => Ok(AuthResult::Failure(
975 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
976 .to_string(),
977 )),
978 }
979 }
980
981 fn build_validated_jwt_auth_token(
982 raw_token: &str,
983 claims: crate::tokens::JwtClaims,
984 metadata: &CredentialMetadata,
985 auth_method: &str,
986 ) -> AuthToken {
987 let crate::tokens::JwtClaims {
988 sub,
989 iss,
990 exp,
991 iat,
992 jti,
993 scope,
994 permissions,
995 roles,
996 client_id,
997 ..
998 } = claims;
999
1000 let now = chrono::Utc::now();
1001 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
1002 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
1003 .unwrap_or(now + chrono::Duration::hours(1));
1004 let lifetime = (expires_at - now)
1005 .to_std()
1006 .unwrap_or_else(|_| Duration::from_secs(1));
1007 let scopes = if scope.trim().is_empty() {
1008 Vec::new()
1009 } else {
1010 scope.split_whitespace().map(str::to_string).collect()
1011 };
1012
1013 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
1014 .with_scopes(scopes)
1015 .with_permissions(permissions.unwrap_or_default())
1016 .with_roles(roles.unwrap_or_default());
1017 token.token_id = jti;
1018 token.subject = Some(sub);
1019 token.issuer = Some(iss);
1020 token.issued_at = issued_at;
1021 token.expires_at = expires_at;
1022 token.metadata.issued_ip = metadata.client_ip.clone();
1023 token.metadata.user_agent = metadata.user_agent.clone();
1024 if let Some(client_id) = client_id {
1025 token.client_id = Some(client_id);
1026 }
1027 token
1028 }
1029
1030 fn credential_failure_reason(error: &AuthError) -> Option<String> {
1031 match error {
1032 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
1033 AuthError::Validation { message } => Some(message.clone()),
1034 AuthError::UserNotFound => Some("User not found".to_string()),
1035 _ => None,
1036 }
1037 }
1038
1039 async fn authenticate_password_builtin(
1041 &self,
1042 username: &str,
1043 password: &str,
1044 metadata: &CredentialMetadata,
1045 ) -> Result<AuthResult> {
1046 use crate::auth_modular::user_manager::CredentialCheckResult;
1047
1048 if username.is_empty() || password.is_empty() {
1049 return Ok(AuthResult::Failure(
1050 "Username or password cannot be empty".to_string(),
1051 ));
1052 }
1053
1054 match self
1055 .user_manager
1056 .verify_login_credentials(username, password)
1057 .await?
1058 {
1059 None => {
1060 self.log_audit_event("auth_failure", "unknown", "password", metadata)
1061 .await;
1062 Ok(AuthResult::Failure(
1063 "Invalid username or password".to_string(),
1064 ))
1065 }
1066 Some(CredentialCheckResult {
1067 ref user_id,
1068 mfa_enabled: true,
1069 }) => {
1070 let now = chrono::Utc::now();
1071 let challenge = MfaChallenge {
1072 id: crate::utils::string::generate_id(Some("mfa")),
1073 mfa_type: crate::methods::MfaType::MultiMethod,
1074 user_id: user_id.clone(),
1075 created_at: now,
1076 expires_at: now + chrono::Duration::minutes(5),
1077 attempts: 0,
1078 max_attempts: 5,
1079 code_hash: None,
1080 message: Some(
1081 "Provide your current TOTP code or a backup code to complete login"
1082 .to_string(),
1083 ),
1084 data: HashMap::new(),
1085 };
1086 self.guard_and_store_mfa_challenge(challenge.clone())
1087 .await?;
1088 self.log_audit_event("mfa_required", user_id, "password", metadata)
1089 .await;
1090 info!(
1091 "Built-in password authentication requires MFA for user: {}",
1092 username
1093 );
1094 Ok(AuthResult::MfaRequired(Box::new(challenge)))
1095 }
1096 Some(CredentialCheckResult {
1097 ref user_id,
1098 mfa_enabled: false,
1099 }) => {
1100 let token = self
1101 .mint_and_store_token(
1102 user_id,
1103 vec!["read".to_string(), "write".to_string()],
1104 "password",
1105 None,
1106 )
1107 .await?;
1108 self.monitoring_manager.record_auth_request().await;
1109 self.log_audit_event("auth_success", user_id, "password", metadata)
1110 .await;
1111 info!(
1112 "Built-in password authentication successful for user: {}",
1113 username
1114 );
1115 Ok(AuthResult::Success(Box::new(token)))
1116 }
1117 }
1118 }
1119
1120 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1122 debug!("Completing MFA for challenge '{}'", challenge.id);
1123
1124 let stored_challenge = self
1125 .mfa_manager
1126 .get_challenge(&challenge.id)
1127 .await?
1128 .ok_or(MfaError::ChallengeExpired)?;
1129
1130 if stored_challenge.is_expired() {
1131 self.mfa_manager.remove_challenge(&challenge.id).await?;
1132 return Err(MfaError::ChallengeExpired.into());
1133 }
1134
1135 if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1136 return Err(MfaError::InvalidCode.into());
1137 }
1138
1139 self.mfa_manager.remove_challenge(&challenge.id).await?;
1140
1141 let scopes = self
1142 .user_manager
1143 .get_user_roles(&challenge.user_id)
1144 .await
1145 .unwrap_or_else(|_| vec!["user".to_string()]);
1146
1147 let token = self
1148 .mint_and_store_token(&challenge.user_id, scopes, "mfa", None)
1149 .await?;
1150
1151 info!(
1152 "MFA completed successfully for user '{}'",
1153 challenge.user_id
1154 );
1155 Ok(token)
1156 }
1157
1158 pub async fn complete_mfa_by_id(
1160 &self,
1161 challenge_id: &str,
1162 mfa_code: &str,
1163 ) -> Result<AuthToken> {
1164 let challenge = self
1165 .mfa_manager
1166 .get_challenge(challenge_id)
1167 .await?
1168 .ok_or(MfaError::ChallengeExpired)?;
1169
1170 self.complete_mfa(challenge, mfa_code).await
1171 }
1172
1173 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1175 self.require_initialized()?;
1176 let valid = token.is_valid()
1177 && self.token_manager.validate_auth_token(token).is_ok()
1178 && self.touch_stored_token(token).await?;
1179 self.monitoring_manager.record_token_validation(valid).await;
1180 Ok(valid)
1181 }
1182
1183 async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1184 let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1185 return Ok(false);
1186 };
1187 stored.mark_used();
1188 self.storage.update_token(&stored).await?;
1189 Ok(true)
1190 }
1191
1192 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1194 if !self.validate_token(token).await? {
1195 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1196 }
1197
1198 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1199
1200 match self.user_manager.get_user_info(&token_info.user_id).await {
1203 Ok(mut info) => {
1204 if !token_info.attributes.is_empty() {
1206 let string_attrs: HashMap<String, String> = token_info
1207 .attributes
1208 .into_iter()
1209 .map(|(k, v)| {
1210 (
1211 k,
1212 v.as_str()
1213 .map(|s| s.to_string())
1214 .unwrap_or_else(|| v.to_string()),
1215 )
1216 })
1217 .collect();
1218 info.attributes = string_attrs.into();
1219 }
1220 Ok(info)
1221 }
1222 Err(_) => {
1223 let string_attrs: HashMap<String, String> = token_info
1224 .attributes
1225 .into_iter()
1226 .map(|(k, v)| {
1227 (
1228 k,
1229 v.as_str()
1230 .map(|s| s.to_string())
1231 .unwrap_or_else(|| v.to_string()),
1232 )
1233 })
1234 .collect();
1235 Ok(UserInfo {
1236 id: token_info.user_id,
1237 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1238 email: token_info.email,
1239 name: token_info.name,
1240 roles: token_info.roles.into(),
1241 active: false,
1242 email_verified: false,
1243 attributes: string_attrs.into(),
1244 })
1245 }
1246 }
1247 }
1248
1249 pub async fn check_permission(
1276 &self,
1277 token: &AuthToken,
1278 action: &str,
1279 resource: &str,
1280 ) -> Result<bool> {
1281 if !self.validate_token(token).await? {
1282 return Ok(false);
1283 }
1284 self.authorization_manager
1285 .check_token_permission(token, action, resource)
1286 .await
1287 }
1288
1289 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1291 self.require_initialized()?;
1292 debug!("Refreshing token for user '{}'", token.user_id);
1293
1294 if let Some(method) = self.methods.get(&token.auth_method)
1296 && method.supports_refresh()
1297 && let Some(ref refresh_token) = token.refresh_token
1298 {
1299 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1300 self.storage.store_token(&new_token).await?;
1301 return Ok(new_token);
1302 }
1303
1304 let new_token = self.token_manager.refresh_token(token)?;
1306 self.storage.store_token(&new_token).await?;
1307
1308 info!("Token refreshed for user '{}'", token.user_id);
1309
1310 Ok(new_token)
1311 }
1312
1313 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1315 self.require_initialized()?;
1316 debug!("Revoking token for user '{}'", token.user_id);
1317
1318 let mut revoked_token = token.clone();
1320 revoked_token.revoke(Some("Manual revocation".to_string()));
1321
1322 self.storage.update_token(&revoked_token).await?;
1324
1325 info!("Token revoked for user '{}'", token.user_id);
1326
1327 Ok(())
1328 }
1329
1330 pub async fn create_api_key(
1332 &self,
1333 user_id: &str,
1334 expires_in: Option<Duration>,
1335 ) -> Result<String> {
1336 self.require_initialized()?;
1337 self.user_manager.create_api_key(user_id, expires_in).await
1338 }
1339
1340 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1342 self.require_initialized()?;
1343 self.user_manager.validate_api_key(api_key).await
1344 }
1345
1346 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1348 self.require_initialized()?;
1349 self.user_manager.revoke_api_key(api_key).await
1350 }
1351
1352 pub async fn create_session(
1354 &self,
1355 user_id: &str,
1356 expires_in: Duration,
1357 ip_address: Option<String>,
1358 user_agent: Option<String>,
1359 ) -> Result<String> {
1360 self.require_initialized()?;
1361 let (session_id, new_total) = self
1362 .session_manager
1363 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1364 .await?;
1365 self.monitoring_manager
1366 .update_session_count(new_total)
1367 .await;
1368 Ok(session_id)
1369 }
1370
1371 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1391 self.create_session(
1392 req.get_user_id(),
1393 req.get_expires_in(),
1394 req.get_ip_address().map(|s| s.to_string()),
1395 req.get_user_agent().map(|s| s.to_string()),
1396 )
1397 .await
1398 }
1399
1400 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1402 self.require_initialized()?;
1403 self.session_manager.get_session(session_id).await
1404 }
1405
1406 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1408 self.require_initialized()?;
1409 self.session_manager.delete_session(session_id).await?;
1410
1411 let remaining = self
1412 .session_manager
1413 .count_active_sessions()
1414 .await
1415 .unwrap_or(0);
1416 self.monitoring_manager
1417 .update_session_count(remaining)
1418 .await;
1419
1420 Ok(())
1421 }
1422
1423 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1425 self.require_initialized()?;
1426 self.storage.list_user_tokens(user_id).await
1427 }
1428
1429 pub async fn cleanup_expired_data(&self) -> Result<()> {
1431 debug!("Cleaning up expired data");
1432
1433 self.storage.cleanup_expired().await?;
1435
1436 self.mfa_manager.cleanup_expired_challenges().await?;
1438
1439 self.session_manager.cleanup_expired_sessions().await?;
1441
1442 if let Some(ref rate_limiter) = self.rate_limiter {
1444 let _ = rate_limiter.cleanup().ok();
1445 }
1446
1447 Ok(())
1448 }
1449
1450 fn is_production_environment() -> bool {
1453 if let Ok(env) = std::env::var("ENVIRONMENT")
1454 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1455 {
1456 return true;
1457 }
1458 if let Ok(env) = std::env::var("ENV")
1459 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1460 {
1461 return true;
1462 }
1463 if let Ok(env) = std::env::var("NODE_ENV")
1464 && env.to_lowercase() == "production"
1465 {
1466 return true;
1467 }
1468 if let Ok(env) = std::env::var("RUST_ENV")
1469 && env.to_lowercase() == "production"
1470 {
1471 return true;
1472 }
1473 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1474 || std::env::var("DOCKER_CONTAINER").is_ok()
1475 }
1476
1477 pub async fn get_stats(&self) -> Result<AuthStats> {
1479 let mut stats = AuthStats::default();
1480
1481 if let Err(e) = self.storage.cleanup_expired().await {
1482 warn!("Failed to cleanup expired data: {}", e);
1483 }
1484 if let Some(rate_limiter) = &self.rate_limiter {
1485 let _ = rate_limiter.cleanup().ok();
1486 }
1487
1488 let active_sessions = self
1489 .session_manager
1490 .count_active_sessions()
1491 .await
1492 .unwrap_or(0) as u32;
1493
1494 stats.registered_methods = self.methods.keys().cloned().collect();
1495 stats.active_sessions = active_sessions as u64;
1496 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1497 let perf = self.monitoring_manager.get_performance_metrics();
1499 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1500 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1501 + perf.get("auth_failures").copied().unwrap_or(0);
1502
1503 Ok(stats)
1504 }
1505
1506 pub fn token_manager(&self) -> &TokenManager {
1511 &self.token_manager
1512 }
1513
1514 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1524 self.user_manager.validate_username(username).await
1525 }
1526
1527 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1534 self.user_manager.validate_display_name(display_name).await
1535 }
1536
1537 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1546 self.user_manager.validate_password_strength(password).await
1547 }
1548
1549 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1554 Ok(crate::utils::validation::validate_user_input(input))
1555 }
1556
1557 pub async fn create_auth_token(
1577 &self,
1578 user_id: impl Into<String>,
1579 scopes: impl Into<crate::types::Scopes>,
1580 method_name: impl Into<String>,
1581 lifetime: Option<Duration>,
1582 ) -> Result<AuthToken> {
1583 let method_name = method_name.into();
1584 let user_id = user_id.into();
1585 let scopes: crate::types::Scopes = scopes.into();
1586
1587 let auth_method = self
1589 .methods
1590 .get(&method_name)
1591 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1592 auth_method.validate_config()?;
1593
1594 const MAX_TOKENS_PER_USER: usize = 100;
1596 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1597 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1598 warn!(
1599 "User '{}' has reached maximum tokens ({})",
1600 user_id, MAX_TOKENS_PER_USER
1601 );
1602 return Err(AuthError::rate_limit(
1603 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1604 ));
1605 }
1606
1607 let token = self
1608 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1609 .await?;
1610 self.monitoring_manager
1611 .record_token_creation(&method_name)
1612 .await;
1613 Ok(token)
1614 }
1615
1616 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1626 self.mfa_manager.sms.initiate_challenge(user_id).await
1627 }
1628
1629 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1637 self.mfa_manager.sms.verify_code(challenge_id, code).await
1638 }
1639
1640 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1647 self.mfa_manager.email.register_email(user_id, email).await
1648 }
1649
1650 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1661 self.mfa_manager.totp.generate_secret(user_id).await
1662 }
1663
1664 pub async fn generate_totp_qr_code(
1672 &self,
1673 user_id: &str,
1674 app_name: &str,
1675 secret: &str,
1676 ) -> Result<String> {
1677 self.mfa_manager
1678 .totp
1679 .generate_qr_code(user_id, app_name, secret)
1680 .await
1681 }
1682
1683 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1688 self.mfa_manager.totp.generate_code(secret).await
1689 }
1690
1691 pub async fn generate_totp_code_for_window(
1695 &self,
1696 secret: &str,
1697 time_window: Option<u64>,
1698 ) -> Result<String> {
1699 self.mfa_manager
1700 .totp
1701 .generate_code_for_window(secret, time_window)
1702 .await
1703 }
1704
1705 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
1713 self.mfa_manager.totp.verify_code(user_id, code).await
1714 }
1715
1716 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1721 debug!("Checking IP rate limit for '{}'", ip);
1722 let Some(ref rate_limiter) = self.rate_limiter else {
1723 return Ok(true);
1724 };
1725 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
1726 warn!("Rate limit exceeded for IP: {}", ip);
1727 return Err(AuthError::rate_limit(format!(
1728 "Too many requests from IP {}. Please try again later.",
1729 ip
1730 )));
1731 }
1732 Ok(true)
1733 }
1734
1735 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1740 debug!("Getting security metrics");
1741 let mut metrics = std::collections::HashMap::new();
1742 let total_active_sessions = self
1743 .session_manager
1744 .count_active_sessions()
1745 .await
1746 .unwrap_or(0);
1747 metrics.insert("active_sessions".to_string(), total_active_sessions);
1748 metrics.insert("total_tokens".to_string(), total_active_sessions);
1749 metrics.insert(
1750 "failed_attempts".to_string(),
1751 self.audit_manager
1752 .get_failed_login_count_24h()
1753 .await
1754 .unwrap_or(0),
1755 );
1756 metrics.insert(
1757 "successful_attempts".to_string(),
1758 self.audit_manager
1759 .get_successful_login_count_24h()
1760 .await
1761 .unwrap_or(0),
1762 );
1763 metrics.insert("expired_tokens".to_string(), 0u64);
1764 Ok(metrics)
1765 }
1766
1767 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
1773 self.mfa_manager
1774 .sms
1775 .register_phone_number(user_id, phone_number)
1776 .await
1777 }
1778
1779 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1784 self.mfa_manager
1785 .backup_codes
1786 .generate_codes(user_id, count)
1787 .await
1788 }
1789 pub async fn grant_permission(
1801 &self,
1802 user_id: &str,
1803 action: &str,
1804 resource: &str,
1805 ) -> Result<()> {
1806 self.authorization_manager
1807 .grant_permission(user_id, action, resource)
1808 .await
1809 }
1810
1811 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
1821 self.mfa_manager.email.initiate_challenge(user_id).await
1822 }
1823
1824 pub fn storage(&self) -> Arc<dyn AuthStorage> {
1829 self.storage.clone()
1830 }
1831
1832 pub fn config(&self) -> &AuthConfig {
1834 &self.config
1835 }
1836
1837 pub async fn reset_authorization_runtime(&self) {
1839 self.authorization_manager.reset_runtime_state().await;
1840 }
1841
1842 pub async fn register_user(
1865 &self,
1866 username: &str,
1867 email: &str,
1868 password: &str,
1869 ) -> Result<String> {
1870 self.require_initialized()?;
1871 self.user_manager
1872 .register_user(username, email, password)
1873 .await
1874 }
1875
1876 #[deprecated(
1903 since = "0.6.0",
1904 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
1905 )]
1906 pub async fn list_users(
1907 &self,
1908 limit: Option<usize>,
1909 offset: Option<usize>,
1910 active_only: bool,
1911 ) -> Result<Vec<UserInfo>> {
1912 self.require_initialized()?;
1913 self.user_manager
1914 .list_users(limit, offset, active_only)
1915 .await
1916 }
1917
1918 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
1937 self.require_initialized()?;
1938 self.user_manager
1939 .list_users(
1940 query.get_limit(),
1941 query.get_offset(),
1942 query.get_active_only(),
1943 )
1944 .await
1945 }
1946
1947 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
1949 self.require_initialized()?;
1950 self.user_manager.get_user_info(user_id).await
1951 }
1952
1953 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
1955 self.require_initialized()?;
1956 self.user_manager.update_user_roles(user_id, roles).await
1957 }
1958
1959 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
1961 self.require_initialized()?;
1962 self.user_manager.set_user_active(user_id, active).await
1963 }
1964
1965 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
1967 self.require_initialized()?;
1968 self.user_manager.update_user_email(user_id, email).await
1969 }
1970
1971 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
1973 self.require_initialized()?;
1974 self.user_manager
1975 .verify_user_password(user_id, password)
1976 .await
1977 }
1978
1979 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
1981 self.user_manager.get_username_by_id(user_id).await
1982 }
1983
1984 pub async fn username_exists(&self, username: &str) -> Result<bool> {
1986 self.user_manager.username_exists(username).await
1987 }
1988
1989 pub async fn email_exists(&self, email: &str) -> Result<bool> {
1991 self.user_manager.email_exists(email).await
1992 }
1993
1994 pub async fn get_user_by_username(
1996 &self,
1997 username: &str,
1998 ) -> Result<HashMap<String, serde_json::Value>> {
1999 self.user_manager.get_user_by_username(username).await
2000 }
2001
2002 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2004 self.require_initialized()?;
2005 self.user_manager
2006 .update_user_password(username, new_password)
2007 .await
2008 }
2009
2010 pub async fn update_user_password_by_id(
2012 &self,
2013 user_id: &str,
2014 new_password: &str,
2015 ) -> Result<()> {
2016 self.require_initialized()?;
2017 self.user_manager
2018 .update_user_password_by_id(user_id, new_password)
2019 .await
2020 }
2021
2022 pub async fn delete_user(&self, username: &str) -> Result<()> {
2024 self.require_initialized()?;
2025 self.user_manager.delete_user(username).await
2026 }
2027
2028 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2030 self.require_initialized()?;
2031 self.user_manager.delete_user_by_id(user_id).await
2032 }
2033
2034 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2036 self.mfa_manager
2037 .verify_challenge_code(challenge, code)
2038 .await
2039 }
2040
2041 async fn log_audit_event(
2043 &self,
2044 event_type: &str,
2045 user_id: &str,
2046 method: &str,
2047 metadata: &CredentialMetadata,
2048 ) {
2049 if !self.config.audit.enabled {
2050 return;
2051 }
2052 let should_log = match event_type {
2053 "auth_success" | "mfa_required" => self.config.audit.log_success,
2054 "auth_failure" => self.config.audit.log_failures,
2055 _ => true,
2056 };
2057 if should_log {
2058 self.audit_manager
2059 .log_auth_trace_event(
2060 event_type,
2061 user_id,
2062 method,
2063 metadata.client_ip.as_deref().unwrap_or("unknown"),
2064 metadata.user_agent.as_deref().unwrap_or("unknown"),
2065 )
2066 .await;
2067 }
2068 }
2069
2070 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2072 self.mfa_manager.guard_and_store(challenge).await
2073 }
2074
2075 async fn mint_and_store_token(
2077 &self,
2078 user_id: &str,
2079 scopes: impl Into<crate::types::Scopes>,
2080 method: &str,
2081 lifetime: Option<Duration>,
2082 ) -> Result<AuthToken> {
2083 let token = self
2084 .token_manager
2085 .create_auth_token(user_id, scopes, method, lifetime)?;
2086 self.storage.store_token(&token).await?;
2087 Ok(token)
2088 }
2089
2090 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2092 self.session_manager.coordinate_distributed_sessions().await
2093 }
2094
2095 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2097 self.session_manager.synchronize_session(session_id).await
2098 }
2099
2100 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2102 self.monitoring_manager.clone()
2103 }
2104
2105 #[cfg(feature = "api-server")]
2107 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2108 Some(self.security_manager.clone())
2109 }
2110
2111 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2113 self.monitoring_manager.get_performance_metrics()
2114 }
2115
2116 pub async fn health_check(
2118 &self,
2119 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2120 self.monitoring_manager.health_check().await
2121 }
2122
2123 pub async fn export_prometheus_metrics(&self) -> String {
2125 self.monitoring_manager.export_prometheus_metrics().await
2126 }
2127 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2129 self.require_initialized()?;
2130 self.authorization_manager.create_role(role).await
2131 }
2132
2133 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2135 self.authorization_manager.list_roles().await
2136 }
2137
2138 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2140 self.authorization_manager.get_role(role_name).await
2141 }
2142
2143 pub async fn add_role_permission(
2145 &self,
2146 role_name: &str,
2147 permission: crate::permissions::Permission,
2148 ) -> Result<()> {
2149 self.authorization_manager
2150 .add_role_permission(role_name, permission)
2151 .await
2152 }
2153
2154 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2156 self.require_initialized()?;
2157 self.authorization_manager
2158 .assign_role(user_id, role_name)
2159 .await
2160 }
2161
2162 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2164 self.require_initialized()?;
2165 self.authorization_manager
2166 .remove_role(user_id, role_name)
2167 .await
2168 }
2169
2170 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2172 self.require_initialized()?;
2173 self.authorization_manager
2174 .set_role_inheritance(child_role, parent_role)
2175 .await
2176 }
2177
2178 pub async fn revoke_permission(
2180 &self,
2181 user_id: &str,
2182 action: &str,
2183 resource: &str,
2184 ) -> Result<()> {
2185 self.require_initialized()?;
2186 self.authorization_manager
2187 .revoke_permission(user_id, action, resource)
2188 .await
2189 }
2190
2191 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2193 self.authorization_manager
2194 .user_has_role(user_id, role_name)
2195 .await
2196 }
2197
2198 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2200 self.authorization_manager.list_user_roles(user_id).await
2201 }
2202
2203 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2205 self.authorization_manager
2206 .get_effective_permissions(user_id)
2207 .await
2208 }
2209
2210 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2212 self.authorization_manager
2213 .create_abac_policy(name, description)
2214 .await
2215 }
2216
2217 pub async fn map_user_attribute(
2238 &self,
2239 user_id: &str,
2240 attribute: &str,
2241 value: &str,
2242 ) -> Result<()> {
2243 self.authorization_manager
2244 .map_user_attribute(user_id, attribute, value)
2245 .await
2246 }
2247
2248 pub async fn get_user_attribute(
2272 &self,
2273 user_id: &str,
2274 attribute: &str,
2275 ) -> Result<Option<String>> {
2276 self.authorization_manager
2277 .get_user_attribute(user_id, attribute)
2278 .await
2279 }
2280
2281 pub async fn check_dynamic_permission(
2312 &self,
2313 user_id: &str,
2314 action: &str,
2315 resource: &str,
2316 context: std::collections::HashMap<String, String>,
2317 ) -> Result<bool> {
2318 self.authorization_manager
2319 .check_dynamic_permission(user_id, action, resource, context)
2320 .await
2321 }
2322
2323 pub async fn check_dynamic_permission_with_context(
2343 &self,
2344 user_id: &str,
2345 action: &str,
2346 resource: &str,
2347 context: PermissionContext,
2348 ) -> Result<bool> {
2349 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2350 .await
2351 }
2352
2353 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2355 self.authorization_manager.create_resource(resource).await
2356 }
2357
2358 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2377 self.authorization_manager
2378 .delegate_permission(
2379 req.delegator_id(),
2380 req.delegatee_id(),
2381 req.action(),
2382 req.resource(),
2383 req.get_duration(),
2384 )
2385 .await
2386 }
2387
2388 pub async fn delegate_permission(
2393 &self,
2394 delegator_id: &str,
2395 delegatee_id: &str,
2396 action: &str,
2397 resource: &str,
2398 duration: std::time::Duration,
2399 ) -> Result<()> {
2400 self.authorization_manager
2401 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2402 .await
2403 }
2404
2405 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2407 self.authorization_manager
2408 .get_active_delegations(user_id)
2409 .await
2410 }
2411
2412 pub async fn get_permission_audit_logs(
2414 &self,
2415 user_id: Option<&str>,
2416 action: Option<&str>,
2417 resource: Option<&str>,
2418 limit: Option<usize>,
2419 ) -> Result<Vec<String>> {
2420 self.audit_manager
2421 .get_permission_audit_logs(user_id, action, resource, limit)
2422 .await
2423 }
2424
2425 pub async fn get_permission_audit_logs_with_query(
2445 &self,
2446 query: AuditLogQuery,
2447 ) -> Result<Vec<String>> {
2448 self.audit_manager
2449 .get_permission_audit_logs(
2450 query.get_user_id(),
2451 query.get_action(),
2452 query.get_resource(),
2453 query.get_limit(),
2454 )
2455 .await
2456 }
2457
2458 pub async fn get_permission_metrics(
2460 &self,
2461 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2462 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2463 let permission_checks_last_hour = self
2464 .audit_manager
2465 .get_permission_checks_last_hour()
2466 .await
2467 .unwrap_or(0);
2468 self.authorization_manager
2469 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2470 .await
2471 }
2472
2473 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2475 let active_sessions = self
2476 .session_manager
2477 .count_active_sessions()
2478 .await
2479 .unwrap_or(0);
2480 self.audit_manager
2481 .get_security_audit_stats(active_sessions)
2482 .await
2483 }
2484
2485 pub async fn get_user_profile(
2487 &self,
2488 user_id: &str,
2489 ) -> Result<crate::providers::ProviderProfile> {
2490 self.user_manager.get_user_profile(user_id).await
2491 }
2492}
2493
2494pub use crate::audit::SecurityAuditStats;
2495
2496pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2497
2498#[derive(Debug, Clone, Default)]
2500pub struct AuthStats {
2501 pub registered_methods: Vec<String>,
2503
2504 pub active_sessions: u64,
2506
2507 pub active_mfa_challenges: u64,
2509
2510 pub tokens_issued: u64,
2512
2513 pub auth_attempts: u64,
2515}
2516
2517#[cfg(test)]
2518mod tests {
2519 use super::*;
2520 use crate::config::{AuthConfig, SecurityConfig};
2521 #[tokio::test]
2522 async fn test_framework_initialization() {
2523 let config = AuthConfig::new().security(SecurityConfig {
2524 min_password_length: 8,
2525 require_password_complexity: false,
2526 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2527 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2528 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2529 secure_cookies: false,
2530 cookie_same_site: crate::config::CookieSameSite::Lax,
2531 csrf_protection: false,
2532 session_timeout: Duration::from_secs(3600),
2533 previous_secret_key: None,
2534 });
2535 let mut framework = AuthFramework::new(config);
2536
2537 assert!(framework.initialize().await.is_ok());
2538 assert!(framework.initialized);
2539 }
2540
2541 #[tokio::test]
2542 async fn test_method_registration() {
2543 let config = AuthConfig::new().security(SecurityConfig {
2548 min_password_length: 8,
2549 require_password_complexity: false,
2550 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2551 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2552 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2553 secure_cookies: false,
2554 cookie_same_site: crate::config::CookieSameSite::Lax,
2555 csrf_protection: false,
2556 session_timeout: Duration::from_secs(3600),
2557 previous_secret_key: None,
2558 });
2559 let framework = AuthFramework::new(config);
2560
2561 assert!(!framework.initialized);
2563
2564 }
2567
2568 #[tokio::test]
2569 async fn test_token_validation() {
2570 let config = AuthConfig::new().security(SecurityConfig {
2571 min_password_length: 8,
2572 require_password_complexity: false,
2573 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2574 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2575 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2576 secure_cookies: false,
2577 cookie_same_site: crate::config::CookieSameSite::Lax,
2578 csrf_protection: false,
2579 session_timeout: Duration::from_secs(3600),
2580 previous_secret_key: None,
2581 });
2582 let mut framework = AuthFramework::new(config);
2583 framework.initialize().await.unwrap();
2584
2585 let token = framework
2586 .token_manager
2587 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2588 .unwrap();
2589
2590 framework.storage.store_token(&token).await.unwrap();
2592
2593 assert!(framework.validate_token(&token).await.unwrap());
2594 }
2595
2596 #[tokio::test]
2597 async fn test_session_management() {
2598 let config = AuthConfig::new().security(SecurityConfig {
2599 min_password_length: 8,
2600 require_password_complexity: false,
2601 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2602 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2603 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2604 secure_cookies: false,
2605 cookie_same_site: crate::config::CookieSameSite::Lax,
2606 csrf_protection: false,
2607 session_timeout: Duration::from_secs(3600),
2608 previous_secret_key: None,
2609 });
2610 let mut framework = AuthFramework::new(config);
2611 framework.initialize().await.unwrap();
2612
2613 let session_id = framework
2614 .create_session(
2615 "test-user",
2616 Duration::from_secs(3600),
2617 Some("192.168.1.1".to_string()),
2618 Some("Test Agent".to_string()),
2619 )
2620 .await
2621 .unwrap();
2622
2623 let session = framework.get_session(&session_id).await.unwrap();
2624 assert!(session.is_some());
2625
2626 framework.delete_session(&session_id).await.unwrap();
2627 let session = framework.get_session(&session_id).await.unwrap();
2628 assert!(session.is_none());
2629 }
2630
2631 #[tokio::test]
2632 async fn test_grouped_operations_accessors() {
2633 let config = AuthConfig::new().security(SecurityConfig {
2634 min_password_length: 8,
2635 require_password_complexity: false,
2636 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2637 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2638 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2639 secure_cookies: false,
2640 cookie_same_site: crate::config::CookieSameSite::Lax,
2641 csrf_protection: false,
2642 session_timeout: Duration::from_secs(3600),
2643 previous_secret_key: None,
2644 });
2645 let mut framework = AuthFramework::new(config);
2646 framework.initialize().await.unwrap();
2647
2648 let user_id = framework
2649 .users()
2650 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
2651 .await
2652 .unwrap();
2653 assert!(
2654 framework
2655 .users()
2656 .exists_by_username("grouped-user")
2657 .await
2658 .unwrap()
2659 );
2660
2661 let session_id = framework
2662 .sessions()
2663 .create(&user_id, Duration::from_secs(300), None, None)
2664 .await
2665 .unwrap();
2666 assert!(
2667 framework
2668 .sessions()
2669 .get(&session_id)
2670 .await
2671 .unwrap()
2672 .is_some()
2673 );
2674 assert_eq!(
2675 framework
2676 .sessions()
2677 .list_for_user(&user_id)
2678 .await
2679 .unwrap()
2680 .len(),
2681 1
2682 );
2683
2684 framework
2685 .authorization()
2686 .grant(&user_id, "read", "documents")
2687 .await
2688 .unwrap();
2689 let permissions = framework
2690 .authorization()
2691 .effective_permissions(&user_id)
2692 .await
2693 .unwrap();
2694 assert!(
2695 permissions
2696 .iter()
2697 .any(|permission| permission == "read:documents")
2698 );
2699
2700 framework.sessions().delete(&session_id).await.unwrap();
2701 assert!(
2702 framework
2703 .sessions()
2704 .get(&session_id)
2705 .await
2706 .unwrap()
2707 .is_none()
2708 );
2709 }
2710
2711 #[tokio::test]
2712 async fn test_cleanup_expired_data() {
2713 let config = AuthConfig::new().security(SecurityConfig {
2714 min_password_length: 8,
2715 require_password_complexity: false,
2716 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2717 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2718 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2719 secure_cookies: false,
2720 cookie_same_site: crate::config::CookieSameSite::Lax,
2721 csrf_protection: false,
2722 session_timeout: Duration::from_secs(3600),
2723 previous_secret_key: None,
2724 });
2725 let mut framework = AuthFramework::new(config);
2726 framework.initialize().await.unwrap();
2727
2728 assert!(framework.cleanup_expired_data().await.is_ok());
2730 }
2731
2732 #[cfg(feature = "redis-storage")]
2740 #[test]
2741 fn new_validated_redis_fails_closed_without_an_encryption_key() {
2742 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
2743 unsafe {
2746 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
2747 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
2748 }
2749
2750 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
2751 config.storage = crate::config::StorageConfig::Redis {
2752 url: "redis://127.0.0.1:1/".to_string(),
2753 key_prefix: "test:".to_string(),
2754 };
2755 let result = AuthFramework::new_validated(config);
2758 assert!(
2759 result.is_err(),
2760 "constructing with Redis storage and no encryption key configured must fail \
2761 closed, not silently build unwrapped (unencrypted) storage"
2762 );
2763 }
2764
2765 #[tokio::test]
2766 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
2767 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
2768 config.storage_encryption.require_wrapped_storage = true;
2769 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
2770 assert!(
2771 framework.initialize().await.is_err(),
2772 "caller-supplied unwrapped storage must be refused when wrapping is required"
2773 );
2774 }
2775
2776 #[tokio::test]
2777 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
2778 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
2779 required.storage_encryption.require_wrapped_storage = true;
2780 let wrapped: Arc<dyn AuthStorage> =
2781 Arc::new(crate::storage::encryption::EncryptedStorage::new(
2782 MemoryStorage::new(),
2783 crate::storage::encryption::StorageEncryption::new_random(),
2784 false,
2785 false,
2786 ));
2787 let mut framework = AuthFramework::new_with_storage(required, wrapped);
2788 framework.initialize().await.unwrap();
2789
2790 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
2792 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
2793 framework.initialize().await.unwrap();
2794 }
2795
2796 #[tokio::test]
2797 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
2798 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
2799 config.storage_encryption.require_wrapped_storage = true;
2800 let mut framework = AuthFramework::new(config);
2801 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
2803 framework.initialize().await.unwrap();
2804 }
2805}