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 let Some(proof) = self.validated_token(token).await? else {
1443 return Ok(false);
1444 };
1445 self.check_validated_permission(&proof, action, resource)
1446 .await
1447 }
1448
1449 pub async fn validated_token(
1451 &self,
1452 token: &AuthToken,
1453 ) -> Result<Option<crate::tokens::ValidatedToken>> {
1454 Ok(self
1455 .validate_token(token)
1456 .await?
1457 .then(|| crate::tokens::ValidatedToken::new(token.clone())))
1458 }
1459
1460 pub async fn check_validated_permission(
1462 &self,
1463 proof: &crate::tokens::ValidatedToken,
1464 action: &str,
1465 resource: &str,
1466 ) -> Result<bool> {
1467 self.authorization_manager
1468 .check_validated_permission(proof, action, resource)
1469 .await
1470 }
1471
1472 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1474 self.require_initialized()?;
1475 debug!("Refreshing token for user '{}'", token.user_id);
1476
1477 if let Some(method) = self.methods.get(&token.auth_method)
1479 && method.supports_refresh()
1480 && let Some(ref refresh_token) = token.refresh_token
1481 {
1482 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1483 self.storage.store_token(&new_token).await?;
1484 return Ok(new_token);
1485 }
1486
1487 if !self.validate_token(token).await? {
1491 return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1492 message: "Cannot refresh a token that is not valid".to_string(),
1493 }));
1494 }
1495 let stored = self
1497 .storage
1498 .get_token(&token.token_id)
1499 .await?
1500 .ok_or_else(|| {
1501 AuthError::Token(crate::errors::TokenError::Invalid {
1502 message: "Cannot refresh a token that is not stored".to_string(),
1503 })
1504 })?;
1505 let new_token = self.token_manager.refresh_token(&stored)?;
1506 self.storage.store_token(&new_token).await?;
1507
1508 info!("Token refreshed for user '{}'", token.user_id);
1509
1510 Ok(new_token)
1511 }
1512
1513 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1515 self.require_initialized()?;
1516 debug!("Revoking token for user '{}'", token.user_id);
1517
1518 let mut revoked_token = token.clone();
1520 revoked_token.revoke(Some("Manual revocation".to_string()));
1521
1522 self.storage.update_token(&revoked_token).await?;
1524
1525 let jti = self
1528 .token_manager
1529 .validate_jwt_token(&token.access_token)
1530 .map(|claims| claims.jti)
1531 .unwrap_or_else(|_| token.token_id.clone());
1532 let remaining = (token.expires_at - chrono::Utc::now())
1533 .to_std()
1534 .unwrap_or_default()
1535 .max(Duration::from_secs(60));
1536 self.storage
1537 .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1538 .await?;
1539
1540 info!("Token revoked for user '{}'", token.user_id);
1541
1542 Ok(())
1543 }
1544
1545 pub async fn create_api_key(
1547 &self,
1548 user_id: &str,
1549 expires_in: Option<Duration>,
1550 ) -> Result<String> {
1551 self.require_initialized()?;
1552 self.user_manager.create_api_key(user_id, expires_in).await
1553 }
1554
1555 pub async fn create_api_key_with_role(
1562 &self,
1563 user_id: &str,
1564 role: &str,
1565 expires_in: Option<Duration>,
1566 ) -> Result<String> {
1567 self.require_initialized()?;
1568 self.user_manager
1569 .create_api_key_with_role(user_id, role, expires_in)
1570 .await
1571 }
1572
1573 pub async fn rotate_api_key(&self, old_key: &str) -> Result<String> {
1579 self.require_initialized()?;
1580 self.user_manager.rotate_api_key(old_key).await
1581 }
1582
1583 pub async fn rotate_api_key_with_expiry(
1585 &self,
1586 old_key: &str,
1587 expires_in: Option<Duration>,
1588 ) -> Result<String> {
1589 self.require_initialized()?;
1590 self.user_manager
1591 .rotate_api_key_with_expiry(old_key, expires_in)
1592 .await
1593 }
1594
1595 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1597 self.require_initialized()?;
1598 self.user_manager.validate_api_key(api_key).await
1599 }
1600
1601 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1603 self.require_initialized()?;
1604 self.user_manager.revoke_api_key(api_key).await
1605 }
1606
1607 pub async fn create_session(
1609 &self,
1610 user_id: &str,
1611 expires_in: Duration,
1612 ip_address: Option<String>,
1613 user_agent: Option<String>,
1614 ) -> Result<String> {
1615 self.require_initialized()?;
1616 let (session_id, new_total) = self
1617 .session_manager
1618 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1619 .await?;
1620 self.monitoring_manager
1621 .update_session_count(new_total)
1622 .await;
1623 Ok(session_id)
1624 }
1625
1626 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1646 self.create_session(
1647 req.get_user_id(),
1648 req.get_expires_in(),
1649 req.get_ip_address().map(|s| s.to_string()),
1650 req.get_user_agent().map(|s| s.to_string()),
1651 )
1652 .await
1653 }
1654
1655 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1657 self.require_initialized()?;
1658 self.session_manager.get_session(session_id).await
1659 }
1660
1661 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1663 self.require_initialized()?;
1664 self.session_manager.delete_session(session_id).await?;
1665
1666 let remaining = self
1667 .session_manager
1668 .count_active_sessions()
1669 .await
1670 .unwrap_or(0);
1671 self.monitoring_manager
1672 .update_session_count(remaining)
1673 .await;
1674
1675 Ok(())
1676 }
1677
1678 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1680 self.require_initialized()?;
1681 self.storage.list_user_tokens(user_id).await
1682 }
1683
1684 pub async fn cleanup_expired_data(&self) -> Result<()> {
1686 debug!("Cleaning up expired data");
1687
1688 self.storage.cleanup_expired().await?;
1690
1691 self.mfa_manager.cleanup_expired_challenges().await?;
1693
1694 self.session_manager.cleanup_expired_sessions().await?;
1696
1697 if let Some(ref rate_limiter) = self.rate_limiter {
1699 let _ = rate_limiter.cleanup().ok();
1700 }
1701
1702 Ok(())
1703 }
1704
1705 fn is_production_environment() -> bool {
1708 if let Ok(env) = std::env::var("ENVIRONMENT")
1709 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1710 {
1711 return true;
1712 }
1713 if let Ok(env) = std::env::var("ENV")
1714 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1715 {
1716 return true;
1717 }
1718 if let Ok(env) = std::env::var("NODE_ENV")
1719 && env.to_lowercase() == "production"
1720 {
1721 return true;
1722 }
1723 if let Ok(env) = std::env::var("RUST_ENV")
1724 && env.to_lowercase() == "production"
1725 {
1726 return true;
1727 }
1728 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1729 || std::env::var("DOCKER_CONTAINER").is_ok()
1730 }
1731
1732 pub async fn get_stats(&self) -> Result<AuthStats> {
1734 let mut stats = AuthStats::default();
1735
1736 if let Err(e) = self.storage.cleanup_expired().await {
1737 warn!("Failed to cleanup expired data: {}", e);
1738 }
1739 if let Some(rate_limiter) = &self.rate_limiter {
1740 let _ = rate_limiter.cleanup().ok();
1741 }
1742
1743 let active_sessions = self
1744 .session_manager
1745 .count_active_sessions()
1746 .await
1747 .unwrap_or(0) as u32;
1748
1749 stats.registered_methods = self.methods.keys().cloned().collect();
1750 stats.active_sessions = active_sessions as u64;
1751 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1752 let perf = self.monitoring_manager.get_performance_metrics();
1754 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1755 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1756 + perf.get("auth_failures").copied().unwrap_or(0);
1757
1758 Ok(stats)
1759 }
1760
1761 pub fn token_manager(&self) -> &TokenManager {
1766 &self.token_manager
1767 }
1768
1769 pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1776 let claims = self.token_manager.validate_jwt_token(token)?;
1777 if !claims.is_refresh_token() {
1778 return Err(rejected("Expected a refresh token"));
1779 }
1780 let read = |key: String| async move {
1781 self.storage.get_kv(&key).await.map_err(|e| {
1782 tracing::error!("Could not read refresh-token state: {}", e);
1783 rejected("Unable to verify token status")
1784 })
1785 };
1786 let family = claims.refresh_family().to_string();
1787 if read(format!("revoked_token:{}", claims.jti))
1788 .await?
1789 .is_some()
1790 || read(format!("revoked_family:{family}")).await?.is_some()
1791 {
1792 return Err(rejected("Refresh token has been revoked"));
1793 }
1794 ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1795
1796 let remaining =
1797 Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1798 let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1800 let consumed_key = format!("refresh_consumed:{}", claims.jti);
1801 let first_use = self
1807 .storage
1808 .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1809 .await
1810 .map_err(|e| {
1811 tracing::error!("Could not record refresh token use: {}", e);
1812 rejected("Unable to record refresh token use")
1813 })?;
1814 if !first_use {
1815 warn!(
1816 "Refresh token reuse detected for user '{}'; revoking its chain",
1817 claims.sub
1818 );
1819 if let Err(e) = self
1820 .storage
1821 .store_kv(
1822 &format!("revoked_family:{family}"),
1823 b"reuse",
1824 Some(family_ttl),
1825 )
1826 .await
1827 {
1828 tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1829 }
1830 return Err(rejected("Refresh token has already been used"));
1831 }
1832
1833 let lifetime = self.config.refresh_token_lifetime;
1834 let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1835 &claims.sub,
1836 Some(lifetime),
1837 &family,
1838 )?;
1839 Ok(RefreshRedemption {
1840 claims,
1841 new_refresh_token,
1842 })
1843 }
1844
1845 pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1852 validate_access_jwt_with(
1853 &self.token_manager,
1854 self.storage.as_ref(),
1855 token,
1856 true,
1857 false,
1858 )
1859 .await
1860 }
1861
1862 pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1868 validate_access_jwt_with(
1869 &self.token_manager,
1870 self.storage.as_ref(),
1871 token,
1872 true,
1873 true,
1874 )
1875 .await
1876 }
1877
1878 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1888 self.user_manager.validate_username(username).await
1889 }
1890
1891 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1898 self.user_manager.validate_display_name(display_name).await
1899 }
1900
1901 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1910 self.user_manager.validate_password_strength(password).await
1911 }
1912
1913 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1918 Ok(crate::utils::validation::validate_user_input(input))
1919 }
1920
1921 pub async fn create_auth_token(
1941 &self,
1942 user_id: impl Into<String>,
1943 scopes: impl Into<crate::types::Scopes>,
1944 method_name: impl Into<String>,
1945 lifetime: Option<Duration>,
1946 ) -> Result<AuthToken> {
1947 let method_name = method_name.into();
1948 let user_id = user_id.into();
1949 let scopes: crate::types::Scopes = scopes.into();
1950
1951 let auth_method = self
1953 .methods
1954 .get(&method_name)
1955 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1956 auth_method.validate_config()?;
1957
1958 const MAX_TOKENS_PER_USER: usize = 100;
1960 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1961 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1962 warn!(
1963 "User '{}' has reached maximum tokens ({})",
1964 user_id, MAX_TOKENS_PER_USER
1965 );
1966 return Err(AuthError::rate_limit(
1967 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1968 ));
1969 }
1970
1971 let token = self
1972 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1973 .await?;
1974 self.monitoring_manager
1975 .record_token_creation(&method_name)
1976 .await;
1977 Ok(token)
1978 }
1979
1980 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1990 self.mfa_manager.sms.initiate_challenge(user_id).await
1991 }
1992
1993 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
2001 self.mfa_manager.sms.verify_code(challenge_id, code).await
2002 }
2003
2004 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
2011 self.mfa_manager.email.register_email(user_id, email).await
2012 }
2013
2014 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
2025 self.mfa_manager.totp.generate_secret(user_id).await
2026 }
2027
2028 pub async fn generate_totp_qr_code(
2036 &self,
2037 user_id: &str,
2038 app_name: &str,
2039 secret: &str,
2040 ) -> Result<String> {
2041 self.mfa_manager
2042 .totp
2043 .generate_qr_code(user_id, app_name, secret)
2044 .await
2045 }
2046
2047 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
2052 self.mfa_manager.totp.generate_code(secret).await
2053 }
2054
2055 pub async fn generate_totp_code_for_window(
2059 &self,
2060 secret: &str,
2061 time_window: Option<u64>,
2062 ) -> Result<String> {
2063 self.mfa_manager
2064 .totp
2065 .generate_code_for_window(secret, time_window)
2066 .await
2067 }
2068
2069 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2077 self.mfa_manager.totp.verify_code(user_id, code).await
2078 }
2079
2080 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2085 debug!("Checking IP rate limit for '{}'", ip);
2086 let Some(ref rate_limiter) = self.rate_limiter else {
2087 return Ok(true);
2088 };
2089 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2090 warn!("Rate limit exceeded for IP: {}", ip);
2091 return Err(AuthError::rate_limit(format!(
2092 "Too many requests from IP {}. Please try again later.",
2093 ip
2094 )));
2095 }
2096 Ok(true)
2097 }
2098
2099 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2104 debug!("Getting security metrics");
2105 let mut metrics = std::collections::HashMap::new();
2106 let total_active_sessions = self
2107 .session_manager
2108 .count_active_sessions()
2109 .await
2110 .unwrap_or(0);
2111 metrics.insert("active_sessions".to_string(), total_active_sessions);
2112 metrics.insert("total_tokens".to_string(), total_active_sessions);
2113 metrics.insert(
2114 "failed_attempts".to_string(),
2115 self.audit_manager
2116 .get_failed_login_count_24h()
2117 .await
2118 .unwrap_or(0),
2119 );
2120 metrics.insert(
2121 "successful_attempts".to_string(),
2122 self.audit_manager
2123 .get_successful_login_count_24h()
2124 .await
2125 .unwrap_or(0),
2126 );
2127 metrics.insert("expired_tokens".to_string(), 0u64);
2128 Ok(metrics)
2129 }
2130
2131 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2137 self.mfa_manager
2138 .sms
2139 .register_phone_number(user_id, phone_number)
2140 .await
2141 }
2142
2143 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2148 self.mfa_manager
2149 .backup_codes
2150 .generate_codes(user_id, count)
2151 .await
2152 }
2153 pub async fn grant_permission(
2165 &self,
2166 user_id: &str,
2167 action: &str,
2168 resource: &str,
2169 ) -> Result<()> {
2170 self.authorization_manager
2171 .grant_permission(user_id, action, resource)
2172 .await
2173 }
2174
2175 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2185 self.mfa_manager.email.initiate_challenge(user_id).await
2186 }
2187
2188 pub fn storage(&self) -> Arc<dyn AuthStorage> {
2193 self.storage.clone()
2194 }
2195
2196 pub fn config(&self) -> &AuthConfig {
2198 &self.config
2199 }
2200
2201 pub async fn reset_authorization_runtime(&self) {
2203 self.authorization_manager.reset_runtime_state().await;
2204 }
2205
2206 pub async fn register_user(
2229 &self,
2230 username: &str,
2231 email: &str,
2232 password: &str,
2233 ) -> Result<String> {
2234 self.require_initialized()?;
2235 self.user_manager
2236 .register_user(username, email, password)
2237 .await
2238 }
2239
2240 #[deprecated(
2267 since = "0.6.0",
2268 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2269 )]
2270 pub async fn list_users(
2271 &self,
2272 limit: Option<usize>,
2273 offset: Option<usize>,
2274 active_only: bool,
2275 ) -> Result<Vec<UserInfo>> {
2276 self.require_initialized()?;
2277 self.user_manager
2278 .list_users(limit, offset, active_only)
2279 .await
2280 }
2281
2282 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2301 self.require_initialized()?;
2302 self.user_manager
2303 .list_users(
2304 query.get_limit(),
2305 query.get_offset(),
2306 query.get_active_only(),
2307 )
2308 .await
2309 }
2310
2311 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2313 self.require_initialized()?;
2314 self.user_manager.get_user_info(user_id).await
2315 }
2316
2317 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2319 self.require_initialized()?;
2320 self.user_manager.update_user_roles(user_id, roles).await
2321 }
2322
2323 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2325 self.require_initialized()?;
2326 self.user_manager.set_user_active(user_id, active).await
2327 }
2328
2329 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2331 self.require_initialized()?;
2332 self.user_manager.update_user_email(user_id, email).await
2333 }
2334
2335 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2337 self.require_initialized()?;
2338 self.user_manager
2339 .verify_user_password(user_id, password)
2340 .await
2341 }
2342
2343 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2345 self.user_manager.get_username_by_id(user_id).await
2346 }
2347
2348 pub async fn username_exists(&self, username: &str) -> Result<bool> {
2350 self.user_manager.username_exists(username).await
2351 }
2352
2353 pub async fn email_exists(&self, email: &str) -> Result<bool> {
2355 self.user_manager.email_exists(email).await
2356 }
2357
2358 pub async fn get_user_by_username(
2360 &self,
2361 username: &str,
2362 ) -> Result<HashMap<String, serde_json::Value>> {
2363 self.user_manager.get_user_by_username(username).await
2364 }
2365
2366 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2368 self.require_initialized()?;
2369 self.user_manager
2370 .update_user_password(username, new_password)
2371 .await
2372 }
2373
2374 pub async fn update_user_password_by_id(
2376 &self,
2377 user_id: &str,
2378 new_password: &str,
2379 ) -> Result<()> {
2380 self.require_initialized()?;
2381 self.user_manager
2382 .update_user_password_by_id(user_id, new_password)
2383 .await
2384 }
2385
2386 pub async fn delete_user(&self, username: &str) -> Result<()> {
2388 self.require_initialized()?;
2389 self.user_manager.delete_user(username).await
2390 }
2391
2392 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2394 self.require_initialized()?;
2395 self.user_manager.delete_user_by_id(user_id).await
2396 }
2397
2398 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2400 self.mfa_manager
2401 .verify_challenge_code(challenge, code)
2402 .await
2403 }
2404
2405 async fn log_audit_event(
2407 &self,
2408 event_type: &str,
2409 user_id: &str,
2410 method: &str,
2411 metadata: &CredentialMetadata,
2412 ) {
2413 if !self.config.audit.enabled {
2414 return;
2415 }
2416 let should_log = match event_type {
2417 "auth_success" | "mfa_required" => self.config.audit.log_success,
2418 "auth_failure" => self.config.audit.log_failures,
2419 _ => true,
2420 };
2421 if should_log {
2422 self.audit_manager
2423 .log_auth_trace_event(
2424 event_type,
2425 user_id,
2426 method,
2427 metadata.client_ip.as_deref().unwrap_or("unknown"),
2428 metadata.user_agent.as_deref().unwrap_or("unknown"),
2429 )
2430 .await;
2431 }
2432 }
2433
2434 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2436 self.mfa_manager.guard_and_store(challenge).await
2437 }
2438
2439 async fn mint_and_store_token(
2441 &self,
2442 user_id: &str,
2443 scopes: impl Into<crate::types::Scopes>,
2444 method: &str,
2445 lifetime: Option<Duration>,
2446 ) -> Result<AuthToken> {
2447 let token = self
2448 .token_manager
2449 .create_auth_token(user_id, scopes, method, lifetime)?;
2450 self.storage.store_token(&token).await?;
2451 Ok(token)
2452 }
2453
2454 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2456 self.session_manager.coordinate_distributed_sessions().await
2457 }
2458
2459 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2461 self.session_manager.synchronize_session(session_id).await
2462 }
2463
2464 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2466 self.monitoring_manager.clone()
2467 }
2468
2469 #[cfg(feature = "api-server")]
2471 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2472 Some(self.security_manager.clone())
2473 }
2474
2475 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2477 self.monitoring_manager.get_performance_metrics()
2478 }
2479
2480 pub async fn health_check(
2482 &self,
2483 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2484 self.monitoring_manager.health_check().await
2485 }
2486
2487 pub async fn export_prometheus_metrics(&self) -> String {
2489 self.monitoring_manager.export_prometheus_metrics().await
2490 }
2491 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2493 self.require_initialized()?;
2494 self.authorization_manager.create_role(role).await
2495 }
2496
2497 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2499 self.authorization_manager.list_roles().await
2500 }
2501
2502 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2504 self.authorization_manager.get_role(role_name).await
2505 }
2506
2507 pub async fn add_role_permission(
2509 &self,
2510 role_name: &str,
2511 permission: crate::permissions::Permission,
2512 ) -> Result<()> {
2513 self.authorization_manager
2514 .add_role_permission(role_name, permission)
2515 .await
2516 }
2517
2518 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2520 self.require_initialized()?;
2521 self.authorization_manager
2522 .assign_role(user_id, role_name)
2523 .await
2524 }
2525
2526 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2528 self.require_initialized()?;
2529 self.authorization_manager
2530 .remove_role(user_id, role_name)
2531 .await
2532 }
2533
2534 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2536 self.require_initialized()?;
2537 self.authorization_manager
2538 .set_role_inheritance(child_role, parent_role)
2539 .await
2540 }
2541
2542 pub async fn revoke_permission(
2544 &self,
2545 user_id: &str,
2546 action: &str,
2547 resource: &str,
2548 ) -> Result<()> {
2549 self.require_initialized()?;
2550 self.authorization_manager
2551 .revoke_permission(user_id, action, resource)
2552 .await
2553 }
2554
2555 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2557 self.authorization_manager
2558 .user_has_role(user_id, role_name)
2559 .await
2560 }
2561
2562 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2564 self.authorization_manager.list_user_roles(user_id).await
2565 }
2566
2567 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2569 self.authorization_manager
2570 .get_effective_permissions(user_id)
2571 .await
2572 }
2573
2574 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2576 self.authorization_manager
2577 .create_abac_policy(name, description)
2578 .await
2579 }
2580
2581 pub async fn map_user_attribute(
2602 &self,
2603 user_id: &str,
2604 attribute: &str,
2605 value: &str,
2606 ) -> Result<()> {
2607 self.authorization_manager
2608 .map_user_attribute(user_id, attribute, value)
2609 .await
2610 }
2611
2612 pub async fn get_user_attribute(
2636 &self,
2637 user_id: &str,
2638 attribute: &str,
2639 ) -> Result<Option<String>> {
2640 self.authorization_manager
2641 .get_user_attribute(user_id, attribute)
2642 .await
2643 }
2644
2645 pub async fn check_dynamic_permission(
2676 &self,
2677 user_id: &str,
2678 action: &str,
2679 resource: &str,
2680 context: std::collections::HashMap<String, String>,
2681 ) -> Result<bool> {
2682 self.authorization_manager
2683 .check_dynamic_permission(user_id, action, resource, context)
2684 .await
2685 }
2686
2687 pub async fn check_dynamic_permission_with_context(
2707 &self,
2708 user_id: &str,
2709 action: &str,
2710 resource: &str,
2711 context: PermissionContext,
2712 ) -> Result<bool> {
2713 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2714 .await
2715 }
2716
2717 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2719 self.authorization_manager.create_resource(resource).await
2720 }
2721
2722 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2741 self.authorization_manager
2742 .delegate_permission(
2743 req.delegator_id(),
2744 req.delegatee_id(),
2745 req.action(),
2746 req.resource(),
2747 req.get_duration(),
2748 )
2749 .await
2750 }
2751
2752 pub async fn delegate_permission(
2757 &self,
2758 delegator_id: &str,
2759 delegatee_id: &str,
2760 action: &str,
2761 resource: &str,
2762 duration: std::time::Duration,
2763 ) -> Result<()> {
2764 self.authorization_manager
2765 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2766 .await
2767 }
2768
2769 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2771 self.authorization_manager
2772 .get_active_delegations(user_id)
2773 .await
2774 }
2775
2776 pub async fn get_permission_audit_logs(
2778 &self,
2779 user_id: Option<&str>,
2780 action: Option<&str>,
2781 resource: Option<&str>,
2782 limit: Option<usize>,
2783 ) -> Result<Vec<String>> {
2784 self.audit_manager
2785 .get_permission_audit_logs(user_id, action, resource, limit)
2786 .await
2787 }
2788
2789 pub async fn get_permission_audit_logs_with_query(
2809 &self,
2810 query: AuditLogQuery,
2811 ) -> Result<Vec<String>> {
2812 self.audit_manager
2813 .get_permission_audit_logs(
2814 query.get_user_id(),
2815 query.get_action(),
2816 query.get_resource(),
2817 query.get_limit(),
2818 )
2819 .await
2820 }
2821
2822 pub async fn get_permission_metrics(
2824 &self,
2825 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2826 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2827 let permission_checks_last_hour = self
2828 .audit_manager
2829 .get_permission_checks_last_hour()
2830 .await
2831 .unwrap_or(0);
2832 self.authorization_manager
2833 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2834 .await
2835 }
2836
2837 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2839 let active_sessions = self
2840 .session_manager
2841 .count_active_sessions()
2842 .await
2843 .unwrap_or(0);
2844 self.audit_manager
2845 .get_security_audit_stats(active_sessions)
2846 .await
2847 }
2848
2849 pub async fn get_user_profile(
2851 &self,
2852 user_id: &str,
2853 ) -> Result<crate::providers::ProviderProfile> {
2854 self.user_manager.get_user_profile(user_id).await
2855 }
2856}
2857
2858pub use crate::audit::SecurityAuditStats;
2859
2860pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2861
2862#[derive(Debug, Clone, Default)]
2864pub struct AuthStats {
2865 pub registered_methods: Vec<String>,
2867
2868 pub active_sessions: u64,
2870
2871 pub active_mfa_challenges: u64,
2873
2874 pub tokens_issued: u64,
2876
2877 pub auth_attempts: u64,
2879}
2880
2881#[cfg(test)]
2882mod tests {
2883 use super::*;
2884 use crate::config::{AuthConfig, SecurityConfig};
2885 #[tokio::test]
2886 async fn test_framework_initialization() {
2887 let config = AuthConfig::new().security(SecurityConfig {
2888 min_password_length: 8,
2889 require_password_complexity: false,
2890 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2891 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2892 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2893 secure_cookies: false,
2894 cookie_same_site: crate::config::CookieSameSite::Lax,
2895 csrf_protection: false,
2896 session_timeout: Duration::from_secs(3600),
2897 previous_secret_key: None,
2898 });
2899 let mut framework = AuthFramework::new(config);
2900
2901 assert!(framework.initialize().await.is_ok());
2902 assert!(framework.initialized);
2903 }
2904
2905 #[tokio::test]
2906 async fn test_method_registration() {
2907 let config = AuthConfig::new().security(SecurityConfig {
2912 min_password_length: 8,
2913 require_password_complexity: false,
2914 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2915 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2916 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2917 secure_cookies: false,
2918 cookie_same_site: crate::config::CookieSameSite::Lax,
2919 csrf_protection: false,
2920 session_timeout: Duration::from_secs(3600),
2921 previous_secret_key: None,
2922 });
2923 let framework = AuthFramework::new(config);
2924
2925 assert!(!framework.initialized);
2927
2928 }
2931
2932 #[tokio::test]
2933 async fn test_token_validation() {
2934 let config = AuthConfig::new().security(SecurityConfig {
2935 min_password_length: 8,
2936 require_password_complexity: false,
2937 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2938 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2939 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2940 secure_cookies: false,
2941 cookie_same_site: crate::config::CookieSameSite::Lax,
2942 csrf_protection: false,
2943 session_timeout: Duration::from_secs(3600),
2944 previous_secret_key: None,
2945 });
2946 let mut framework = AuthFramework::new(config);
2947 framework.initialize().await.unwrap();
2948
2949 let token = framework
2950 .token_manager
2951 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2952 .unwrap();
2953
2954 framework.storage.store_token(&token).await.unwrap();
2956
2957 assert!(framework.validate_token(&token).await.unwrap());
2958 }
2959
2960 #[tokio::test]
2961 async fn test_session_management() {
2962 let config = AuthConfig::new().security(SecurityConfig {
2963 min_password_length: 8,
2964 require_password_complexity: false,
2965 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2966 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2967 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2968 secure_cookies: false,
2969 cookie_same_site: crate::config::CookieSameSite::Lax,
2970 csrf_protection: false,
2971 session_timeout: Duration::from_secs(3600),
2972 previous_secret_key: None,
2973 });
2974 let mut framework = AuthFramework::new(config);
2975 framework.initialize().await.unwrap();
2976
2977 let session_id = framework
2978 .create_session(
2979 "test-user",
2980 Duration::from_secs(3600),
2981 Some("192.168.1.1".to_string()),
2982 Some("Test Agent".to_string()),
2983 )
2984 .await
2985 .unwrap();
2986
2987 let session = framework.get_session(&session_id).await.unwrap();
2988 assert!(session.is_some());
2989
2990 framework.delete_session(&session_id).await.unwrap();
2991 let session = framework.get_session(&session_id).await.unwrap();
2992 assert!(session.is_none());
2993 }
2994
2995 #[tokio::test]
2996 async fn test_grouped_operations_accessors() {
2997 let config = AuthConfig::new().security(SecurityConfig {
2998 min_password_length: 8,
2999 require_password_complexity: false,
3000 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3001 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3002 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3003 secure_cookies: false,
3004 cookie_same_site: crate::config::CookieSameSite::Lax,
3005 csrf_protection: false,
3006 session_timeout: Duration::from_secs(3600),
3007 previous_secret_key: None,
3008 });
3009 let mut framework = AuthFramework::new(config);
3010 framework.initialize().await.unwrap();
3011
3012 let user_id = framework
3013 .users()
3014 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
3015 .await
3016 .unwrap();
3017 assert!(
3018 framework
3019 .users()
3020 .exists_by_username("grouped-user")
3021 .await
3022 .unwrap()
3023 );
3024
3025 let session_id = framework
3026 .sessions()
3027 .create(&user_id, Duration::from_secs(300), None, None)
3028 .await
3029 .unwrap();
3030 assert!(
3031 framework
3032 .sessions()
3033 .get(&session_id)
3034 .await
3035 .unwrap()
3036 .is_some()
3037 );
3038 assert_eq!(
3039 framework
3040 .sessions()
3041 .list_for_user(&user_id)
3042 .await
3043 .unwrap()
3044 .len(),
3045 1
3046 );
3047
3048 framework
3049 .authorization()
3050 .grant(&user_id, "read", "documents")
3051 .await
3052 .unwrap();
3053 let permissions = framework
3054 .authorization()
3055 .effective_permissions(&user_id)
3056 .await
3057 .unwrap();
3058 assert!(
3059 permissions
3060 .iter()
3061 .any(|permission| permission == "read:documents")
3062 );
3063
3064 framework.sessions().delete(&session_id).await.unwrap();
3065 assert!(
3066 framework
3067 .sessions()
3068 .get(&session_id)
3069 .await
3070 .unwrap()
3071 .is_none()
3072 );
3073 }
3074
3075 #[tokio::test]
3076 async fn test_cleanup_expired_data() {
3077 let config = AuthConfig::new().security(SecurityConfig {
3078 min_password_length: 8,
3079 require_password_complexity: false,
3080 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3081 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3082 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3083 secure_cookies: false,
3084 cookie_same_site: crate::config::CookieSameSite::Lax,
3085 csrf_protection: false,
3086 session_timeout: Duration::from_secs(3600),
3087 previous_secret_key: None,
3088 });
3089 let mut framework = AuthFramework::new(config);
3090 framework.initialize().await.unwrap();
3091
3092 assert!(framework.cleanup_expired_data().await.is_ok());
3094 }
3095
3096 #[cfg(feature = "redis-storage")]
3104 #[test]
3105 fn new_validated_redis_fails_closed_without_an_encryption_key() {
3106 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3107 unsafe {
3110 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3111 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3112 }
3113
3114 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3115 config.storage = crate::config::StorageConfig::Redis {
3116 url: "redis://127.0.0.1:1/".to_string(),
3117 key_prefix: "test:".to_string(),
3118 };
3119 let result = AuthFramework::new_validated(config);
3122 assert!(
3123 result.is_err(),
3124 "constructing with Redis storage and no encryption key configured must fail \
3125 closed, not silently build unwrapped (unencrypted) storage"
3126 );
3127 }
3128
3129 #[tokio::test]
3130 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3131 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3132 config.storage_encryption.require_wrapped_storage = true;
3133 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3134 assert!(
3135 framework.initialize().await.is_err(),
3136 "caller-supplied unwrapped storage must be refused when wrapping is required"
3137 );
3138 }
3139
3140 #[tokio::test]
3141 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3142 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3143 required.storage_encryption.require_wrapped_storage = true;
3144 let wrapped: Arc<dyn AuthStorage> =
3145 Arc::new(crate::storage::encryption::EncryptedStorage::new(
3146 MemoryStorage::new(),
3147 crate::storage::encryption::StorageEncryption::new_random(),
3148 false,
3149 false,
3150 ));
3151 let mut framework = AuthFramework::new_with_storage(required, wrapped);
3152 framework.initialize().await.unwrap();
3153
3154 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3156 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3157 framework.initialize().await.unwrap();
3158 }
3159
3160 #[tokio::test]
3161 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3162 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3163 config.storage_encryption.require_wrapped_storage = true;
3164 let mut framework = AuthFramework::new(config);
3165 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3167 framework.initialize().await.unwrap();
3168 }
3169}