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
238#[derive(Debug)]
240pub struct RefreshRedemption {
241 pub claims: crate::tokens::JwtClaims,
243 pub new_refresh_token: String,
245}
246
247pub(crate) async fn validate_access_jwt_with(
258 token_manager: &TokenManager,
259 storage: &dyn AuthStorage,
260 token: &str,
261 require_account: bool,
262 allow_client_bound: bool,
263) -> Result<crate::tokens::JwtClaims> {
264 let claims = token_manager.validate_jwt_token(token)?;
265 if claims.is_client_bound() && !allow_client_bound {
267 return Err(rejected(
268 "A client-bound token cannot be used here (it was issued to an OAuth client)",
269 ));
270 }
271 if claims.is_refresh_token() {
274 return Err(rejected(
275 "A refresh token cannot be used as an access token",
276 ));
277 }
278 if claims.token_use().is_some() {
279 return Err(rejected("This token is not an access token"));
280 }
281 match storage
282 .get_kv(&format!("revoked_token:{}", claims.jti))
283 .await
284 {
285 Ok(None) => {}
286 Ok(Some(_)) => return Err(rejected("Token has been revoked")),
287 Err(e) => {
288 tracing::error!("Could not check token revocation list: {}", e);
289 return Err(rejected("Unable to verify token status"));
290 }
291 }
292 ensure_account_active(storage, &claims.sub, require_account).await?;
293 Ok(claims)
294}
295
296pub(crate) async fn ensure_account_active(
300 storage: &dyn AuthStorage,
301 user_id: &str,
302 require_record: bool,
303) -> Result<()> {
304 match storage.get_kv(&format!("user:{user_id}")).await {
305 Ok(None) if require_record => Err(rejected("Unknown account")),
306 Ok(None) => match storage.get_kv(&format!("deleted_user:{user_id}")).await {
308 Ok(None) => Ok(()),
309 Ok(Some(_)) => Err(rejected("Account has been deleted")),
310 Err(e) => {
311 tracing::error!("Could not read account tombstone: {}", e);
312 Err(rejected("Unable to verify account status"))
313 }
314 },
315 Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
316 Ok(record) if record["active"].as_bool().unwrap_or(true) => Ok(()),
317 Ok(_) => Err(rejected("Account has been deactivated")),
318 Err(_) => Err(rejected("Unable to verify account status")),
319 },
320 Err(e) => {
321 tracing::error!("Could not read account record: {}", e);
322 Err(rejected("Unable to verify account status"))
323 }
324 }
325}
326
327pub(crate) fn token_value_matches_jwt(token_manager: &TokenManager, token: &AuthToken) -> bool {
331 if !(token.auth_method == "jwt" || token.access_token.contains('.')) {
332 return true;
333 }
334 token_manager
335 .validate_jwt_token(&token.access_token)
336 .map(|claims| {
337 claims.sub == token.user_id
338 && claims.token_use().is_none()
341 && claims.client_id == token.client_id
342 })
343 .unwrap_or(false)
344}
345
346pub(crate) async fn access_token_is_revoked(
349 token_manager: &TokenManager,
350 storage: &dyn AuthStorage,
351 token: &AuthToken,
352) -> Result<bool> {
353 let jti = token_manager
354 .validate_jwt_token(&token.access_token)
355 .map(|claims| claims.jti)
356 .unwrap_or_else(|_| token.token_id.clone());
357 Ok(storage
358 .get_kv(&format!("revoked_token:{jti}"))
359 .await?
360 .is_some())
361}
362
363fn rejected(message: &str) -> AuthError {
364 AuthError::Token(crate::errors::TokenError::Invalid {
365 message: message.to_string(),
366 })
367}
368
369impl AuthFramework {
370 pub fn users(&self) -> UserOperations<'_> {
372 UserOperations { framework: self }
373 }
374
375 pub fn sessions(&self) -> SessionOperations<'_> {
377 SessionOperations { framework: self }
378 }
379
380 pub fn tokens(&self) -> TokenOperations<'_> {
382 TokenOperations { framework: self }
383 }
384
385 pub fn authorization(&self) -> AuthorizationOperations<'_> {
387 AuthorizationOperations { framework: self }
388 }
389
390 pub fn mfa(&self) -> MfaOperations<'_> {
392 MfaOperations { framework: self }
393 }
394
395 pub fn monitoring(&self) -> MonitoringOperations<'_> {
397 MonitoringOperations { framework: self }
398 }
399
400 pub fn audit(&self) -> AuditOperations<'_> {
402 AuditOperations { framework: self }
403 }
404
405 pub fn maintenance(&self) -> MaintenanceOperations<'_> {
407 MaintenanceOperations { framework: self }
408 }
409
410 pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
412 self.runtime_config.read().await.clone()
413 }
414
415 #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
416 #[doc(hidden)]
417 pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
418 self.runtime_config().await
419 }
420
421 pub async fn update_runtime_config(
426 &self,
427 update: crate::config::RuntimeConfig,
428 ) -> Result<crate::config::RuntimeConfig> {
429 if update.token_lifetime_secs == 0 {
431 return Err(AuthError::config("token_lifetime_secs must be > 0"));
432 }
433 if update.refresh_token_lifetime_secs == 0 {
434 return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
435 }
436 if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
437 return Err(AuthError::config(
438 "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
439 ));
440 }
441 if update.min_password_length == 0 {
442 return Err(AuthError::config("min_password_length must be > 0"));
443 }
444 let mut cfg = self.runtime_config.write().await;
445 *cfg = update.clone();
446 Ok(update)
447 }
448
449 pub fn admin(&self) -> AdminOperations<'_> {
451 AdminOperations { framework: self }
452 }
453
454 pub fn new(config: AuthConfig) -> Self {
462 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
464 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
465 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
466
467 let ephemeral_secret = {
473 let rng = ring::rand::SystemRandom::new();
474 let mut buf = [0u8; 32];
475 ring::rand::SecureRandom::fill(&rng, &mut buf)
476 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
477 buf
478 };
479 let token_manager =
480 TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
481
482 let user_manager = crate::auth_modular::user_manager::UserManager::new(
483 storage.clone(),
484 config.security.password_hash_algorithm.clone(),
485 );
486 let session_manager =
487 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
488 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
489 let authorization_manager =
490 crate::auth_modular::authorization_manager::AuthorizationManager::new(
491 Arc::new(RwLock::new(PermissionChecker::new())),
492 storage.clone(),
493 );
494
495 Self {
496 config,
497 methods: HashMap::new(),
498 token_manager,
499 storage,
500 authorization_manager,
501 rate_limiter: None, monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
503 crate::monitoring::MonitoringConfig::default(),
504 )),
505 audit_manager,
506 #[cfg(feature = "api-server")]
507 security_manager: Arc::new(crate::api::SecurityManager::new()),
508 runtime_config: Arc::new(tokio::sync::RwLock::new(
509 crate::config::RuntimeConfig::default(),
510 )),
511 user_manager,
512 session_manager,
513 mfa_manager,
514 initialized: false,
515 storage_overridden: false,
516 storage_from_caller: false,
517 }
518 }
519
520 pub fn new_validated(config: AuthConfig) -> Result<Self> {
525 config.validate().map_err(|e| {
527 AuthError::configuration(format!("Configuration validation failed: {}", e))
528 })?;
529
530 let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
532
533 let mut token_manager =
534 TokenManager::new_hmac(¤t_secret_bytes, "auth-framework", "auth-framework");
535
536 if let Some(prev_secret) = &config.security.previous_secret_key {
538 token_manager =
540 TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
541 token_manager.rotate_hmac_key(¤t_secret_bytes);
542 }
543
544 let storage: Arc<dyn AuthStorage> = match &config.storage {
553 #[cfg(feature = "redis-storage")]
554 crate::config::StorageConfig::Redis { url, key_prefix } => {
555 let redis: Arc<dyn AuthStorage> = Arc::new(
556 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
557 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
558 })?,
559 );
560 crate::storage::factory::wrap_with_encryption_if_enabled(
561 redis,
562 &config.storage_encryption,
563 )?
564 }
565 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
566 };
567
568 let rate_limiter = if config.rate_limiting.enabled {
570 Some(RateLimiter::new(
571 config.rate_limiting.max_requests,
572 config.rate_limiting.window,
573 ))
574 } else {
575 None
576 };
577
578 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
580 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
581
582 let user_manager = crate::auth_modular::user_manager::UserManager::new(
583 storage.clone(),
584 config.security.password_hash_algorithm.clone(),
585 );
586 let session_manager =
587 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
588 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
589 let authorization_manager =
590 crate::auth_modular::authorization_manager::AuthorizationManager::new(
591 Arc::new(RwLock::new(PermissionChecker::new())),
592 storage.clone(),
593 );
594
595 Ok(Self {
596 config: config.clone(),
597 methods: HashMap::new(),
598 token_manager,
599 storage,
600 authorization_manager,
601 rate_limiter,
602 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
603 crate::monitoring::MonitoringConfig::default(),
604 )),
605 audit_manager,
606 #[cfg(feature = "api-server")]
607 security_manager: Arc::new(crate::api::SecurityManager::new()),
608 runtime_config: Arc::new(tokio::sync::RwLock::new(
609 crate::config::RuntimeConfig::from_auth_config(&config),
610 )),
611 user_manager,
612 session_manager,
613 mfa_manager,
614 initialized: false,
615 storage_overridden: false,
616 storage_from_caller: false,
617 })
618 }
619
620 pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
627 self.storage = storage.clone();
628 self.user_manager = crate::auth_modular::user_manager::UserManager::new(
629 storage.clone(),
630 self.config.security.password_hash_algorithm.clone(),
631 );
632 self.session_manager =
633 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
634 self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
635 self.authorization_manager =
636 crate::auth_modular::authorization_manager::AuthorizationManager::new(
637 Arc::new(RwLock::new(PermissionChecker::new())),
638 storage,
639 );
640 self.storage_overridden = true;
641 self.storage_from_caller = true;
642 }
643
644 pub(crate) fn replace_storage_from_factory(
648 &mut self,
649 storage: std::sync::Arc<dyn AuthStorage>,
650 ) {
651 self.replace_storage(storage);
652 self.storage_from_caller = false;
653 }
654
655 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
662 self.session_manager.set_distributed_store(store);
663 }
664
665 pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
667 let mut framework = Self::new(config);
668 framework.replace_storage(storage);
669 framework
670 }
671
672 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
674 let name = name.into();
675 info!("Registering authentication method: {}", name);
676
677 if let Err(e) = method.validate_config() {
679 error!("Method '{}' configuration validation failed: {}", name, e);
680 return;
681 }
682
683 self.methods.insert(name, method);
684 }
685
686 fn require_initialized(&self) -> Result<()> {
692 if self.initialized {
693 Ok(())
694 } else {
695 Err(AuthError::configuration(
696 "Framework not initialized. Call `initialize().await` first, \
697 or use `AuthFramework::builder().build().await` which initializes automatically.",
698 ))
699 }
700 }
701
702 pub async fn initialize(&mut self) -> Result<()> {
712 if self.initialized {
713 return Ok(());
714 }
715
716 info!("Initializing authentication framework");
717
718 self.config.validate().map_err(|e| {
720 AuthError::configuration(format!("Configuration validation failed: {}", e))
721 })?;
722
723 let token_manager = match resolve_jwt_secret_bytes(&self.config) {
725 Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
726 Err(_) => {
727 if Self::is_production_environment() {
728 return Err(AuthError::configuration(
729 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
730 Generate a secure secret with: openssl rand -base64 32\n\
731 Set it with: export JWT_SECRET=\"your-secret-here\"",
732 ));
733 }
734 warn!("No JWT secret configured, using development-only default");
735 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
736 warn!("This configuration is NOT SECURE and should only be used in development!");
737 self.token_manager.clone()
738 }
739 };
740
741 self.token_manager = token_manager;
743
744 if self.storage_from_caller {
748 crate::storage::factory::check_overridden_storage(
749 &self.storage,
750 &self.config.storage_encryption,
751 )?;
752 }
753
754 if !self.storage_overridden {
756 let storage = crate::storage::factory::build_storage_backend_with_encryption(
757 &self.config.storage,
758 None,
759 &self.config.storage_encryption,
760 )
761 .await?;
762 self.replace_storage(storage);
763 self.storage_overridden = false;
764 self.storage_from_caller = false;
765 }
766
767 if self.config.rate_limiting.enabled {
769 self.rate_limiter = Some(RateLimiter::new(
770 self.config.rate_limiting.max_requests,
771 self.config.rate_limiting.window,
772 ));
773 }
774
775 self.authorization_manager.create_default_roles().await;
777
778 self.authorization_manager.load_persisted_roles().await?;
780
781 self.cleanup_expired_data().await?;
783
784 self.initialized = true;
785 info!("Authentication framework initialized successfully");
786
787 Ok(())
788 }
789
790 pub async fn authenticate(
818 &self,
819 method_name: &str,
820 credential: Credential,
821 ) -> Result<AuthResult> {
822 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
823 .await
824 }
825
826 pub async fn authenticate_with_metadata(
828 &self,
829 method_name: &str,
830 credential: Credential,
831 metadata: CredentialMetadata,
832 ) -> Result<AuthResult> {
833 use std::time::Instant;
834 use tokio::time::{Duration as TokioDuration, sleep};
835
836 let start_time = Instant::now();
837
838 self.monitoring_manager.record_auth_request().await;
840
841 self.require_initialized()?;
842
843 let result = self
845 .authenticate_internal(method_name, credential, metadata)
846 .await;
847
848 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
851 if elapsed < min_duration {
852 sleep(min_duration - elapsed).await;
853 }
854
855 if let Ok(ref auth_result) = result {
857 match auth_result {
858 AuthResult::Success(token) => {
859 self.monitoring_manager
860 .record_auth_success(&token.user_id, elapsed)
861 .await;
862 }
863 AuthResult::Failure(reason) => {
864 self.monitoring_manager
865 .record_auth_failure(None, reason)
866 .await;
867 }
868 _ => {} }
870 }
871
872 result
873 }
874
875 async fn authenticate_internal(
877 &self,
878 method_name: &str,
879 credential: Credential,
880 metadata: CredentialMetadata,
881 ) -> Result<AuthResult> {
882 if let Some(ref rate_limiter) = self.rate_limiter {
884 let rate_key = format!(
885 "auth:{}:{}",
886 method_name,
887 metadata.client_ip.as_deref().unwrap_or("unknown")
888 );
889
890 if !rate_limiter.is_allowed(&rate_key) {
891 warn!(
892 "Rate limit exceeded for method '{}' from IP {:?}",
893 method_name, metadata.client_ip
894 );
895 return Err(AuthError::rate_limit("Too many authentication attempts"));
896 }
897 }
898
899 if method_name == "password"
903 && let Credential::Password {
904 ref username,
905 ref password,
906 } = credential
907 {
908 return self
909 .authenticate_password_builtin(username, password, &metadata)
910 .await;
911 }
912
913 if method_name == "jwt" {
914 return match credential {
915 Credential::Jwt { token } | Credential::Bearer { token } => {
916 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
917 .await
918 }
919 _ => Ok(AuthResult::Failure(
920 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
921 )),
922 };
923 }
924
925 if matches!(method_name, "api_key" | "api-key") {
926 return match credential {
927 Credential::ApiKey { key } => {
928 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
929 .await
930 }
931 _ => Ok(AuthResult::Failure(
932 "API key authentication expects Credential::api_key".to_string(),
933 )),
934 };
935 }
936
937 if method_name == "oauth2" {
938 return self
939 .authenticate_oauth2_builtin(credential, &metadata)
940 .await;
941 }
942
943 let method = self.methods.get(method_name).ok_or_else(|| {
945 AuthError::auth_method(method_name, "Authentication method not found".to_string())
946 })?;
947
948 debug!(
950 "Authentication attempt with method '{}' for credential: {}",
951 method_name,
952 credential.safe_display()
953 );
954
955 let result = method.authenticate(credential, metadata.clone()).await?;
957
958 match &result {
960 MethodResult::Success(token) => {
961 info!(
962 "Authentication successful for user '{}' with method '{}'",
963 token.user_id, method_name
964 );
965
966 self.storage.store_token(token).await?;
968
969 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
971 .await;
972
973 Ok(AuthResult::Success(token.clone()))
974 }
975
976 MethodResult::MfaRequired(challenge) => {
977 info!(
978 "MFA required for user '{}' with method '{}'",
979 challenge.user_id, method_name
980 );
981
982 self.guard_and_store_mfa_challenge((**challenge).clone())
984 .await?;
985
986 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
988 .await;
989
990 Ok(AuthResult::MfaRequired(challenge.clone()))
991 }
992
993 MethodResult::Failure { reason } => {
994 warn!(
995 "Authentication failed for method '{}': {}",
996 method_name, reason
997 );
998
999 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
1001 .await;
1002
1003 Ok(AuthResult::Failure(reason.clone()))
1004 }
1005 }
1006 }
1007
1008 async fn authenticate_jwt_builtin(
1009 &self,
1010 token: &str,
1011 metadata: &CredentialMetadata,
1012 auth_method: &str,
1013 ) -> Result<AuthResult> {
1014 if token.is_empty() {
1015 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
1016 }
1017
1018 match validate_access_jwt_with(
1019 &self.token_manager,
1020 self.storage.as_ref(),
1021 token,
1022 false,
1023 false,
1024 )
1025 .await
1026 {
1027 Ok(claims) => {
1028 let token =
1029 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
1030 Ok(AuthResult::Success(Box::new(token)))
1031 }
1032 Err(error) => {
1033 if let Some(reason) = Self::credential_failure_reason(&error) {
1034 Ok(AuthResult::Failure(reason))
1035 } else {
1036 Err(error)
1037 }
1038 }
1039 }
1040 }
1041
1042 async fn authenticate_api_key_builtin(
1043 &self,
1044 api_key: &str,
1045 metadata: &CredentialMetadata,
1046 auth_method: &str,
1047 ) -> Result<AuthResult> {
1048 if api_key.is_empty() {
1049 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
1050 }
1051
1052 match self.validate_api_key(api_key).await {
1053 Ok(user) => {
1054 let scopes: Vec<String> = if user.roles.is_empty() {
1055 vec!["api_user".to_string()]
1056 } else {
1057 user.roles.to_vec()
1058 };
1059 let mut token = self
1060 .token_manager
1061 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
1062 .with_roles(user.roles)
1063 .with_scopes(scopes);
1064 token.metadata.issued_ip = metadata.client_ip.clone();
1065 token.metadata.user_agent = metadata.user_agent.clone();
1066 Ok(AuthResult::Success(Box::new(token)))
1067 }
1068 Err(error) => {
1069 if let Some(reason) = Self::credential_failure_reason(&error) {
1070 Ok(AuthResult::Failure(reason))
1071 } else {
1072 Err(error)
1073 }
1074 }
1075 }
1076 }
1077
1078 async fn authenticate_oauth2_builtin(
1079 &self,
1080 credential: Credential,
1081 metadata: &CredentialMetadata,
1082 ) -> Result<AuthResult> {
1083 match credential {
1084 Credential::OAuth {
1085 authorization_code, ..
1086 } => {
1087 if authorization_code.is_empty() {
1088 return Ok(AuthResult::Failure(
1089 "OAuth authorization code cannot be empty".to_string(),
1090 ));
1091 }
1092 Ok(AuthResult::Failure(
1093 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
1094 .to_string(),
1095 ))
1096 }
1097 Credential::OAuthRefresh { refresh_token } => {
1098 if refresh_token.is_empty() {
1099 return Ok(AuthResult::Failure(
1100 "OAuth refresh token cannot be empty".to_string(),
1101 ));
1102 }
1103 Ok(AuthResult::Failure(
1104 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
1105 .to_string(),
1106 ))
1107 }
1108 Credential::Jwt { token }
1109 | Credential::Bearer { token }
1110 | Credential::OpenIdConnect { id_token: token, .. } => {
1111 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
1112 }
1113 _ => Ok(AuthResult::Failure(
1114 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
1115 .to_string(),
1116 )),
1117 }
1118 }
1119
1120 fn build_validated_jwt_auth_token(
1121 raw_token: &str,
1122 claims: crate::tokens::JwtClaims,
1123 metadata: &CredentialMetadata,
1124 auth_method: &str,
1125 ) -> AuthToken {
1126 let crate::tokens::JwtClaims {
1127 sub,
1128 iss,
1129 exp,
1130 iat,
1131 jti,
1132 scope,
1133 permissions,
1134 roles,
1135 client_id,
1136 ..
1137 } = claims;
1138
1139 let now = chrono::Utc::now();
1140 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
1141 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
1142 .unwrap_or(now + chrono::Duration::hours(1));
1143 let lifetime = (expires_at - now)
1144 .to_std()
1145 .unwrap_or_else(|_| Duration::from_secs(1));
1146 let scopes = if scope.trim().is_empty() {
1147 Vec::new()
1148 } else {
1149 scope.split_whitespace().map(str::to_string).collect()
1150 };
1151
1152 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
1153 .with_scopes(scopes)
1154 .with_permissions(permissions.unwrap_or_default())
1155 .with_roles(roles.unwrap_or_default());
1156 token.token_id = jti;
1157 token.subject = Some(sub);
1158 token.issuer = Some(iss);
1159 token.issued_at = issued_at;
1160 token.expires_at = expires_at;
1161 token.metadata.issued_ip = metadata.client_ip.clone();
1162 token.metadata.user_agent = metadata.user_agent.clone();
1163 if let Some(client_id) = client_id {
1164 token.client_id = Some(client_id);
1165 }
1166 token
1167 }
1168
1169 fn credential_failure_reason(error: &AuthError) -> Option<String> {
1170 match error {
1171 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
1172 AuthError::Validation { message } => Some(message.clone()),
1173 AuthError::UserNotFound => Some("User not found".to_string()),
1174 _ => None,
1175 }
1176 }
1177
1178 async fn authenticate_password_builtin(
1180 &self,
1181 username: &str,
1182 password: &str,
1183 metadata: &CredentialMetadata,
1184 ) -> Result<AuthResult> {
1185 use crate::auth_modular::user_manager::CredentialCheckResult;
1186
1187 if username.is_empty() || password.is_empty() {
1188 return Ok(AuthResult::Failure(
1189 "Username or password cannot be empty".to_string(),
1190 ));
1191 }
1192
1193 match self
1194 .user_manager
1195 .verify_login_credentials(username, password)
1196 .await?
1197 {
1198 None => {
1199 self.log_audit_event("auth_failure", "unknown", "password", metadata)
1200 .await;
1201 Ok(AuthResult::Failure(
1202 "Invalid username or password".to_string(),
1203 ))
1204 }
1205 Some(CredentialCheckResult {
1206 ref user_id,
1207 mfa_enabled: true,
1208 }) => {
1209 let now = chrono::Utc::now();
1210 let challenge = MfaChallenge {
1211 id: crate::utils::string::generate_id(Some("mfa")),
1212 mfa_type: crate::methods::MfaType::MultiMethod,
1213 user_id: user_id.clone(),
1214 created_at: now,
1215 expires_at: now + chrono::Duration::minutes(5),
1216 attempts: 0,
1217 max_attempts: 5,
1218 code_hash: None,
1219 message: Some(
1220 "Provide your current TOTP code or a backup code to complete login"
1221 .to_string(),
1222 ),
1223 data: HashMap::new(),
1224 };
1225 self.guard_and_store_mfa_challenge(challenge.clone())
1226 .await?;
1227 self.log_audit_event("mfa_required", user_id, "password", metadata)
1228 .await;
1229 info!(
1230 "Built-in password authentication requires MFA for user: {}",
1231 username
1232 );
1233 Ok(AuthResult::MfaRequired(Box::new(challenge)))
1234 }
1235 Some(CredentialCheckResult {
1236 ref user_id,
1237 mfa_enabled: false,
1238 }) => {
1239 let token = self
1240 .mint_and_store_token(
1241 user_id,
1242 vec!["read".to_string(), "write".to_string()],
1243 "password",
1244 None,
1245 )
1246 .await?;
1247 self.monitoring_manager.record_auth_request().await;
1248 self.log_audit_event("auth_success", user_id, "password", metadata)
1249 .await;
1250 info!(
1251 "Built-in password authentication successful for user: {}",
1252 username
1253 );
1254 Ok(AuthResult::Success(Box::new(token)))
1255 }
1256 }
1257 }
1258
1259 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1261 debug!("Completing MFA for challenge '{}'", challenge.id);
1262
1263 let stored_challenge = self
1266 .mfa_manager
1267 .begin_attempt(&challenge.id)
1268 .await?
1269 .ok_or(MfaError::ChallengeExpired)?;
1270
1271 if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1272 if stored_challenge.attempts >= stored_challenge.max_attempts {
1273 self.mfa_manager.remove_challenge(&challenge.id).await?;
1274 }
1275 return Err(MfaError::InvalidCode.into());
1276 }
1277
1278 self.mfa_manager.remove_challenge(&challenge.id).await?;
1279
1280 let user_id = stored_challenge.user_id.as_str();
1281 let scopes = self
1282 .user_manager
1283 .get_user_roles(user_id)
1284 .await
1285 .unwrap_or_else(|_| vec!["user".to_string()]);
1286
1287 let token = self
1288 .mint_and_store_token(user_id, scopes, "mfa", None)
1289 .await?;
1290
1291 info!("MFA completed successfully for user '{}'", user_id);
1292 Ok(token)
1293 }
1294
1295 pub async fn mfa_challenge_owner(&self, challenge_id: &str) -> Option<String> {
1297 self.mfa_manager
1298 .get_challenge(challenge_id)
1299 .await
1300 .ok()
1301 .flatten()
1302 .map(|c| c.user_id)
1303 }
1304
1305 pub(crate) async fn discard_mfa_challenge(&self, challenge_id: &str) {
1307 let _ = self.mfa_manager.remove_challenge(challenge_id).await;
1308 }
1309
1310 pub async fn complete_mfa_by_id(
1312 &self,
1313 challenge_id: &str,
1314 mfa_code: &str,
1315 ) -> Result<AuthToken> {
1316 let challenge = self
1317 .mfa_manager
1318 .get_challenge(challenge_id)
1319 .await?
1320 .ok_or(MfaError::ChallengeExpired)?;
1321
1322 self.complete_mfa(challenge, mfa_code).await
1323 }
1324
1325 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1327 self.require_initialized()?;
1328 let valid = token.is_valid()
1329 && self.token_manager.validate_auth_token(token).is_ok()
1330 && token_value_matches_jwt(&self.token_manager, token)
1331 && !access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token).await?
1332 && self.touch_stored_token(token).await?;
1333 self.monitoring_manager.record_token_validation(valid).await;
1334 Ok(valid)
1335 }
1336
1337 async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1338 let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1339 return Ok(false);
1340 };
1341 if stored.is_revoked() {
1342 return Ok(false);
1343 }
1344 if stored.access_token != token.access_token || stored.user_id != token.user_id {
1346 return Ok(false);
1347 }
1348 stored.mark_used();
1349 self.storage.update_token(&stored).await?;
1350 Ok(true)
1351 }
1352
1353 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1355 if !self.validate_token(token).await? {
1356 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1357 }
1358
1359 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1360
1361 match self.user_manager.get_user_info(&token_info.user_id).await {
1364 Ok(mut info) => {
1365 if !token_info.attributes.is_empty() {
1367 let string_attrs: HashMap<String, String> = token_info
1368 .attributes
1369 .into_iter()
1370 .map(|(k, v)| {
1371 (
1372 k,
1373 v.as_str()
1374 .map(|s| s.to_string())
1375 .unwrap_or_else(|| v.to_string()),
1376 )
1377 })
1378 .collect();
1379 info.attributes = string_attrs.into();
1380 }
1381 Ok(info)
1382 }
1383 Err(_) => {
1384 let string_attrs: HashMap<String, String> = token_info
1385 .attributes
1386 .into_iter()
1387 .map(|(k, v)| {
1388 (
1389 k,
1390 v.as_str()
1391 .map(|s| s.to_string())
1392 .unwrap_or_else(|| v.to_string()),
1393 )
1394 })
1395 .collect();
1396 Ok(UserInfo {
1397 id: token_info.user_id,
1398 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1399 email: token_info.email,
1400 name: token_info.name,
1401 roles: token_info.roles.into(),
1402 active: false,
1403 email_verified: false,
1404 attributes: string_attrs.into(),
1405 })
1406 }
1407 }
1408 }
1409
1410 pub async fn check_permission(
1437 &self,
1438 token: &AuthToken,
1439 action: &str,
1440 resource: &str,
1441 ) -> Result<bool> {
1442 if !self.validate_token(token).await? {
1443 return Ok(false);
1444 }
1445 self.authorization_manager
1446 .check_token_permission(token, action, resource)
1447 .await
1448 }
1449
1450 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1452 self.require_initialized()?;
1453 debug!("Refreshing token for user '{}'", token.user_id);
1454
1455 if let Some(method) = self.methods.get(&token.auth_method)
1457 && method.supports_refresh()
1458 && let Some(ref refresh_token) = token.refresh_token
1459 {
1460 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1461 self.storage.store_token(&new_token).await?;
1462 return Ok(new_token);
1463 }
1464
1465 if !self.validate_token(token).await? {
1469 return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1470 message: "Cannot refresh a token that is not valid".to_string(),
1471 }));
1472 }
1473 let stored = self
1475 .storage
1476 .get_token(&token.token_id)
1477 .await?
1478 .ok_or_else(|| {
1479 AuthError::Token(crate::errors::TokenError::Invalid {
1480 message: "Cannot refresh a token that is not stored".to_string(),
1481 })
1482 })?;
1483 let new_token = self.token_manager.refresh_token(&stored)?;
1484 self.storage.store_token(&new_token).await?;
1485
1486 info!("Token refreshed for user '{}'", token.user_id);
1487
1488 Ok(new_token)
1489 }
1490
1491 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1493 self.require_initialized()?;
1494 debug!("Revoking token for user '{}'", token.user_id);
1495
1496 let mut revoked_token = token.clone();
1498 revoked_token.revoke(Some("Manual revocation".to_string()));
1499
1500 self.storage.update_token(&revoked_token).await?;
1502
1503 let jti = self
1506 .token_manager
1507 .validate_jwt_token(&token.access_token)
1508 .map(|claims| claims.jti)
1509 .unwrap_or_else(|_| token.token_id.clone());
1510 let remaining = (token.expires_at - chrono::Utc::now())
1511 .to_std()
1512 .unwrap_or_default()
1513 .max(Duration::from_secs(60));
1514 self.storage
1515 .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1516 .await?;
1517
1518 info!("Token revoked for user '{}'", token.user_id);
1519
1520 Ok(())
1521 }
1522
1523 pub async fn create_api_key(
1525 &self,
1526 user_id: &str,
1527 expires_in: Option<Duration>,
1528 ) -> Result<String> {
1529 self.require_initialized()?;
1530 self.user_manager.create_api_key(user_id, expires_in).await
1531 }
1532
1533 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1535 self.require_initialized()?;
1536 self.user_manager.validate_api_key(api_key).await
1537 }
1538
1539 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1541 self.require_initialized()?;
1542 self.user_manager.revoke_api_key(api_key).await
1543 }
1544
1545 pub async fn create_session(
1547 &self,
1548 user_id: &str,
1549 expires_in: Duration,
1550 ip_address: Option<String>,
1551 user_agent: Option<String>,
1552 ) -> Result<String> {
1553 self.require_initialized()?;
1554 let (session_id, new_total) = self
1555 .session_manager
1556 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1557 .await?;
1558 self.monitoring_manager
1559 .update_session_count(new_total)
1560 .await;
1561 Ok(session_id)
1562 }
1563
1564 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1584 self.create_session(
1585 req.get_user_id(),
1586 req.get_expires_in(),
1587 req.get_ip_address().map(|s| s.to_string()),
1588 req.get_user_agent().map(|s| s.to_string()),
1589 )
1590 .await
1591 }
1592
1593 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1595 self.require_initialized()?;
1596 self.session_manager.get_session(session_id).await
1597 }
1598
1599 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1601 self.require_initialized()?;
1602 self.session_manager.delete_session(session_id).await?;
1603
1604 let remaining = self
1605 .session_manager
1606 .count_active_sessions()
1607 .await
1608 .unwrap_or(0);
1609 self.monitoring_manager
1610 .update_session_count(remaining)
1611 .await;
1612
1613 Ok(())
1614 }
1615
1616 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1618 self.require_initialized()?;
1619 self.storage.list_user_tokens(user_id).await
1620 }
1621
1622 pub async fn cleanup_expired_data(&self) -> Result<()> {
1624 debug!("Cleaning up expired data");
1625
1626 self.storage.cleanup_expired().await?;
1628
1629 self.mfa_manager.cleanup_expired_challenges().await?;
1631
1632 self.session_manager.cleanup_expired_sessions().await?;
1634
1635 if let Some(ref rate_limiter) = self.rate_limiter {
1637 let _ = rate_limiter.cleanup().ok();
1638 }
1639
1640 Ok(())
1641 }
1642
1643 fn is_production_environment() -> bool {
1646 if let Ok(env) = std::env::var("ENVIRONMENT")
1647 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1648 {
1649 return true;
1650 }
1651 if let Ok(env) = std::env::var("ENV")
1652 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1653 {
1654 return true;
1655 }
1656 if let Ok(env) = std::env::var("NODE_ENV")
1657 && env.to_lowercase() == "production"
1658 {
1659 return true;
1660 }
1661 if let Ok(env) = std::env::var("RUST_ENV")
1662 && env.to_lowercase() == "production"
1663 {
1664 return true;
1665 }
1666 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1667 || std::env::var("DOCKER_CONTAINER").is_ok()
1668 }
1669
1670 pub async fn get_stats(&self) -> Result<AuthStats> {
1672 let mut stats = AuthStats::default();
1673
1674 if let Err(e) = self.storage.cleanup_expired().await {
1675 warn!("Failed to cleanup expired data: {}", e);
1676 }
1677 if let Some(rate_limiter) = &self.rate_limiter {
1678 let _ = rate_limiter.cleanup().ok();
1679 }
1680
1681 let active_sessions = self
1682 .session_manager
1683 .count_active_sessions()
1684 .await
1685 .unwrap_or(0) as u32;
1686
1687 stats.registered_methods = self.methods.keys().cloned().collect();
1688 stats.active_sessions = active_sessions as u64;
1689 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1690 let perf = self.monitoring_manager.get_performance_metrics();
1692 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1693 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1694 + perf.get("auth_failures").copied().unwrap_or(0);
1695
1696 Ok(stats)
1697 }
1698
1699 pub fn token_manager(&self) -> &TokenManager {
1704 &self.token_manager
1705 }
1706
1707 pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1714 let claims = self.token_manager.validate_jwt_token(token)?;
1715 if !claims.is_refresh_token() {
1716 return Err(rejected("Expected a refresh token"));
1717 }
1718 let read = |key: String| async move {
1719 self.storage.get_kv(&key).await.map_err(|e| {
1720 tracing::error!("Could not read refresh-token state: {}", e);
1721 rejected("Unable to verify token status")
1722 })
1723 };
1724 let family = claims.refresh_family().to_string();
1725 if read(format!("revoked_token:{}", claims.jti))
1726 .await?
1727 .is_some()
1728 || read(format!("revoked_family:{family}")).await?.is_some()
1729 {
1730 return Err(rejected("Refresh token has been revoked"));
1731 }
1732 ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1733
1734 let remaining =
1735 Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1736 let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1738 let consumed_key = format!("refresh_consumed:{}", claims.jti);
1739 let first_use = self
1745 .storage
1746 .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1747 .await
1748 .map_err(|e| {
1749 tracing::error!("Could not record refresh token use: {}", e);
1750 rejected("Unable to record refresh token use")
1751 })?;
1752 if !first_use {
1753 warn!(
1754 "Refresh token reuse detected for user '{}'; revoking its chain",
1755 claims.sub
1756 );
1757 if let Err(e) = self
1758 .storage
1759 .store_kv(
1760 &format!("revoked_family:{family}"),
1761 b"reuse",
1762 Some(family_ttl),
1763 )
1764 .await
1765 {
1766 tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1767 }
1768 return Err(rejected("Refresh token has already been used"));
1769 }
1770
1771 let lifetime = self.config.refresh_token_lifetime;
1772 let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1773 &claims.sub,
1774 Some(lifetime),
1775 &family,
1776 )?;
1777 Ok(RefreshRedemption {
1778 claims,
1779 new_refresh_token,
1780 })
1781 }
1782
1783 pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1790 validate_access_jwt_with(
1791 &self.token_manager,
1792 self.storage.as_ref(),
1793 token,
1794 true,
1795 false,
1796 )
1797 .await
1798 }
1799
1800 pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1806 validate_access_jwt_with(
1807 &self.token_manager,
1808 self.storage.as_ref(),
1809 token,
1810 true,
1811 true,
1812 )
1813 .await
1814 }
1815
1816 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1826 self.user_manager.validate_username(username).await
1827 }
1828
1829 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1836 self.user_manager.validate_display_name(display_name).await
1837 }
1838
1839 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1848 self.user_manager.validate_password_strength(password).await
1849 }
1850
1851 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1856 Ok(crate::utils::validation::validate_user_input(input))
1857 }
1858
1859 pub async fn create_auth_token(
1879 &self,
1880 user_id: impl Into<String>,
1881 scopes: impl Into<crate::types::Scopes>,
1882 method_name: impl Into<String>,
1883 lifetime: Option<Duration>,
1884 ) -> Result<AuthToken> {
1885 let method_name = method_name.into();
1886 let user_id = user_id.into();
1887 let scopes: crate::types::Scopes = scopes.into();
1888
1889 let auth_method = self
1891 .methods
1892 .get(&method_name)
1893 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1894 auth_method.validate_config()?;
1895
1896 const MAX_TOKENS_PER_USER: usize = 100;
1898 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1899 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1900 warn!(
1901 "User '{}' has reached maximum tokens ({})",
1902 user_id, MAX_TOKENS_PER_USER
1903 );
1904 return Err(AuthError::rate_limit(
1905 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1906 ));
1907 }
1908
1909 let token = self
1910 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1911 .await?;
1912 self.monitoring_manager
1913 .record_token_creation(&method_name)
1914 .await;
1915 Ok(token)
1916 }
1917
1918 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1928 self.mfa_manager.sms.initiate_challenge(user_id).await
1929 }
1930
1931 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1939 self.mfa_manager.sms.verify_code(challenge_id, code).await
1940 }
1941
1942 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1949 self.mfa_manager.email.register_email(user_id, email).await
1950 }
1951
1952 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1963 self.mfa_manager.totp.generate_secret(user_id).await
1964 }
1965
1966 pub async fn generate_totp_qr_code(
1974 &self,
1975 user_id: &str,
1976 app_name: &str,
1977 secret: &str,
1978 ) -> Result<String> {
1979 self.mfa_manager
1980 .totp
1981 .generate_qr_code(user_id, app_name, secret)
1982 .await
1983 }
1984
1985 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1990 self.mfa_manager.totp.generate_code(secret).await
1991 }
1992
1993 pub async fn generate_totp_code_for_window(
1997 &self,
1998 secret: &str,
1999 time_window: Option<u64>,
2000 ) -> Result<String> {
2001 self.mfa_manager
2002 .totp
2003 .generate_code_for_window(secret, time_window)
2004 .await
2005 }
2006
2007 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2015 self.mfa_manager.totp.verify_code(user_id, code).await
2016 }
2017
2018 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2023 debug!("Checking IP rate limit for '{}'", ip);
2024 let Some(ref rate_limiter) = self.rate_limiter else {
2025 return Ok(true);
2026 };
2027 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2028 warn!("Rate limit exceeded for IP: {}", ip);
2029 return Err(AuthError::rate_limit(format!(
2030 "Too many requests from IP {}. Please try again later.",
2031 ip
2032 )));
2033 }
2034 Ok(true)
2035 }
2036
2037 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2042 debug!("Getting security metrics");
2043 let mut metrics = std::collections::HashMap::new();
2044 let total_active_sessions = self
2045 .session_manager
2046 .count_active_sessions()
2047 .await
2048 .unwrap_or(0);
2049 metrics.insert("active_sessions".to_string(), total_active_sessions);
2050 metrics.insert("total_tokens".to_string(), total_active_sessions);
2051 metrics.insert(
2052 "failed_attempts".to_string(),
2053 self.audit_manager
2054 .get_failed_login_count_24h()
2055 .await
2056 .unwrap_or(0),
2057 );
2058 metrics.insert(
2059 "successful_attempts".to_string(),
2060 self.audit_manager
2061 .get_successful_login_count_24h()
2062 .await
2063 .unwrap_or(0),
2064 );
2065 metrics.insert("expired_tokens".to_string(), 0u64);
2066 Ok(metrics)
2067 }
2068
2069 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2075 self.mfa_manager
2076 .sms
2077 .register_phone_number(user_id, phone_number)
2078 .await
2079 }
2080
2081 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2086 self.mfa_manager
2087 .backup_codes
2088 .generate_codes(user_id, count)
2089 .await
2090 }
2091 pub async fn grant_permission(
2103 &self,
2104 user_id: &str,
2105 action: &str,
2106 resource: &str,
2107 ) -> Result<()> {
2108 self.authorization_manager
2109 .grant_permission(user_id, action, resource)
2110 .await
2111 }
2112
2113 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2123 self.mfa_manager.email.initiate_challenge(user_id).await
2124 }
2125
2126 pub fn storage(&self) -> Arc<dyn AuthStorage> {
2131 self.storage.clone()
2132 }
2133
2134 pub fn config(&self) -> &AuthConfig {
2136 &self.config
2137 }
2138
2139 pub async fn reset_authorization_runtime(&self) {
2141 self.authorization_manager.reset_runtime_state().await;
2142 }
2143
2144 pub async fn register_user(
2167 &self,
2168 username: &str,
2169 email: &str,
2170 password: &str,
2171 ) -> Result<String> {
2172 self.require_initialized()?;
2173 self.user_manager
2174 .register_user(username, email, password)
2175 .await
2176 }
2177
2178 #[deprecated(
2205 since = "0.6.0",
2206 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2207 )]
2208 pub async fn list_users(
2209 &self,
2210 limit: Option<usize>,
2211 offset: Option<usize>,
2212 active_only: bool,
2213 ) -> Result<Vec<UserInfo>> {
2214 self.require_initialized()?;
2215 self.user_manager
2216 .list_users(limit, offset, active_only)
2217 .await
2218 }
2219
2220 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2239 self.require_initialized()?;
2240 self.user_manager
2241 .list_users(
2242 query.get_limit(),
2243 query.get_offset(),
2244 query.get_active_only(),
2245 )
2246 .await
2247 }
2248
2249 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2251 self.require_initialized()?;
2252 self.user_manager.get_user_info(user_id).await
2253 }
2254
2255 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2257 self.require_initialized()?;
2258 self.user_manager.update_user_roles(user_id, roles).await
2259 }
2260
2261 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2263 self.require_initialized()?;
2264 self.user_manager.set_user_active(user_id, active).await
2265 }
2266
2267 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2269 self.require_initialized()?;
2270 self.user_manager.update_user_email(user_id, email).await
2271 }
2272
2273 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2275 self.require_initialized()?;
2276 self.user_manager
2277 .verify_user_password(user_id, password)
2278 .await
2279 }
2280
2281 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2283 self.user_manager.get_username_by_id(user_id).await
2284 }
2285
2286 pub async fn username_exists(&self, username: &str) -> Result<bool> {
2288 self.user_manager.username_exists(username).await
2289 }
2290
2291 pub async fn email_exists(&self, email: &str) -> Result<bool> {
2293 self.user_manager.email_exists(email).await
2294 }
2295
2296 pub async fn get_user_by_username(
2298 &self,
2299 username: &str,
2300 ) -> Result<HashMap<String, serde_json::Value>> {
2301 self.user_manager.get_user_by_username(username).await
2302 }
2303
2304 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2306 self.require_initialized()?;
2307 self.user_manager
2308 .update_user_password(username, new_password)
2309 .await
2310 }
2311
2312 pub async fn update_user_password_by_id(
2314 &self,
2315 user_id: &str,
2316 new_password: &str,
2317 ) -> Result<()> {
2318 self.require_initialized()?;
2319 self.user_manager
2320 .update_user_password_by_id(user_id, new_password)
2321 .await
2322 }
2323
2324 pub async fn delete_user(&self, username: &str) -> Result<()> {
2326 self.require_initialized()?;
2327 self.user_manager.delete_user(username).await
2328 }
2329
2330 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2332 self.require_initialized()?;
2333 self.user_manager.delete_user_by_id(user_id).await
2334 }
2335
2336 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2338 self.mfa_manager
2339 .verify_challenge_code(challenge, code)
2340 .await
2341 }
2342
2343 async fn log_audit_event(
2345 &self,
2346 event_type: &str,
2347 user_id: &str,
2348 method: &str,
2349 metadata: &CredentialMetadata,
2350 ) {
2351 if !self.config.audit.enabled {
2352 return;
2353 }
2354 let should_log = match event_type {
2355 "auth_success" | "mfa_required" => self.config.audit.log_success,
2356 "auth_failure" => self.config.audit.log_failures,
2357 _ => true,
2358 };
2359 if should_log {
2360 self.audit_manager
2361 .log_auth_trace_event(
2362 event_type,
2363 user_id,
2364 method,
2365 metadata.client_ip.as_deref().unwrap_or("unknown"),
2366 metadata.user_agent.as_deref().unwrap_or("unknown"),
2367 )
2368 .await;
2369 }
2370 }
2371
2372 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2374 self.mfa_manager.guard_and_store(challenge).await
2375 }
2376
2377 async fn mint_and_store_token(
2379 &self,
2380 user_id: &str,
2381 scopes: impl Into<crate::types::Scopes>,
2382 method: &str,
2383 lifetime: Option<Duration>,
2384 ) -> Result<AuthToken> {
2385 let token = self
2386 .token_manager
2387 .create_auth_token(user_id, scopes, method, lifetime)?;
2388 self.storage.store_token(&token).await?;
2389 Ok(token)
2390 }
2391
2392 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2394 self.session_manager.coordinate_distributed_sessions().await
2395 }
2396
2397 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2399 self.session_manager.synchronize_session(session_id).await
2400 }
2401
2402 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2404 self.monitoring_manager.clone()
2405 }
2406
2407 #[cfg(feature = "api-server")]
2409 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2410 Some(self.security_manager.clone())
2411 }
2412
2413 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2415 self.monitoring_manager.get_performance_metrics()
2416 }
2417
2418 pub async fn health_check(
2420 &self,
2421 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2422 self.monitoring_manager.health_check().await
2423 }
2424
2425 pub async fn export_prometheus_metrics(&self) -> String {
2427 self.monitoring_manager.export_prometheus_metrics().await
2428 }
2429 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2431 self.require_initialized()?;
2432 self.authorization_manager.create_role(role).await
2433 }
2434
2435 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2437 self.authorization_manager.list_roles().await
2438 }
2439
2440 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2442 self.authorization_manager.get_role(role_name).await
2443 }
2444
2445 pub async fn add_role_permission(
2447 &self,
2448 role_name: &str,
2449 permission: crate::permissions::Permission,
2450 ) -> Result<()> {
2451 self.authorization_manager
2452 .add_role_permission(role_name, permission)
2453 .await
2454 }
2455
2456 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2458 self.require_initialized()?;
2459 self.authorization_manager
2460 .assign_role(user_id, role_name)
2461 .await
2462 }
2463
2464 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2466 self.require_initialized()?;
2467 self.authorization_manager
2468 .remove_role(user_id, role_name)
2469 .await
2470 }
2471
2472 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2474 self.require_initialized()?;
2475 self.authorization_manager
2476 .set_role_inheritance(child_role, parent_role)
2477 .await
2478 }
2479
2480 pub async fn revoke_permission(
2482 &self,
2483 user_id: &str,
2484 action: &str,
2485 resource: &str,
2486 ) -> Result<()> {
2487 self.require_initialized()?;
2488 self.authorization_manager
2489 .revoke_permission(user_id, action, resource)
2490 .await
2491 }
2492
2493 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2495 self.authorization_manager
2496 .user_has_role(user_id, role_name)
2497 .await
2498 }
2499
2500 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2502 self.authorization_manager.list_user_roles(user_id).await
2503 }
2504
2505 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2507 self.authorization_manager
2508 .get_effective_permissions(user_id)
2509 .await
2510 }
2511
2512 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2514 self.authorization_manager
2515 .create_abac_policy(name, description)
2516 .await
2517 }
2518
2519 pub async fn map_user_attribute(
2540 &self,
2541 user_id: &str,
2542 attribute: &str,
2543 value: &str,
2544 ) -> Result<()> {
2545 self.authorization_manager
2546 .map_user_attribute(user_id, attribute, value)
2547 .await
2548 }
2549
2550 pub async fn get_user_attribute(
2574 &self,
2575 user_id: &str,
2576 attribute: &str,
2577 ) -> Result<Option<String>> {
2578 self.authorization_manager
2579 .get_user_attribute(user_id, attribute)
2580 .await
2581 }
2582
2583 pub async fn check_dynamic_permission(
2614 &self,
2615 user_id: &str,
2616 action: &str,
2617 resource: &str,
2618 context: std::collections::HashMap<String, String>,
2619 ) -> Result<bool> {
2620 self.authorization_manager
2621 .check_dynamic_permission(user_id, action, resource, context)
2622 .await
2623 }
2624
2625 pub async fn check_dynamic_permission_with_context(
2645 &self,
2646 user_id: &str,
2647 action: &str,
2648 resource: &str,
2649 context: PermissionContext,
2650 ) -> Result<bool> {
2651 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2652 .await
2653 }
2654
2655 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2657 self.authorization_manager.create_resource(resource).await
2658 }
2659
2660 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2679 self.authorization_manager
2680 .delegate_permission(
2681 req.delegator_id(),
2682 req.delegatee_id(),
2683 req.action(),
2684 req.resource(),
2685 req.get_duration(),
2686 )
2687 .await
2688 }
2689
2690 pub async fn delegate_permission(
2695 &self,
2696 delegator_id: &str,
2697 delegatee_id: &str,
2698 action: &str,
2699 resource: &str,
2700 duration: std::time::Duration,
2701 ) -> Result<()> {
2702 self.authorization_manager
2703 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2704 .await
2705 }
2706
2707 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2709 self.authorization_manager
2710 .get_active_delegations(user_id)
2711 .await
2712 }
2713
2714 pub async fn get_permission_audit_logs(
2716 &self,
2717 user_id: Option<&str>,
2718 action: Option<&str>,
2719 resource: Option<&str>,
2720 limit: Option<usize>,
2721 ) -> Result<Vec<String>> {
2722 self.audit_manager
2723 .get_permission_audit_logs(user_id, action, resource, limit)
2724 .await
2725 }
2726
2727 pub async fn get_permission_audit_logs_with_query(
2747 &self,
2748 query: AuditLogQuery,
2749 ) -> Result<Vec<String>> {
2750 self.audit_manager
2751 .get_permission_audit_logs(
2752 query.get_user_id(),
2753 query.get_action(),
2754 query.get_resource(),
2755 query.get_limit(),
2756 )
2757 .await
2758 }
2759
2760 pub async fn get_permission_metrics(
2762 &self,
2763 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2764 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2765 let permission_checks_last_hour = self
2766 .audit_manager
2767 .get_permission_checks_last_hour()
2768 .await
2769 .unwrap_or(0);
2770 self.authorization_manager
2771 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2772 .await
2773 }
2774
2775 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2777 let active_sessions = self
2778 .session_manager
2779 .count_active_sessions()
2780 .await
2781 .unwrap_or(0);
2782 self.audit_manager
2783 .get_security_audit_stats(active_sessions)
2784 .await
2785 }
2786
2787 pub async fn get_user_profile(
2789 &self,
2790 user_id: &str,
2791 ) -> Result<crate::providers::ProviderProfile> {
2792 self.user_manager.get_user_profile(user_id).await
2793 }
2794}
2795
2796pub use crate::audit::SecurityAuditStats;
2797
2798pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2799
2800#[derive(Debug, Clone, Default)]
2802pub struct AuthStats {
2803 pub registered_methods: Vec<String>,
2805
2806 pub active_sessions: u64,
2808
2809 pub active_mfa_challenges: u64,
2811
2812 pub tokens_issued: u64,
2814
2815 pub auth_attempts: u64,
2817}
2818
2819#[cfg(test)]
2820mod tests {
2821 use super::*;
2822 use crate::config::{AuthConfig, SecurityConfig};
2823 #[tokio::test]
2824 async fn test_framework_initialization() {
2825 let config = AuthConfig::new().security(SecurityConfig {
2826 min_password_length: 8,
2827 require_password_complexity: false,
2828 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2829 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2830 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2831 secure_cookies: false,
2832 cookie_same_site: crate::config::CookieSameSite::Lax,
2833 csrf_protection: false,
2834 session_timeout: Duration::from_secs(3600),
2835 previous_secret_key: None,
2836 });
2837 let mut framework = AuthFramework::new(config);
2838
2839 assert!(framework.initialize().await.is_ok());
2840 assert!(framework.initialized);
2841 }
2842
2843 #[tokio::test]
2844 async fn test_method_registration() {
2845 let config = AuthConfig::new().security(SecurityConfig {
2850 min_password_length: 8,
2851 require_password_complexity: false,
2852 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2853 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2854 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2855 secure_cookies: false,
2856 cookie_same_site: crate::config::CookieSameSite::Lax,
2857 csrf_protection: false,
2858 session_timeout: Duration::from_secs(3600),
2859 previous_secret_key: None,
2860 });
2861 let framework = AuthFramework::new(config);
2862
2863 assert!(!framework.initialized);
2865
2866 }
2869
2870 #[tokio::test]
2871 async fn test_token_validation() {
2872 let config = AuthConfig::new().security(SecurityConfig {
2873 min_password_length: 8,
2874 require_password_complexity: false,
2875 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2876 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2877 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2878 secure_cookies: false,
2879 cookie_same_site: crate::config::CookieSameSite::Lax,
2880 csrf_protection: false,
2881 session_timeout: Duration::from_secs(3600),
2882 previous_secret_key: None,
2883 });
2884 let mut framework = AuthFramework::new(config);
2885 framework.initialize().await.unwrap();
2886
2887 let token = framework
2888 .token_manager
2889 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2890 .unwrap();
2891
2892 framework.storage.store_token(&token).await.unwrap();
2894
2895 assert!(framework.validate_token(&token).await.unwrap());
2896 }
2897
2898 #[tokio::test]
2899 async fn test_session_management() {
2900 let config = AuthConfig::new().security(SecurityConfig {
2901 min_password_length: 8,
2902 require_password_complexity: false,
2903 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2904 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2905 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2906 secure_cookies: false,
2907 cookie_same_site: crate::config::CookieSameSite::Lax,
2908 csrf_protection: false,
2909 session_timeout: Duration::from_secs(3600),
2910 previous_secret_key: None,
2911 });
2912 let mut framework = AuthFramework::new(config);
2913 framework.initialize().await.unwrap();
2914
2915 let session_id = framework
2916 .create_session(
2917 "test-user",
2918 Duration::from_secs(3600),
2919 Some("192.168.1.1".to_string()),
2920 Some("Test Agent".to_string()),
2921 )
2922 .await
2923 .unwrap();
2924
2925 let session = framework.get_session(&session_id).await.unwrap();
2926 assert!(session.is_some());
2927
2928 framework.delete_session(&session_id).await.unwrap();
2929 let session = framework.get_session(&session_id).await.unwrap();
2930 assert!(session.is_none());
2931 }
2932
2933 #[tokio::test]
2934 async fn test_grouped_operations_accessors() {
2935 let config = AuthConfig::new().security(SecurityConfig {
2936 min_password_length: 8,
2937 require_password_complexity: false,
2938 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2939 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2940 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2941 secure_cookies: false,
2942 cookie_same_site: crate::config::CookieSameSite::Lax,
2943 csrf_protection: false,
2944 session_timeout: Duration::from_secs(3600),
2945 previous_secret_key: None,
2946 });
2947 let mut framework = AuthFramework::new(config);
2948 framework.initialize().await.unwrap();
2949
2950 let user_id = framework
2951 .users()
2952 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
2953 .await
2954 .unwrap();
2955 assert!(
2956 framework
2957 .users()
2958 .exists_by_username("grouped-user")
2959 .await
2960 .unwrap()
2961 );
2962
2963 let session_id = framework
2964 .sessions()
2965 .create(&user_id, Duration::from_secs(300), None, None)
2966 .await
2967 .unwrap();
2968 assert!(
2969 framework
2970 .sessions()
2971 .get(&session_id)
2972 .await
2973 .unwrap()
2974 .is_some()
2975 );
2976 assert_eq!(
2977 framework
2978 .sessions()
2979 .list_for_user(&user_id)
2980 .await
2981 .unwrap()
2982 .len(),
2983 1
2984 );
2985
2986 framework
2987 .authorization()
2988 .grant(&user_id, "read", "documents")
2989 .await
2990 .unwrap();
2991 let permissions = framework
2992 .authorization()
2993 .effective_permissions(&user_id)
2994 .await
2995 .unwrap();
2996 assert!(
2997 permissions
2998 .iter()
2999 .any(|permission| permission == "read:documents")
3000 );
3001
3002 framework.sessions().delete(&session_id).await.unwrap();
3003 assert!(
3004 framework
3005 .sessions()
3006 .get(&session_id)
3007 .await
3008 .unwrap()
3009 .is_none()
3010 );
3011 }
3012
3013 #[tokio::test]
3014 async fn test_cleanup_expired_data() {
3015 let config = AuthConfig::new().security(SecurityConfig {
3016 min_password_length: 8,
3017 require_password_complexity: false,
3018 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3019 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3020 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3021 secure_cookies: false,
3022 cookie_same_site: crate::config::CookieSameSite::Lax,
3023 csrf_protection: false,
3024 session_timeout: Duration::from_secs(3600),
3025 previous_secret_key: None,
3026 });
3027 let mut framework = AuthFramework::new(config);
3028 framework.initialize().await.unwrap();
3029
3030 assert!(framework.cleanup_expired_data().await.is_ok());
3032 }
3033
3034 #[cfg(feature = "redis-storage")]
3042 #[test]
3043 fn new_validated_redis_fails_closed_without_an_encryption_key() {
3044 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3045 unsafe {
3048 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3049 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3050 }
3051
3052 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3053 config.storage = crate::config::StorageConfig::Redis {
3054 url: "redis://127.0.0.1:1/".to_string(),
3055 key_prefix: "test:".to_string(),
3056 };
3057 let result = AuthFramework::new_validated(config);
3060 assert!(
3061 result.is_err(),
3062 "constructing with Redis storage and no encryption key configured must fail \
3063 closed, not silently build unwrapped (unencrypted) storage"
3064 );
3065 }
3066
3067 #[tokio::test]
3068 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3069 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3070 config.storage_encryption.require_wrapped_storage = true;
3071 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3072 assert!(
3073 framework.initialize().await.is_err(),
3074 "caller-supplied unwrapped storage must be refused when wrapping is required"
3075 );
3076 }
3077
3078 #[tokio::test]
3079 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3080 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3081 required.storage_encryption.require_wrapped_storage = true;
3082 let wrapped: Arc<dyn AuthStorage> =
3083 Arc::new(crate::storage::encryption::EncryptedStorage::new(
3084 MemoryStorage::new(),
3085 crate::storage::encryption::StorageEncryption::new_random(),
3086 false,
3087 false,
3088 ));
3089 let mut framework = AuthFramework::new_with_storage(required, wrapped);
3090 framework.initialize().await.unwrap();
3091
3092 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3094 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3095 framework.initialize().await.unwrap();
3096 }
3097
3098 #[tokio::test]
3099 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3100 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3101 config.storage_encryption.require_wrapped_storage = true;
3102 let mut framework = AuthFramework::new(config);
3103 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3105 framework.initialize().await.unwrap();
3106 }
3107}