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
238pub struct RefreshRedemption {
240 pub claims: crate::tokens::JwtClaims,
242 pub new_refresh_token: String,
244}
245
246impl std::fmt::Debug for RefreshRedemption {
247 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
248 let mut d = f.debug_struct("RefreshRedemption");
249 d.field("claims", &self.claims);
250 d.field(
251 "new_refresh_token",
252 &crate::utils::redact::redacted(&self.new_refresh_token),
253 );
254 d.finish()
255 }
256}
257
258pub(crate) async fn validate_access_jwt_with(
269 token_manager: &TokenManager,
270 storage: &dyn AuthStorage,
271 token: &str,
272 require_account: bool,
273 allow_client_bound: bool,
274) -> Result<crate::tokens::JwtClaims> {
275 let claims = token_manager.validate_jwt_token(token)?;
276 if claims.is_client_bound() && !allow_client_bound {
278 return Err(rejected(
279 "A client-bound token cannot be used here (it was issued to an OAuth client)",
280 ));
281 }
282 if claims.is_refresh_token() {
285 return Err(rejected(
286 "A refresh token cannot be used as an access token",
287 ));
288 }
289 if claims.token_use().is_some() {
290 return Err(rejected("This token is not an access token"));
291 }
292 match storage
293 .get_kv(&format!("revoked_token:{}", claims.jti))
294 .await
295 {
296 Ok(None) => {}
297 Ok(Some(_)) => return Err(rejected("Token has been revoked")),
298 Err(e) => {
299 tracing::error!("Could not check token revocation list: {}", e);
300 return Err(rejected("Unable to verify token status"));
301 }
302 }
303 ensure_account_active(storage, &claims.sub, require_account).await?;
304 Ok(claims)
305}
306
307pub(crate) async fn ensure_account_active(
311 storage: &dyn AuthStorage,
312 user_id: &str,
313 require_record: bool,
314) -> Result<()> {
315 match storage.get_kv(&format!("user:{user_id}")).await {
316 Ok(None) if require_record => Err(rejected("Unknown account")),
317 Ok(None) => match storage.get_kv(&format!("deleted_user:{user_id}")).await {
319 Ok(None) => Ok(()),
320 Ok(Some(_)) => Err(rejected("Account has been deleted")),
321 Err(e) => {
322 tracing::error!("Could not read account tombstone: {}", e);
323 Err(rejected("Unable to verify account status"))
324 }
325 },
326 Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
327 Ok(record) if record["active"].as_bool().unwrap_or(true) => Ok(()),
328 Ok(_) => Err(rejected("Account has been deactivated")),
329 Err(_) => Err(rejected("Unable to verify account status")),
330 },
331 Err(e) => {
332 tracing::error!("Could not read account record: {}", e);
333 Err(rejected("Unable to verify account status"))
334 }
335 }
336}
337
338pub(crate) fn token_value_matches_jwt(token_manager: &TokenManager, token: &AuthToken) -> bool {
342 if !(token.auth_method == "jwt" || token.access_token.contains('.')) {
343 return true;
344 }
345 token_manager
346 .validate_jwt_token(&token.access_token)
347 .map(|claims| {
348 claims.sub == token.user_id
349 && claims.token_use().is_none()
352 && claims.client_id == token.client_id
353 })
354 .unwrap_or(false)
355}
356
357pub(crate) async fn access_token_is_revoked(
360 token_manager: &TokenManager,
361 storage: &dyn AuthStorage,
362 token: &AuthToken,
363) -> Result<bool> {
364 let jti = token_manager
365 .validate_jwt_token(&token.access_token)
366 .map(|claims| claims.jti)
367 .unwrap_or_else(|_| token.token_id.clone());
368 Ok(storage
369 .get_kv(&format!("revoked_token:{jti}"))
370 .await?
371 .is_some())
372}
373
374fn rejected(message: &str) -> AuthError {
375 AuthError::Token(crate::errors::TokenError::Invalid {
376 message: message.to_string(),
377 })
378}
379
380impl AuthFramework {
381 pub fn users(&self) -> UserOperations<'_> {
383 UserOperations { framework: self }
384 }
385
386 pub fn sessions(&self) -> SessionOperations<'_> {
388 SessionOperations { framework: self }
389 }
390
391 pub fn tokens(&self) -> TokenOperations<'_> {
393 TokenOperations { framework: self }
394 }
395
396 pub fn authorization(&self) -> AuthorizationOperations<'_> {
398 AuthorizationOperations { framework: self }
399 }
400
401 pub fn mfa(&self) -> MfaOperations<'_> {
403 MfaOperations { framework: self }
404 }
405
406 pub fn monitoring(&self) -> MonitoringOperations<'_> {
408 MonitoringOperations { framework: self }
409 }
410
411 pub fn audit(&self) -> AuditOperations<'_> {
413 AuditOperations { framework: self }
414 }
415
416 pub fn audit_storage(&self) -> Arc<dyn crate::audit::AuditStorage> {
420 self.audit_manager.storage().clone()
421 }
422
423 pub(crate) async fn record_audit_event(&self, event: crate::audit::AuditEvent) {
426 let kind = event.event_type.clone();
427 if let Err(e) = self.audit_manager.log_event(event).await {
428 tracing::warn!("Could not record the {kind} audit event: {e}");
429 }
430 }
431
432 pub(crate) async fn query_audit_events(
434 &self,
435 query: &crate::audit::AuditQuery,
436 ) -> Result<Vec<crate::audit::AuditEvent>> {
437 self.audit_manager.query_events(query).await
438 }
439
440 pub fn maintenance(&self) -> MaintenanceOperations<'_> {
442 MaintenanceOperations { framework: self }
443 }
444
445 pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
447 self.runtime_config.read().await.clone()
448 }
449
450 #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
451 #[doc(hidden)]
452 pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
453 self.runtime_config().await
454 }
455
456 pub async fn update_runtime_config(
461 &self,
462 update: crate::config::RuntimeConfig,
463 ) -> Result<crate::config::RuntimeConfig> {
464 if update.token_lifetime_secs == 0 {
466 return Err(AuthError::config("token_lifetime_secs must be > 0"));
467 }
468 if update.refresh_token_lifetime_secs == 0 {
469 return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
470 }
471 if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
472 return Err(AuthError::config(
473 "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
474 ));
475 }
476 if update.min_password_length == 0 {
477 return Err(AuthError::config("min_password_length must be > 0"));
478 }
479 let mut cfg = self.runtime_config.write().await;
480 *cfg = update.clone();
481 Ok(update)
482 }
483
484 pub fn admin(&self) -> AdminOperations<'_> {
486 AdminOperations { framework: self }
487 }
488
489 pub fn new(config: AuthConfig) -> Self {
497 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
499 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
500 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
501
502 let ephemeral_secret = {
508 let rng = ring::rand::SystemRandom::new();
509 let mut buf = [0u8; 32];
510 ring::rand::SecureRandom::fill(&rng, &mut buf)
511 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
512 buf
513 };
514 let token_manager =
515 TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
516
517 let user_manager = crate::auth_modular::user_manager::UserManager::new(
518 storage.clone(),
519 config.security.password_hash_algorithm.clone(),
520 );
521 let session_manager =
522 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
523 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
524 let authorization_manager =
525 crate::auth_modular::authorization_manager::AuthorizationManager::new(
526 Arc::new(RwLock::new(PermissionChecker::new())),
527 storage.clone(),
528 );
529
530 Self {
531 config,
532 methods: HashMap::new(),
533 token_manager,
534 storage,
535 authorization_manager,
536 rate_limiter: None, monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
538 crate::monitoring::MonitoringConfig::default(),
539 )),
540 audit_manager,
541 #[cfg(feature = "api-server")]
542 security_manager: Arc::new(crate::api::SecurityManager::new()),
543 runtime_config: Arc::new(tokio::sync::RwLock::new(
544 crate::config::RuntimeConfig::default(),
545 )),
546 user_manager,
547 session_manager,
548 mfa_manager,
549 initialized: false,
550 storage_overridden: false,
551 storage_from_caller: false,
552 }
553 }
554
555 pub fn new_validated(config: AuthConfig) -> Result<Self> {
560 config.validate().map_err(|e| {
562 AuthError::configuration(format!("Configuration validation failed: {}", e))
563 })?;
564
565 let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
567
568 let mut token_manager =
569 TokenManager::new_hmac(¤t_secret_bytes, "auth-framework", "auth-framework");
570
571 if let Some(prev_secret) = &config.security.previous_secret_key {
573 token_manager =
575 TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
576 token_manager.rotate_hmac_key(¤t_secret_bytes);
577 }
578
579 let storage: Arc<dyn AuthStorage> = match &config.storage {
588 #[cfg(feature = "redis-storage")]
589 crate::config::StorageConfig::Redis { url, key_prefix } => {
590 let redis: Arc<dyn AuthStorage> = Arc::new(
591 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
592 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
593 })?,
594 );
595 crate::storage::factory::wrap_with_encryption_if_enabled(
596 redis,
597 &config.storage_encryption,
598 )?
599 }
600 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
601 };
602
603 let rate_limiter = if config.rate_limiting.enabled {
605 Some(RateLimiter::new(
606 config.rate_limiting.max_requests,
607 config.rate_limiting.window,
608 ))
609 } else {
610 None
611 };
612
613 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
615 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
616
617 let user_manager = crate::auth_modular::user_manager::UserManager::new(
618 storage.clone(),
619 config.security.password_hash_algorithm.clone(),
620 );
621 let session_manager =
622 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
623 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
624 let authorization_manager =
625 crate::auth_modular::authorization_manager::AuthorizationManager::new(
626 Arc::new(RwLock::new(PermissionChecker::new())),
627 storage.clone(),
628 );
629
630 Ok(Self {
631 config: config.clone(),
632 methods: HashMap::new(),
633 token_manager,
634 storage,
635 authorization_manager,
636 rate_limiter,
637 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
638 crate::monitoring::MonitoringConfig::default(),
639 )),
640 audit_manager,
641 #[cfg(feature = "api-server")]
642 security_manager: Arc::new(crate::api::SecurityManager::new()),
643 runtime_config: Arc::new(tokio::sync::RwLock::new(
644 crate::config::RuntimeConfig::from_auth_config(&config),
645 )),
646 user_manager,
647 session_manager,
648 mfa_manager,
649 initialized: false,
650 storage_overridden: false,
651 storage_from_caller: false,
652 })
653 }
654
655 pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
662 self.storage = storage.clone();
663 self.user_manager = crate::auth_modular::user_manager::UserManager::new(
664 storage.clone(),
665 self.config.security.password_hash_algorithm.clone(),
666 );
667 self.session_manager =
668 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
669 self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
670 self.authorization_manager =
671 crate::auth_modular::authorization_manager::AuthorizationManager::new(
672 Arc::new(RwLock::new(PermissionChecker::new())),
673 storage,
674 );
675 self.storage_overridden = true;
676 self.storage_from_caller = true;
677 }
678
679 pub(crate) fn replace_storage_from_factory(
683 &mut self,
684 storage: std::sync::Arc<dyn AuthStorage>,
685 ) {
686 self.replace_storage(storage);
687 self.storage_from_caller = false;
688 }
689
690 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
697 self.session_manager.set_distributed_store(store);
698 }
699
700 pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
702 let mut framework = Self::new(config);
703 framework.replace_storage(storage);
704 framework
705 }
706
707 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
709 let name = name.into();
710 info!("Registering authentication method: {}", name);
711
712 if let Err(e) = method.validate_config() {
714 error!("Method '{}' configuration validation failed: {}", name, e);
715 return;
716 }
717
718 self.methods.insert(name, method);
719 }
720
721 fn require_initialized(&self) -> Result<()> {
727 if self.initialized {
728 Ok(())
729 } else {
730 Err(AuthError::configuration(
731 "Framework not initialized. Call `initialize().await` first, \
732 or use `AuthFramework::builder().build().await` which initializes automatically.",
733 ))
734 }
735 }
736
737 pub async fn initialize(&mut self) -> Result<()> {
747 if self.initialized {
748 return Ok(());
749 }
750
751 info!("Initializing authentication framework");
752
753 self.config.validate().map_err(|e| {
755 AuthError::configuration(format!("Configuration validation failed: {}", e))
756 })?;
757
758 let token_manager = match resolve_jwt_secret_bytes(&self.config) {
760 Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
761 Err(_) => {
762 if Self::is_production_environment() {
763 return Err(AuthError::configuration(
764 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
765 Generate a secure secret with: openssl rand -base64 32\n\
766 Set it with: export JWT_SECRET=\"your-secret-here\"",
767 ));
768 }
769 warn!("No JWT secret configured, using development-only default");
770 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
771 warn!("This configuration is NOT SECURE and should only be used in development!");
772 self.token_manager.clone()
773 }
774 };
775
776 self.token_manager = token_manager;
778
779 if self.storage_from_caller {
783 crate::storage::factory::check_overridden_storage(
784 &self.storage,
785 &self.config.storage_encryption,
786 )?;
787 }
788
789 if !self.storage_overridden {
791 let storage = crate::storage::factory::build_storage_backend_with_encryption(
792 &self.config.storage,
793 None,
794 &self.config.storage_encryption,
795 )
796 .await?;
797 self.replace_storage(storage);
798 self.storage_overridden = false;
799 self.storage_from_caller = false;
800 }
801
802 if self.config.rate_limiting.enabled {
804 self.rate_limiter = Some(RateLimiter::new(
805 self.config.rate_limiting.max_requests,
806 self.config.rate_limiting.window,
807 ));
808 }
809
810 self.authorization_manager.create_default_roles().await;
812
813 self.authorization_manager.load_persisted_roles().await?;
815
816 self.cleanup_expired_data().await?;
818
819 self.initialized = true;
820 info!("Authentication framework initialized successfully");
821
822 Ok(())
823 }
824
825 pub async fn authenticate(
853 &self,
854 method_name: &str,
855 credential: Credential,
856 ) -> Result<AuthResult> {
857 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
858 .await
859 }
860
861 pub async fn authenticate_with_metadata(
863 &self,
864 method_name: &str,
865 credential: Credential,
866 metadata: CredentialMetadata,
867 ) -> Result<AuthResult> {
868 use std::time::Instant;
869 use tokio::time::{Duration as TokioDuration, sleep};
870
871 let start_time = Instant::now();
872
873 self.monitoring_manager.record_auth_request().await;
875
876 self.require_initialized()?;
877
878 let result = self
880 .authenticate_internal(method_name, credential, metadata)
881 .await;
882
883 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
886 if elapsed < min_duration {
887 sleep(min_duration - elapsed).await;
888 }
889
890 if let Ok(ref auth_result) = result {
892 match auth_result {
893 AuthResult::Success(token) => {
894 self.monitoring_manager
895 .record_auth_success(&token.user_id, elapsed)
896 .await;
897 }
898 AuthResult::Failure(reason) => {
899 self.monitoring_manager
900 .record_auth_failure(None, reason)
901 .await;
902 }
903 _ => {} }
905 }
906
907 result
908 }
909
910 async fn authenticate_internal(
912 &self,
913 method_name: &str,
914 credential: Credential,
915 metadata: CredentialMetadata,
916 ) -> Result<AuthResult> {
917 if let Some(ref rate_limiter) = self.rate_limiter {
919 let rate_key = format!(
920 "auth:{}:{}",
921 method_name,
922 metadata.client_ip.as_deref().unwrap_or("unknown")
923 );
924
925 if !rate_limiter.is_allowed(&rate_key) {
926 warn!(
927 "Rate limit exceeded for method '{}' from IP {:?}",
928 method_name, metadata.client_ip
929 );
930 return Err(AuthError::rate_limit("Too many authentication attempts"));
931 }
932 }
933
934 if method_name == "password"
938 && let Credential::Password {
939 ref username,
940 ref password,
941 } = credential
942 {
943 return self
944 .authenticate_password_builtin(username, password, &metadata)
945 .await;
946 }
947
948 if method_name == "jwt" {
949 return match credential {
950 Credential::Jwt { token } | Credential::Bearer { token } => {
951 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
952 .await
953 }
954 _ => Ok(AuthResult::Failure(
955 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
956 )),
957 };
958 }
959
960 if matches!(method_name, "api_key" | "api-key") {
961 return match credential {
962 Credential::ApiKey { key } => {
963 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
964 .await
965 }
966 _ => Ok(AuthResult::Failure(
967 "API key authentication expects Credential::api_key".to_string(),
968 )),
969 };
970 }
971
972 if method_name == "oauth2" {
973 return self
974 .authenticate_oauth2_builtin(credential, &metadata)
975 .await;
976 }
977
978 let method = self.methods.get(method_name).ok_or_else(|| {
980 AuthError::auth_method(method_name, "Authentication method not found".to_string())
981 })?;
982
983 debug!(
985 "Authentication attempt with method '{}' for credential: {}",
986 method_name,
987 credential.safe_display()
988 );
989
990 let result = method.authenticate(credential, metadata.clone()).await?;
992
993 match &result {
995 MethodResult::Success(token) => {
996 info!(
997 "Authentication successful for user '{}' with method '{}'",
998 token.user_id, method_name
999 );
1000
1001 self.storage.store_token(token).await?;
1003
1004 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
1006 .await;
1007
1008 Ok(AuthResult::Success(token.clone()))
1009 }
1010
1011 MethodResult::MfaRequired(challenge) => {
1012 info!(
1013 "MFA required for user '{}' with method '{}'",
1014 challenge.user_id, method_name
1015 );
1016
1017 self.guard_and_store_mfa_challenge((**challenge).clone())
1019 .await?;
1020
1021 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
1023 .await;
1024
1025 Ok(AuthResult::MfaRequired(challenge.clone()))
1026 }
1027
1028 MethodResult::Failure { reason } => {
1029 warn!(
1030 "Authentication failed for method '{}': {}",
1031 method_name, reason
1032 );
1033
1034 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
1036 .await;
1037
1038 Ok(AuthResult::Failure(reason.clone()))
1039 }
1040 }
1041 }
1042
1043 async fn authenticate_jwt_builtin(
1044 &self,
1045 token: &str,
1046 metadata: &CredentialMetadata,
1047 auth_method: &str,
1048 ) -> Result<AuthResult> {
1049 if token.is_empty() {
1050 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
1051 }
1052
1053 match validate_access_jwt_with(
1054 &self.token_manager,
1055 self.storage.as_ref(),
1056 token,
1057 false,
1058 false,
1059 )
1060 .await
1061 {
1062 Ok(claims) => {
1063 let token =
1064 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
1065 Ok(AuthResult::Success(Box::new(token)))
1066 }
1067 Err(error) => {
1068 if let Some(reason) = Self::credential_failure_reason(&error) {
1069 Ok(AuthResult::Failure(reason))
1070 } else {
1071 Err(error)
1072 }
1073 }
1074 }
1075 }
1076
1077 async fn authenticate_api_key_builtin(
1078 &self,
1079 api_key: &str,
1080 metadata: &CredentialMetadata,
1081 auth_method: &str,
1082 ) -> Result<AuthResult> {
1083 if api_key.is_empty() {
1084 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
1085 }
1086
1087 match self.validate_api_key(api_key).await {
1088 Ok(user) => {
1089 let scopes: Vec<String> = if user.roles.is_empty() {
1090 vec!["api_user".to_string()]
1091 } else {
1092 user.roles.to_vec()
1093 };
1094 let mut token = self
1095 .token_manager
1096 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
1097 .with_roles(user.roles)
1098 .with_scopes(scopes);
1099 token.metadata.issued_ip = metadata.client_ip.clone();
1100 token.metadata.user_agent = metadata.user_agent.clone();
1101 Ok(AuthResult::Success(Box::new(token)))
1102 }
1103 Err(error) => {
1104 if let Some(reason) = Self::credential_failure_reason(&error) {
1105 Ok(AuthResult::Failure(reason))
1106 } else {
1107 Err(error)
1108 }
1109 }
1110 }
1111 }
1112
1113 async fn authenticate_oauth2_builtin(
1114 &self,
1115 credential: Credential,
1116 metadata: &CredentialMetadata,
1117 ) -> Result<AuthResult> {
1118 match credential {
1119 Credential::OAuth {
1120 authorization_code, ..
1121 } => {
1122 if authorization_code.is_empty() {
1123 return Ok(AuthResult::Failure(
1124 "OAuth authorization code cannot be empty".to_string(),
1125 ));
1126 }
1127 Ok(AuthResult::Failure(
1128 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
1129 .to_string(),
1130 ))
1131 }
1132 Credential::OAuthRefresh { refresh_token } => {
1133 if refresh_token.is_empty() {
1134 return Ok(AuthResult::Failure(
1135 "OAuth refresh token cannot be empty".to_string(),
1136 ));
1137 }
1138 Ok(AuthResult::Failure(
1139 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
1140 .to_string(),
1141 ))
1142 }
1143 Credential::Jwt { token }
1144 | Credential::Bearer { token }
1145 | Credential::OpenIdConnect { id_token: token, .. } => {
1146 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
1147 }
1148 _ => Ok(AuthResult::Failure(
1149 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
1150 .to_string(),
1151 )),
1152 }
1153 }
1154
1155 fn build_validated_jwt_auth_token(
1156 raw_token: &str,
1157 claims: crate::tokens::JwtClaims,
1158 metadata: &CredentialMetadata,
1159 auth_method: &str,
1160 ) -> AuthToken {
1161 let crate::tokens::JwtClaims {
1162 sub,
1163 iss,
1164 exp,
1165 iat,
1166 jti,
1167 scope,
1168 permissions,
1169 roles,
1170 client_id,
1171 ..
1172 } = claims;
1173
1174 let now = chrono::Utc::now();
1175 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
1176 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
1177 .unwrap_or(now + chrono::Duration::hours(1));
1178 let lifetime = (expires_at - now)
1179 .to_std()
1180 .unwrap_or_else(|_| Duration::from_secs(1));
1181 let scopes = if scope.trim().is_empty() {
1182 Vec::new()
1183 } else {
1184 scope.split_whitespace().map(str::to_string).collect()
1185 };
1186
1187 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
1188 .with_scopes(scopes)
1189 .with_permissions(permissions.unwrap_or_default())
1190 .with_roles(roles.unwrap_or_default());
1191 token.token_id = jti;
1192 token.subject = Some(sub);
1193 token.issuer = Some(iss);
1194 token.issued_at = issued_at;
1195 token.expires_at = expires_at;
1196 token.metadata.issued_ip = metadata.client_ip.clone();
1197 token.metadata.user_agent = metadata.user_agent.clone();
1198 if let Some(client_id) = client_id {
1199 token.client_id = Some(client_id);
1200 }
1201 token
1202 }
1203
1204 fn credential_failure_reason(error: &AuthError) -> Option<String> {
1205 match error {
1206 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
1207 AuthError::Validation { message } => Some(message.clone()),
1208 AuthError::UserNotFound => Some("User not found".to_string()),
1209 _ => None,
1210 }
1211 }
1212
1213 async fn authenticate_password_builtin(
1215 &self,
1216 username: &str,
1217 password: &str,
1218 metadata: &CredentialMetadata,
1219 ) -> Result<AuthResult> {
1220 use crate::auth_modular::user_manager::CredentialCheckResult;
1221
1222 if username.is_empty() || password.is_empty() {
1223 return Ok(AuthResult::Failure(
1224 "Username or password cannot be empty".to_string(),
1225 ));
1226 }
1227
1228 match self
1229 .user_manager
1230 .verify_login_credentials(username, password)
1231 .await?
1232 {
1233 None => {
1234 self.log_audit_event("auth_failure", "unknown", "password", metadata)
1235 .await;
1236 Ok(AuthResult::Failure(
1237 "Invalid username or password".to_string(),
1238 ))
1239 }
1240 Some(CredentialCheckResult {
1241 ref user_id,
1242 mfa_enabled: true,
1243 }) => {
1244 let now = chrono::Utc::now();
1245 let challenge = MfaChallenge {
1246 id: crate::utils::string::generate_id(Some("mfa")),
1247 mfa_type: crate::methods::MfaType::MultiMethod,
1248 user_id: user_id.clone(),
1249 created_at: now,
1250 expires_at: now + chrono::Duration::minutes(5),
1251 attempts: 0,
1252 max_attempts: 5,
1253 code_hash: None,
1254 message: Some(
1255 "Provide your current TOTP code or a backup code to complete login"
1256 .to_string(),
1257 ),
1258 data: HashMap::new(),
1259 };
1260 self.guard_and_store_mfa_challenge(challenge.clone())
1261 .await?;
1262 self.log_audit_event("mfa_required", user_id, "password", metadata)
1263 .await;
1264 info!(
1265 "Built-in password authentication requires MFA for user: {}",
1266 username
1267 );
1268 Ok(AuthResult::MfaRequired(Box::new(challenge)))
1269 }
1270 Some(CredentialCheckResult {
1271 ref user_id,
1272 mfa_enabled: false,
1273 }) => {
1274 let token = self
1275 .mint_and_store_token(
1276 user_id,
1277 vec!["read".to_string(), "write".to_string()],
1278 "password",
1279 None,
1280 )
1281 .await?;
1282 self.monitoring_manager.record_auth_request().await;
1283 self.log_audit_event("auth_success", user_id, "password", metadata)
1284 .await;
1285 info!(
1286 "Built-in password authentication successful for user: {}",
1287 username
1288 );
1289 Ok(AuthResult::Success(Box::new(token)))
1290 }
1291 }
1292 }
1293
1294 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1296 debug!("Completing MFA for challenge '{}'", challenge.id);
1297
1298 let stored_challenge = self
1301 .mfa_manager
1302 .begin_attempt(&challenge.id)
1303 .await?
1304 .ok_or(MfaError::ChallengeExpired)?;
1305
1306 if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1307 if stored_challenge.attempts >= stored_challenge.max_attempts {
1308 self.mfa_manager.remove_challenge(&challenge.id).await?;
1309 }
1310 return Err(MfaError::InvalidCode.into());
1311 }
1312
1313 self.mfa_manager.remove_challenge(&challenge.id).await?;
1314
1315 let user_id = stored_challenge.user_id.as_str();
1316 let scopes = self
1317 .user_manager
1318 .get_user_roles(user_id)
1319 .await
1320 .unwrap_or_else(|_| vec!["user".to_string()]);
1321
1322 let token = self
1323 .mint_and_store_token(user_id, scopes, "mfa", None)
1324 .await?;
1325
1326 info!("MFA completed successfully for user '{}'", user_id);
1327 Ok(token)
1328 }
1329
1330 pub async fn mfa_challenge_owner(&self, challenge_id: &str) -> Option<String> {
1332 self.mfa_manager
1333 .get_challenge(challenge_id)
1334 .await
1335 .ok()
1336 .flatten()
1337 .map(|c| c.user_id)
1338 }
1339
1340 pub(crate) async fn discard_mfa_challenge(&self, challenge_id: &str) {
1342 let _ = self.mfa_manager.remove_challenge(challenge_id).await;
1343 }
1344
1345 pub async fn complete_mfa_by_id(
1347 &self,
1348 challenge_id: &str,
1349 mfa_code: &str,
1350 ) -> Result<AuthToken> {
1351 let challenge = self
1352 .mfa_manager
1353 .get_challenge(challenge_id)
1354 .await?
1355 .ok_or(MfaError::ChallengeExpired)?;
1356
1357 self.complete_mfa(challenge, mfa_code).await
1358 }
1359
1360 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1362 self.require_initialized()?;
1363 let valid = token.is_valid()
1364 && self.token_manager.validate_auth_token(token).is_ok()
1365 && token_value_matches_jwt(&self.token_manager, token)
1366 && !access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token).await?
1367 && self.touch_stored_token(token).await?;
1368 self.monitoring_manager.record_token_validation(valid).await;
1369 Ok(valid)
1370 }
1371
1372 async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1373 let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1374 return Ok(false);
1375 };
1376 if stored.is_revoked() {
1377 return Ok(false);
1378 }
1379 if stored.access_token != token.access_token || stored.user_id != token.user_id {
1381 return Ok(false);
1382 }
1383 stored.mark_used();
1384 self.storage.update_token(&stored).await?;
1385 Ok(true)
1386 }
1387
1388 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1390 if !self.validate_token(token).await? {
1391 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1392 }
1393
1394 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1395
1396 match self.user_manager.get_user_info(&token_info.user_id).await {
1399 Ok(mut info) => {
1400 if !token_info.attributes.is_empty() {
1402 let string_attrs: HashMap<String, String> = token_info
1403 .attributes
1404 .into_iter()
1405 .map(|(k, v)| {
1406 (
1407 k,
1408 v.as_str()
1409 .map(|s| s.to_string())
1410 .unwrap_or_else(|| v.to_string()),
1411 )
1412 })
1413 .collect();
1414 info.attributes = string_attrs.into();
1415 }
1416 Ok(info)
1417 }
1418 Err(_) => {
1419 let string_attrs: HashMap<String, String> = token_info
1420 .attributes
1421 .into_iter()
1422 .map(|(k, v)| {
1423 (
1424 k,
1425 v.as_str()
1426 .map(|s| s.to_string())
1427 .unwrap_or_else(|| v.to_string()),
1428 )
1429 })
1430 .collect();
1431 Ok(UserInfo {
1432 id: token_info.user_id,
1433 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1434 email: token_info.email,
1435 name: token_info.name,
1436 roles: token_info.roles.into(),
1437 active: false,
1438 email_verified: false,
1439 attributes: string_attrs.into(),
1440 })
1441 }
1442 }
1443 }
1444
1445 pub async fn check_permission(
1472 &self,
1473 token: &AuthToken,
1474 action: &str,
1475 resource: &str,
1476 ) -> Result<bool> {
1477 let Some(proof) = self.validated_token(token).await? else {
1478 return Ok(false);
1479 };
1480 self.check_validated_permission(&proof, action, resource)
1481 .await
1482 }
1483
1484 pub async fn validated_token(
1486 &self,
1487 token: &AuthToken,
1488 ) -> Result<Option<crate::tokens::ValidatedToken>> {
1489 Ok(self
1490 .validate_token(token)
1491 .await?
1492 .then(|| crate::tokens::ValidatedToken::new(token.clone())))
1493 }
1494
1495 pub async fn check_validated_permission(
1497 &self,
1498 proof: &crate::tokens::ValidatedToken,
1499 action: &str,
1500 resource: &str,
1501 ) -> Result<bool> {
1502 self.authorization_manager
1503 .check_validated_permission(proof, action, resource)
1504 .await
1505 }
1506
1507 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1509 self.require_initialized()?;
1510 debug!("Refreshing token for user '{}'", token.user_id);
1511
1512 if let Some(method) = self.methods.get(&token.auth_method)
1514 && method.supports_refresh()
1515 && let Some(ref refresh_token) = token.refresh_token
1516 {
1517 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1518 self.storage.store_token(&new_token).await?;
1519 return Ok(new_token);
1520 }
1521
1522 if !self.validate_token(token).await? {
1526 return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1527 message: "Cannot refresh a token that is not valid".to_string(),
1528 }));
1529 }
1530 let stored = self
1532 .storage
1533 .get_token(&token.token_id)
1534 .await?
1535 .ok_or_else(|| {
1536 AuthError::Token(crate::errors::TokenError::Invalid {
1537 message: "Cannot refresh a token that is not stored".to_string(),
1538 })
1539 })?;
1540 let new_token = self.token_manager.refresh_token(&stored)?;
1541 self.storage.store_token(&new_token).await?;
1542
1543 info!("Token refreshed for user '{}'", token.user_id);
1544
1545 Ok(new_token)
1546 }
1547
1548 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1550 self.require_initialized()?;
1551 debug!("Revoking token for user '{}'", token.user_id);
1552
1553 let mut revoked_token = token.clone();
1555 revoked_token.revoke(Some("Manual revocation".to_string()));
1556
1557 self.storage.update_token(&revoked_token).await?;
1559
1560 let jti = self
1563 .token_manager
1564 .validate_jwt_token(&token.access_token)
1565 .map(|claims| claims.jti)
1566 .unwrap_or_else(|_| token.token_id.clone());
1567 let remaining = (token.expires_at - chrono::Utc::now())
1568 .to_std()
1569 .unwrap_or_default()
1570 .max(Duration::from_secs(60));
1571 self.storage
1572 .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1573 .await?;
1574
1575 info!("Token revoked for user '{}'", token.user_id);
1576
1577 Ok(())
1578 }
1579
1580 pub async fn create_api_key(
1582 &self,
1583 user_id: &str,
1584 expires_in: Option<Duration>,
1585 ) -> Result<String> {
1586 self.require_initialized()?;
1587 self.user_manager.create_api_key(user_id, expires_in).await
1588 }
1589
1590 pub async fn create_api_key_with_role(
1597 &self,
1598 user_id: &str,
1599 role: &str,
1600 expires_in: Option<Duration>,
1601 ) -> Result<String> {
1602 self.require_initialized()?;
1603 self.user_manager
1604 .create_api_key_with_role(user_id, role, expires_in)
1605 .await
1606 }
1607
1608 pub async fn rotate_api_key(&self, old_key: &str) -> Result<String> {
1614 self.require_initialized()?;
1615 self.user_manager.rotate_api_key(old_key).await
1616 }
1617
1618 pub async fn rotate_api_key_with_expiry(
1620 &self,
1621 old_key: &str,
1622 expires_in: Option<Duration>,
1623 ) -> Result<String> {
1624 self.require_initialized()?;
1625 self.user_manager
1626 .rotate_api_key_with_expiry(old_key, expires_in)
1627 .await
1628 }
1629
1630 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1632 self.require_initialized()?;
1633 self.user_manager.validate_api_key(api_key).await
1634 }
1635
1636 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1638 self.require_initialized()?;
1639 self.user_manager.revoke_api_key(api_key).await
1640 }
1641
1642 pub async fn create_session(
1644 &self,
1645 user_id: &str,
1646 expires_in: Duration,
1647 ip_address: Option<String>,
1648 user_agent: Option<String>,
1649 ) -> Result<String> {
1650 self.require_initialized()?;
1651 let (session_id, new_total) = self
1652 .session_manager
1653 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1654 .await?;
1655 self.monitoring_manager
1656 .update_session_count(new_total)
1657 .await;
1658 Ok(session_id)
1659 }
1660
1661 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1681 self.create_session(
1682 req.get_user_id(),
1683 req.get_expires_in(),
1684 req.get_ip_address().map(|s| s.to_string()),
1685 req.get_user_agent().map(|s| s.to_string()),
1686 )
1687 .await
1688 }
1689
1690 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1692 self.require_initialized()?;
1693 self.session_manager.get_session(session_id).await
1694 }
1695
1696 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1698 self.require_initialized()?;
1699 self.session_manager.delete_session(session_id).await?;
1700
1701 let remaining = self
1702 .session_manager
1703 .count_active_sessions()
1704 .await
1705 .unwrap_or(0);
1706 self.monitoring_manager
1707 .update_session_count(remaining)
1708 .await;
1709
1710 Ok(())
1711 }
1712
1713 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1715 self.require_initialized()?;
1716 self.storage.list_user_tokens(user_id).await
1717 }
1718
1719 pub async fn cleanup_expired_data(&self) -> Result<()> {
1721 debug!("Cleaning up expired data");
1722
1723 self.storage.cleanup_expired().await?;
1725
1726 self.mfa_manager.cleanup_expired_challenges().await?;
1728
1729 self.session_manager.cleanup_expired_sessions().await?;
1731
1732 if let Some(ref rate_limiter) = self.rate_limiter {
1734 let _ = rate_limiter.cleanup().ok();
1735 }
1736
1737 Ok(())
1738 }
1739
1740 fn is_production_environment() -> bool {
1743 if let Ok(env) = std::env::var("ENVIRONMENT")
1744 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1745 {
1746 return true;
1747 }
1748 if let Ok(env) = std::env::var("ENV")
1749 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1750 {
1751 return true;
1752 }
1753 if let Ok(env) = std::env::var("NODE_ENV")
1754 && env.to_lowercase() == "production"
1755 {
1756 return true;
1757 }
1758 if let Ok(env) = std::env::var("RUST_ENV")
1759 && env.to_lowercase() == "production"
1760 {
1761 return true;
1762 }
1763 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1764 || std::env::var("DOCKER_CONTAINER").is_ok()
1765 }
1766
1767 pub async fn get_stats(&self) -> Result<AuthStats> {
1769 let mut stats = AuthStats::default();
1770
1771 if let Err(e) = self.storage.cleanup_expired().await {
1772 warn!("Failed to cleanup expired data: {}", e);
1773 }
1774 if let Some(rate_limiter) = &self.rate_limiter {
1775 let _ = rate_limiter.cleanup().ok();
1776 }
1777
1778 let active_sessions = self
1779 .session_manager
1780 .count_active_sessions()
1781 .await
1782 .unwrap_or(0) as u32;
1783
1784 stats.registered_methods = self.methods.keys().cloned().collect();
1785 stats.active_sessions = active_sessions as u64;
1786 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1787 let perf = self.monitoring_manager.get_performance_metrics();
1789 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1790 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1791 + perf.get("auth_failures").copied().unwrap_or(0);
1792
1793 Ok(stats)
1794 }
1795
1796 pub fn token_manager(&self) -> &TokenManager {
1801 &self.token_manager
1802 }
1803
1804 pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1811 let claims = self.token_manager.validate_jwt_token(token)?;
1812 if !claims.is_refresh_token() {
1813 return Err(rejected("Expected a refresh token"));
1814 }
1815 let read = |key: String| async move {
1816 self.storage.get_kv(&key).await.map_err(|e| {
1817 tracing::error!("Could not read refresh-token state: {}", e);
1818 rejected("Unable to verify token status")
1819 })
1820 };
1821 let family = claims.refresh_family().to_string();
1822 if read(format!("revoked_token:{}", claims.jti))
1823 .await?
1824 .is_some()
1825 || read(format!("revoked_family:{family}")).await?.is_some()
1826 {
1827 return Err(rejected("Refresh token has been revoked"));
1828 }
1829 ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1830
1831 let remaining =
1832 Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1833 let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1835 let consumed_key = format!("refresh_consumed:{}", claims.jti);
1836 let first_use = self
1842 .storage
1843 .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1844 .await
1845 .map_err(|e| {
1846 tracing::error!("Could not record refresh token use: {}", e);
1847 rejected("Unable to record refresh token use")
1848 })?;
1849 if !first_use {
1850 warn!(
1851 "Refresh token reuse detected for user '{}'; revoking its chain",
1852 claims.sub
1853 );
1854 if let Err(e) = self
1855 .storage
1856 .store_kv(
1857 &format!("revoked_family:{family}"),
1858 b"reuse",
1859 Some(family_ttl),
1860 )
1861 .await
1862 {
1863 tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1864 }
1865 return Err(rejected("Refresh token has already been used"));
1866 }
1867
1868 let lifetime = self.config.refresh_token_lifetime;
1869 let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1870 &claims.sub,
1871 Some(lifetime),
1872 &family,
1873 )?;
1874 Ok(RefreshRedemption {
1875 claims,
1876 new_refresh_token,
1877 })
1878 }
1879
1880 pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1887 validate_access_jwt_with(
1888 &self.token_manager,
1889 self.storage.as_ref(),
1890 token,
1891 true,
1892 false,
1893 )
1894 .await
1895 }
1896
1897 pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1903 validate_access_jwt_with(
1904 &self.token_manager,
1905 self.storage.as_ref(),
1906 token,
1907 true,
1908 true,
1909 )
1910 .await
1911 }
1912
1913 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1923 self.user_manager.validate_username(username).await
1924 }
1925
1926 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1933 self.user_manager.validate_display_name(display_name).await
1934 }
1935
1936 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1945 self.user_manager.validate_password_strength(password).await
1946 }
1947
1948 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1953 Ok(crate::utils::validation::validate_user_input(input))
1954 }
1955
1956 pub async fn create_auth_token(
1976 &self,
1977 user_id: impl Into<String>,
1978 scopes: impl Into<crate::types::Scopes>,
1979 method_name: impl Into<String>,
1980 lifetime: Option<Duration>,
1981 ) -> Result<AuthToken> {
1982 let method_name = method_name.into();
1983 let user_id = user_id.into();
1984 let scopes: crate::types::Scopes = scopes.into();
1985
1986 let auth_method = self
1988 .methods
1989 .get(&method_name)
1990 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1991 auth_method.validate_config()?;
1992
1993 const MAX_TOKENS_PER_USER: usize = 100;
1995 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1996 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1997 warn!(
1998 "User '{}' has reached maximum tokens ({})",
1999 user_id, MAX_TOKENS_PER_USER
2000 );
2001 return Err(AuthError::rate_limit(
2002 "Maximum tokens per user exceeded. Please revoke unused tokens.",
2003 ));
2004 }
2005
2006 let token = self
2007 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
2008 .await?;
2009 self.monitoring_manager
2010 .record_token_creation(&method_name)
2011 .await;
2012 Ok(token)
2013 }
2014
2015 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
2025 self.mfa_manager.sms.initiate_challenge(user_id).await
2026 }
2027
2028 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
2036 self.mfa_manager.sms.verify_code(challenge_id, code).await
2037 }
2038
2039 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
2046 self.mfa_manager.email.register_email(user_id, email).await
2047 }
2048
2049 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
2060 self.mfa_manager.totp.generate_secret(user_id).await
2061 }
2062
2063 pub async fn generate_totp_qr_code(
2071 &self,
2072 user_id: &str,
2073 app_name: &str,
2074 secret: &str,
2075 ) -> Result<String> {
2076 self.mfa_manager
2077 .totp
2078 .generate_qr_code(user_id, app_name, secret)
2079 .await
2080 }
2081
2082 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
2087 self.mfa_manager.totp.generate_code(secret).await
2088 }
2089
2090 pub async fn generate_totp_code_for_window(
2094 &self,
2095 secret: &str,
2096 time_window: Option<u64>,
2097 ) -> Result<String> {
2098 self.mfa_manager
2099 .totp
2100 .generate_code_for_window(secret, time_window)
2101 .await
2102 }
2103
2104 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2112 self.mfa_manager.totp.verify_code(user_id, code).await
2113 }
2114
2115 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2120 debug!("Checking IP rate limit for '{}'", ip);
2121 let Some(ref rate_limiter) = self.rate_limiter else {
2122 return Ok(true);
2123 };
2124 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2125 warn!("Rate limit exceeded for IP: {}", ip);
2126 return Err(AuthError::rate_limit(format!(
2127 "Too many requests from IP {}. Please try again later.",
2128 ip
2129 )));
2130 }
2131 Ok(true)
2132 }
2133
2134 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2139 debug!("Getting security metrics");
2140 let mut metrics = std::collections::HashMap::new();
2141 let total_active_sessions = self
2142 .session_manager
2143 .count_active_sessions()
2144 .await
2145 .unwrap_or(0);
2146 metrics.insert("active_sessions".to_string(), total_active_sessions);
2147 metrics.insert("total_tokens".to_string(), total_active_sessions);
2148 metrics.insert(
2149 "failed_attempts".to_string(),
2150 self.audit_manager
2151 .get_failed_login_count_24h()
2152 .await
2153 .unwrap_or(0),
2154 );
2155 metrics.insert(
2156 "successful_attempts".to_string(),
2157 self.audit_manager
2158 .get_successful_login_count_24h()
2159 .await
2160 .unwrap_or(0),
2161 );
2162 metrics.insert("expired_tokens".to_string(), 0u64);
2163 Ok(metrics)
2164 }
2165
2166 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2172 self.mfa_manager
2173 .sms
2174 .register_phone_number(user_id, phone_number)
2175 .await
2176 }
2177
2178 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2183 self.mfa_manager
2184 .backup_codes
2185 .generate_codes(user_id, count)
2186 .await
2187 }
2188 pub async fn grant_permission(
2200 &self,
2201 user_id: &str,
2202 action: &str,
2203 resource: &str,
2204 ) -> Result<()> {
2205 self.authorization_manager
2206 .grant_permission(user_id, action, resource)
2207 .await
2208 }
2209
2210 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2220 self.mfa_manager.email.initiate_challenge(user_id).await
2221 }
2222
2223 pub fn storage(&self) -> Arc<dyn AuthStorage> {
2228 self.storage.clone()
2229 }
2230
2231 pub fn config(&self) -> &AuthConfig {
2233 &self.config
2234 }
2235
2236 pub async fn reset_authorization_runtime(&self) {
2238 self.authorization_manager.reset_runtime_state().await;
2239 }
2240
2241 pub async fn register_user(
2264 &self,
2265 username: &str,
2266 email: &str,
2267 password: &str,
2268 ) -> Result<String> {
2269 self.require_initialized()?;
2270 self.user_manager
2271 .register_user(username, email, password)
2272 .await
2273 }
2274
2275 #[deprecated(
2302 since = "0.6.0",
2303 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2304 )]
2305 pub async fn list_users(
2306 &self,
2307 limit: Option<usize>,
2308 offset: Option<usize>,
2309 active_only: bool,
2310 ) -> Result<Vec<UserInfo>> {
2311 self.require_initialized()?;
2312 self.user_manager
2313 .list_users(limit, offset, active_only)
2314 .await
2315 }
2316
2317 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2336 self.require_initialized()?;
2337 self.user_manager
2338 .list_users(
2339 query.get_limit(),
2340 query.get_offset(),
2341 query.get_active_only(),
2342 )
2343 .await
2344 }
2345
2346 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2348 self.require_initialized()?;
2349 self.user_manager.get_user_info(user_id).await
2350 }
2351
2352 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2354 self.require_initialized()?;
2355 self.user_manager.update_user_roles(user_id, roles).await
2356 }
2357
2358 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2360 self.require_initialized()?;
2361 self.user_manager.set_user_active(user_id, active).await
2362 }
2363
2364 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2366 self.require_initialized()?;
2367 self.user_manager.update_user_email(user_id, email).await
2368 }
2369
2370 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2372 self.require_initialized()?;
2373 self.user_manager
2374 .verify_user_password(user_id, password)
2375 .await
2376 }
2377
2378 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2380 self.user_manager.get_username_by_id(user_id).await
2381 }
2382
2383 pub async fn username_exists(&self, username: &str) -> Result<bool> {
2385 self.user_manager.username_exists(username).await
2386 }
2387
2388 pub async fn email_exists(&self, email: &str) -> Result<bool> {
2390 self.user_manager.email_exists(email).await
2391 }
2392
2393 pub async fn get_user_by_username(
2395 &self,
2396 username: &str,
2397 ) -> Result<HashMap<String, serde_json::Value>> {
2398 self.user_manager.get_user_by_username(username).await
2399 }
2400
2401 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2403 self.require_initialized()?;
2404 self.user_manager
2405 .update_user_password(username, new_password)
2406 .await
2407 }
2408
2409 pub async fn update_user_password_by_id(
2411 &self,
2412 user_id: &str,
2413 new_password: &str,
2414 ) -> Result<()> {
2415 self.require_initialized()?;
2416 self.user_manager
2417 .update_user_password_by_id(user_id, new_password)
2418 .await
2419 }
2420
2421 pub async fn delete_user(&self, username: &str) -> Result<()> {
2423 self.require_initialized()?;
2424 self.user_manager.delete_user(username).await
2425 }
2426
2427 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2429 self.require_initialized()?;
2430 self.user_manager.delete_user_by_id(user_id).await
2431 }
2432
2433 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2435 self.mfa_manager
2436 .verify_challenge_code(challenge, code)
2437 .await
2438 }
2439
2440 async fn log_audit_event(
2442 &self,
2443 event_type: &str,
2444 user_id: &str,
2445 method: &str,
2446 metadata: &CredentialMetadata,
2447 ) {
2448 if !self.config.audit.enabled {
2449 return;
2450 }
2451 let should_log = match event_type {
2452 "auth_success" | "mfa_required" => self.config.audit.log_success,
2453 "auth_failure" => self.config.audit.log_failures,
2454 _ => true,
2455 };
2456 if should_log {
2457 self.audit_manager
2458 .log_auth_trace_event(
2459 event_type,
2460 user_id,
2461 method,
2462 metadata.client_ip.as_deref().unwrap_or("unknown"),
2463 metadata.user_agent.as_deref().unwrap_or("unknown"),
2464 )
2465 .await;
2466 }
2467 }
2468
2469 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2471 self.mfa_manager.guard_and_store(challenge).await
2472 }
2473
2474 async fn mint_and_store_token(
2476 &self,
2477 user_id: &str,
2478 scopes: impl Into<crate::types::Scopes>,
2479 method: &str,
2480 lifetime: Option<Duration>,
2481 ) -> Result<AuthToken> {
2482 let token = self
2483 .token_manager
2484 .create_auth_token(user_id, scopes, method, lifetime)?;
2485 self.storage.store_token(&token).await?;
2486 Ok(token)
2487 }
2488
2489 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2491 self.session_manager.coordinate_distributed_sessions().await
2492 }
2493
2494 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2496 self.session_manager.synchronize_session(session_id).await
2497 }
2498
2499 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2501 self.monitoring_manager.clone()
2502 }
2503
2504 #[cfg(feature = "api-server")]
2506 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2507 Some(self.security_manager.clone())
2508 }
2509
2510 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2512 self.monitoring_manager.get_performance_metrics()
2513 }
2514
2515 pub async fn health_check(
2517 &self,
2518 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2519 self.monitoring_manager.health_check().await
2520 }
2521
2522 pub async fn export_prometheus_metrics(&self) -> String {
2524 self.monitoring_manager.export_prometheus_metrics().await
2525 }
2526 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2528 self.require_initialized()?;
2529 self.authorization_manager.create_role(role).await
2530 }
2531
2532 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2534 self.authorization_manager.list_roles().await
2535 }
2536
2537 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2539 self.authorization_manager.get_role(role_name).await
2540 }
2541
2542 pub async fn add_role_permission(
2544 &self,
2545 role_name: &str,
2546 permission: crate::permissions::Permission,
2547 ) -> Result<()> {
2548 self.authorization_manager
2549 .add_role_permission(role_name, permission)
2550 .await
2551 }
2552
2553 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2555 self.require_initialized()?;
2556 self.authorization_manager
2557 .assign_role(user_id, role_name)
2558 .await
2559 }
2560
2561 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2563 self.require_initialized()?;
2564 self.authorization_manager
2565 .remove_role(user_id, role_name)
2566 .await
2567 }
2568
2569 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2571 self.require_initialized()?;
2572 self.authorization_manager
2573 .set_role_inheritance(child_role, parent_role)
2574 .await
2575 }
2576
2577 pub async fn revoke_permission(
2579 &self,
2580 user_id: &str,
2581 action: &str,
2582 resource: &str,
2583 ) -> Result<()> {
2584 self.require_initialized()?;
2585 self.authorization_manager
2586 .revoke_permission(user_id, action, resource)
2587 .await
2588 }
2589
2590 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2592 self.authorization_manager
2593 .user_has_role(user_id, role_name)
2594 .await
2595 }
2596
2597 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2599 self.authorization_manager.list_user_roles(user_id).await
2600 }
2601
2602 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2604 self.authorization_manager
2605 .get_effective_permissions(user_id)
2606 .await
2607 }
2608
2609 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2611 self.authorization_manager
2612 .create_abac_policy(name, description)
2613 .await
2614 }
2615
2616 pub async fn map_user_attribute(
2637 &self,
2638 user_id: &str,
2639 attribute: &str,
2640 value: &str,
2641 ) -> Result<()> {
2642 self.authorization_manager
2643 .map_user_attribute(user_id, attribute, value)
2644 .await
2645 }
2646
2647 pub async fn get_user_attribute(
2671 &self,
2672 user_id: &str,
2673 attribute: &str,
2674 ) -> Result<Option<String>> {
2675 self.authorization_manager
2676 .get_user_attribute(user_id, attribute)
2677 .await
2678 }
2679
2680 pub async fn check_dynamic_permission(
2711 &self,
2712 user_id: &str,
2713 action: &str,
2714 resource: &str,
2715 context: std::collections::HashMap<String, String>,
2716 ) -> Result<bool> {
2717 self.authorization_manager
2718 .check_dynamic_permission(user_id, action, resource, context)
2719 .await
2720 }
2721
2722 pub async fn check_dynamic_permission_with_context(
2742 &self,
2743 user_id: &str,
2744 action: &str,
2745 resource: &str,
2746 context: PermissionContext,
2747 ) -> Result<bool> {
2748 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2749 .await
2750 }
2751
2752 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2754 self.authorization_manager.create_resource(resource).await
2755 }
2756
2757 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2776 self.authorization_manager
2777 .delegate_permission(
2778 req.delegator_id(),
2779 req.delegatee_id(),
2780 req.action(),
2781 req.resource(),
2782 req.get_duration(),
2783 )
2784 .await
2785 }
2786
2787 pub async fn delegate_permission(
2792 &self,
2793 delegator_id: &str,
2794 delegatee_id: &str,
2795 action: &str,
2796 resource: &str,
2797 duration: std::time::Duration,
2798 ) -> Result<()> {
2799 self.authorization_manager
2800 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2801 .await
2802 }
2803
2804 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2806 self.authorization_manager
2807 .get_active_delegations(user_id)
2808 .await
2809 }
2810
2811 pub async fn get_permission_audit_logs(
2813 &self,
2814 user_id: Option<&str>,
2815 action: Option<&str>,
2816 resource: Option<&str>,
2817 limit: Option<usize>,
2818 ) -> Result<Vec<String>> {
2819 self.audit_manager
2820 .get_permission_audit_logs(user_id, action, resource, limit)
2821 .await
2822 }
2823
2824 pub async fn get_permission_audit_logs_with_query(
2844 &self,
2845 query: AuditLogQuery,
2846 ) -> Result<Vec<String>> {
2847 self.audit_manager
2848 .get_permission_audit_logs(
2849 query.get_user_id(),
2850 query.get_action(),
2851 query.get_resource(),
2852 query.get_limit(),
2853 )
2854 .await
2855 }
2856
2857 pub async fn get_permission_metrics(
2859 &self,
2860 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2861 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2862 let permission_checks_last_hour = self
2863 .audit_manager
2864 .get_permission_checks_last_hour()
2865 .await
2866 .unwrap_or(0);
2867 self.authorization_manager
2868 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2869 .await
2870 }
2871
2872 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2874 let active_sessions = self
2875 .session_manager
2876 .count_active_sessions()
2877 .await
2878 .unwrap_or(0);
2879 self.audit_manager
2880 .get_security_audit_stats(active_sessions)
2881 .await
2882 }
2883
2884 pub async fn get_user_profile(
2886 &self,
2887 user_id: &str,
2888 ) -> Result<crate::providers::ProviderProfile> {
2889 self.user_manager.get_user_profile(user_id).await
2890 }
2891}
2892
2893pub use crate::audit::SecurityAuditStats;
2894
2895pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2896
2897#[derive(Debug, Clone, Default)]
2899pub struct AuthStats {
2900 pub registered_methods: Vec<String>,
2902
2903 pub active_sessions: u64,
2905
2906 pub active_mfa_challenges: u64,
2908
2909 pub tokens_issued: u64,
2911
2912 pub auth_attempts: u64,
2914}
2915
2916#[cfg(test)]
2917mod tests {
2918 use super::*;
2919 use crate::config::{AuthConfig, SecurityConfig};
2920 #[tokio::test]
2921 async fn test_framework_initialization() {
2922 let config = AuthConfig::new().security(SecurityConfig {
2923 min_password_length: 8,
2924 require_password_complexity: false,
2925 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2926 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2927 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2928 secure_cookies: false,
2929 cookie_same_site: crate::config::CookieSameSite::Lax,
2930 csrf_protection: false,
2931 session_timeout: Duration::from_secs(3600),
2932 previous_secret_key: None,
2933 });
2934 let mut framework = AuthFramework::new(config);
2935
2936 assert!(framework.initialize().await.is_ok());
2937 assert!(framework.initialized);
2938 }
2939
2940 #[tokio::test]
2941 async fn test_method_registration() {
2942 let config = AuthConfig::new().security(SecurityConfig {
2947 min_password_length: 8,
2948 require_password_complexity: false,
2949 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2950 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2951 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2952 secure_cookies: false,
2953 cookie_same_site: crate::config::CookieSameSite::Lax,
2954 csrf_protection: false,
2955 session_timeout: Duration::from_secs(3600),
2956 previous_secret_key: None,
2957 });
2958 let framework = AuthFramework::new(config);
2959
2960 assert!(!framework.initialized);
2962
2963 }
2966
2967 #[tokio::test]
2968 async fn test_token_validation() {
2969 let config = AuthConfig::new().security(SecurityConfig {
2970 min_password_length: 8,
2971 require_password_complexity: false,
2972 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2973 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2974 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2975 secure_cookies: false,
2976 cookie_same_site: crate::config::CookieSameSite::Lax,
2977 csrf_protection: false,
2978 session_timeout: Duration::from_secs(3600),
2979 previous_secret_key: None,
2980 });
2981 let mut framework = AuthFramework::new(config);
2982 framework.initialize().await.unwrap();
2983
2984 let token = framework
2985 .token_manager
2986 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2987 .unwrap();
2988
2989 framework.storage.store_token(&token).await.unwrap();
2991
2992 assert!(framework.validate_token(&token).await.unwrap());
2993 }
2994
2995 #[tokio::test]
2996 async fn test_session_management() {
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 session_id = framework
3013 .create_session(
3014 "test-user",
3015 Duration::from_secs(3600),
3016 Some("192.168.1.1".to_string()),
3017 Some("Test Agent".to_string()),
3018 )
3019 .await
3020 .unwrap();
3021
3022 let session = framework.get_session(&session_id).await.unwrap();
3023 assert!(session.is_some());
3024
3025 framework.delete_session(&session_id).await.unwrap();
3026 let session = framework.get_session(&session_id).await.unwrap();
3027 assert!(session.is_none());
3028 }
3029
3030 #[tokio::test]
3031 async fn test_grouped_operations_accessors() {
3032 let config = AuthConfig::new().security(SecurityConfig {
3033 min_password_length: 8,
3034 require_password_complexity: false,
3035 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3036 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3037 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3038 secure_cookies: false,
3039 cookie_same_site: crate::config::CookieSameSite::Lax,
3040 csrf_protection: false,
3041 session_timeout: Duration::from_secs(3600),
3042 previous_secret_key: None,
3043 });
3044 let mut framework = AuthFramework::new(config);
3045 framework.initialize().await.unwrap();
3046
3047 let user_id = framework
3048 .users()
3049 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
3050 .await
3051 .unwrap();
3052 assert!(
3053 framework
3054 .users()
3055 .exists_by_username("grouped-user")
3056 .await
3057 .unwrap()
3058 );
3059
3060 let session_id = framework
3061 .sessions()
3062 .create(&user_id, Duration::from_secs(300), None, None)
3063 .await
3064 .unwrap();
3065 assert!(
3066 framework
3067 .sessions()
3068 .get(&session_id)
3069 .await
3070 .unwrap()
3071 .is_some()
3072 );
3073 assert_eq!(
3074 framework
3075 .sessions()
3076 .list_for_user(&user_id)
3077 .await
3078 .unwrap()
3079 .len(),
3080 1
3081 );
3082
3083 framework
3084 .authorization()
3085 .grant(&user_id, "read", "documents")
3086 .await
3087 .unwrap();
3088 let permissions = framework
3089 .authorization()
3090 .effective_permissions(&user_id)
3091 .await
3092 .unwrap();
3093 assert!(
3094 permissions
3095 .iter()
3096 .any(|permission| permission == "read:documents")
3097 );
3098
3099 framework.sessions().delete(&session_id).await.unwrap();
3100 assert!(
3101 framework
3102 .sessions()
3103 .get(&session_id)
3104 .await
3105 .unwrap()
3106 .is_none()
3107 );
3108 }
3109
3110 #[tokio::test]
3111 async fn test_cleanup_expired_data() {
3112 let config = AuthConfig::new().security(SecurityConfig {
3113 min_password_length: 8,
3114 require_password_complexity: false,
3115 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3116 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3117 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3118 secure_cookies: false,
3119 cookie_same_site: crate::config::CookieSameSite::Lax,
3120 csrf_protection: false,
3121 session_timeout: Duration::from_secs(3600),
3122 previous_secret_key: None,
3123 });
3124 let mut framework = AuthFramework::new(config);
3125 framework.initialize().await.unwrap();
3126
3127 assert!(framework.cleanup_expired_data().await.is_ok());
3129 }
3130
3131 #[cfg(feature = "redis-storage")]
3139 #[test]
3140 fn new_validated_redis_fails_closed_without_an_encryption_key() {
3141 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3142 unsafe {
3145 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3146 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3147 }
3148
3149 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3150 config.storage = crate::config::StorageConfig::Redis {
3151 url: "redis://127.0.0.1:1/".to_string(),
3152 key_prefix: "test:".to_string(),
3153 };
3154 let result = AuthFramework::new_validated(config);
3157 assert!(
3158 result.is_err(),
3159 "constructing with Redis storage and no encryption key configured must fail \
3160 closed, not silently build unwrapped (unencrypted) storage"
3161 );
3162 }
3163
3164 #[tokio::test]
3165 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3166 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3167 config.storage_encryption.require_wrapped_storage = true;
3168 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3169 assert!(
3170 framework.initialize().await.is_err(),
3171 "caller-supplied unwrapped storage must be refused when wrapping is required"
3172 );
3173 }
3174
3175 #[tokio::test]
3176 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3177 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3178 required.storage_encryption.require_wrapped_storage = true;
3179 let wrapped: Arc<dyn AuthStorage> =
3180 Arc::new(crate::storage::encryption::EncryptedStorage::new(
3181 MemoryStorage::new(),
3182 crate::storage::encryption::StorageEncryption::new_random(),
3183 false,
3184 false,
3185 ));
3186 let mut framework = AuthFramework::new_with_storage(required, wrapped);
3187 framework.initialize().await.unwrap();
3188
3189 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3191 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3192 framework.initialize().await.unwrap();
3193 }
3194
3195 #[tokio::test]
3196 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3197 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3198 config.storage_encryption.require_wrapped_storage = true;
3199 let mut framework = AuthFramework::new(config);
3200 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3202 framework.initialize().await.unwrap();
3203 }
3204}