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(crate) async fn record_audit_event(&self, event: crate::audit::AuditEvent) {
419 let kind = event.event_type.clone();
420 if let Err(e) = self.audit_manager.log_event(event).await {
421 tracing::warn!("Could not record the {kind} audit event: {e}");
422 }
423 }
424
425 pub(crate) async fn query_audit_events(
427 &self,
428 query: &crate::audit::AuditQuery,
429 ) -> Result<Vec<crate::audit::AuditEvent>> {
430 self.audit_manager.query_events(query).await
431 }
432
433 pub fn maintenance(&self) -> MaintenanceOperations<'_> {
435 MaintenanceOperations { framework: self }
436 }
437
438 pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
440 self.runtime_config.read().await.clone()
441 }
442
443 #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
444 #[doc(hidden)]
445 pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
446 self.runtime_config().await
447 }
448
449 pub async fn update_runtime_config(
454 &self,
455 update: crate::config::RuntimeConfig,
456 ) -> Result<crate::config::RuntimeConfig> {
457 if update.token_lifetime_secs == 0 {
459 return Err(AuthError::config("token_lifetime_secs must be > 0"));
460 }
461 if update.refresh_token_lifetime_secs == 0 {
462 return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
463 }
464 if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
465 return Err(AuthError::config(
466 "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
467 ));
468 }
469 if update.min_password_length == 0 {
470 return Err(AuthError::config("min_password_length must be > 0"));
471 }
472 let mut cfg = self.runtime_config.write().await;
473 *cfg = update.clone();
474 Ok(update)
475 }
476
477 pub fn admin(&self) -> AdminOperations<'_> {
479 AdminOperations { framework: self }
480 }
481
482 pub fn new(config: AuthConfig) -> Self {
490 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
492 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
493 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
494
495 let ephemeral_secret = {
501 let rng = ring::rand::SystemRandom::new();
502 let mut buf = [0u8; 32];
503 ring::rand::SecureRandom::fill(&rng, &mut buf)
504 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
505 buf
506 };
507 let token_manager =
508 TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
509
510 let user_manager = crate::auth_modular::user_manager::UserManager::new(
511 storage.clone(),
512 config.security.password_hash_algorithm.clone(),
513 );
514 let session_manager =
515 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
516 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
517 let authorization_manager =
518 crate::auth_modular::authorization_manager::AuthorizationManager::new(
519 Arc::new(RwLock::new(PermissionChecker::new())),
520 storage.clone(),
521 );
522
523 Self {
524 config,
525 methods: HashMap::new(),
526 token_manager,
527 storage,
528 authorization_manager,
529 rate_limiter: None, monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
531 crate::monitoring::MonitoringConfig::default(),
532 )),
533 audit_manager,
534 #[cfg(feature = "api-server")]
535 security_manager: Arc::new(crate::api::SecurityManager::new()),
536 runtime_config: Arc::new(tokio::sync::RwLock::new(
537 crate::config::RuntimeConfig::default(),
538 )),
539 user_manager,
540 session_manager,
541 mfa_manager,
542 initialized: false,
543 storage_overridden: false,
544 storage_from_caller: false,
545 }
546 }
547
548 pub fn new_validated(config: AuthConfig) -> Result<Self> {
553 config.validate().map_err(|e| {
555 AuthError::configuration(format!("Configuration validation failed: {}", e))
556 })?;
557
558 let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
560
561 let mut token_manager =
562 TokenManager::new_hmac(¤t_secret_bytes, "auth-framework", "auth-framework");
563
564 if let Some(prev_secret) = &config.security.previous_secret_key {
566 token_manager =
568 TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
569 token_manager.rotate_hmac_key(¤t_secret_bytes);
570 }
571
572 let storage: Arc<dyn AuthStorage> = match &config.storage {
581 #[cfg(feature = "redis-storage")]
582 crate::config::StorageConfig::Redis { url, key_prefix } => {
583 let redis: Arc<dyn AuthStorage> = Arc::new(
584 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
585 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
586 })?,
587 );
588 crate::storage::factory::wrap_with_encryption_if_enabled(
589 redis,
590 &config.storage_encryption,
591 )?
592 }
593 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
594 };
595
596 let rate_limiter = if config.rate_limiting.enabled {
598 Some(RateLimiter::new(
599 config.rate_limiting.max_requests,
600 config.rate_limiting.window,
601 ))
602 } else {
603 None
604 };
605
606 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
608 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
609
610 let user_manager = crate::auth_modular::user_manager::UserManager::new(
611 storage.clone(),
612 config.security.password_hash_algorithm.clone(),
613 );
614 let session_manager =
615 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
616 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
617 let authorization_manager =
618 crate::auth_modular::authorization_manager::AuthorizationManager::new(
619 Arc::new(RwLock::new(PermissionChecker::new())),
620 storage.clone(),
621 );
622
623 Ok(Self {
624 config: config.clone(),
625 methods: HashMap::new(),
626 token_manager,
627 storage,
628 authorization_manager,
629 rate_limiter,
630 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
631 crate::monitoring::MonitoringConfig::default(),
632 )),
633 audit_manager,
634 #[cfg(feature = "api-server")]
635 security_manager: Arc::new(crate::api::SecurityManager::new()),
636 runtime_config: Arc::new(tokio::sync::RwLock::new(
637 crate::config::RuntimeConfig::from_auth_config(&config),
638 )),
639 user_manager,
640 session_manager,
641 mfa_manager,
642 initialized: false,
643 storage_overridden: false,
644 storage_from_caller: false,
645 })
646 }
647
648 pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
655 self.storage = storage.clone();
656 self.user_manager = crate::auth_modular::user_manager::UserManager::new(
657 storage.clone(),
658 self.config.security.password_hash_algorithm.clone(),
659 );
660 self.session_manager =
661 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
662 self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
663 self.authorization_manager =
664 crate::auth_modular::authorization_manager::AuthorizationManager::new(
665 Arc::new(RwLock::new(PermissionChecker::new())),
666 storage,
667 );
668 self.storage_overridden = true;
669 self.storage_from_caller = true;
670 }
671
672 pub(crate) fn replace_storage_from_factory(
676 &mut self,
677 storage: std::sync::Arc<dyn AuthStorage>,
678 ) {
679 self.replace_storage(storage);
680 self.storage_from_caller = false;
681 }
682
683 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
690 self.session_manager.set_distributed_store(store);
691 }
692
693 pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
695 let mut framework = Self::new(config);
696 framework.replace_storage(storage);
697 framework
698 }
699
700 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
702 let name = name.into();
703 info!("Registering authentication method: {}", name);
704
705 if let Err(e) = method.validate_config() {
707 error!("Method '{}' configuration validation failed: {}", name, e);
708 return;
709 }
710
711 self.methods.insert(name, method);
712 }
713
714 fn require_initialized(&self) -> Result<()> {
720 if self.initialized {
721 Ok(())
722 } else {
723 Err(AuthError::configuration(
724 "Framework not initialized. Call `initialize().await` first, \
725 or use `AuthFramework::builder().build().await` which initializes automatically.",
726 ))
727 }
728 }
729
730 pub async fn initialize(&mut self) -> Result<()> {
740 if self.initialized {
741 return Ok(());
742 }
743
744 info!("Initializing authentication framework");
745
746 self.config.validate().map_err(|e| {
748 AuthError::configuration(format!("Configuration validation failed: {}", e))
749 })?;
750
751 let token_manager = match resolve_jwt_secret_bytes(&self.config) {
753 Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
754 Err(_) => {
755 if Self::is_production_environment() {
756 return Err(AuthError::configuration(
757 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
758 Generate a secure secret with: openssl rand -base64 32\n\
759 Set it with: export JWT_SECRET=\"your-secret-here\"",
760 ));
761 }
762 warn!("No JWT secret configured, using development-only default");
763 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
764 warn!("This configuration is NOT SECURE and should only be used in development!");
765 self.token_manager.clone()
766 }
767 };
768
769 self.token_manager = token_manager;
771
772 if self.storage_from_caller {
776 crate::storage::factory::check_overridden_storage(
777 &self.storage,
778 &self.config.storage_encryption,
779 )?;
780 }
781
782 if !self.storage_overridden {
784 let storage = crate::storage::factory::build_storage_backend_with_encryption(
785 &self.config.storage,
786 None,
787 &self.config.storage_encryption,
788 )
789 .await?;
790 self.replace_storage(storage);
791 self.storage_overridden = false;
792 self.storage_from_caller = false;
793 }
794
795 if self.config.rate_limiting.enabled {
797 self.rate_limiter = Some(RateLimiter::new(
798 self.config.rate_limiting.max_requests,
799 self.config.rate_limiting.window,
800 ));
801 }
802
803 self.authorization_manager.create_default_roles().await;
805
806 self.authorization_manager.load_persisted_roles().await?;
808
809 self.cleanup_expired_data().await?;
811
812 self.initialized = true;
813 info!("Authentication framework initialized successfully");
814
815 Ok(())
816 }
817
818 pub async fn authenticate(
846 &self,
847 method_name: &str,
848 credential: Credential,
849 ) -> Result<AuthResult> {
850 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
851 .await
852 }
853
854 pub async fn authenticate_with_metadata(
856 &self,
857 method_name: &str,
858 credential: Credential,
859 metadata: CredentialMetadata,
860 ) -> Result<AuthResult> {
861 use std::time::Instant;
862 use tokio::time::{Duration as TokioDuration, sleep};
863
864 let start_time = Instant::now();
865
866 self.monitoring_manager.record_auth_request().await;
868
869 self.require_initialized()?;
870
871 let result = self
873 .authenticate_internal(method_name, credential, metadata)
874 .await;
875
876 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
879 if elapsed < min_duration {
880 sleep(min_duration - elapsed).await;
881 }
882
883 if let Ok(ref auth_result) = result {
885 match auth_result {
886 AuthResult::Success(token) => {
887 self.monitoring_manager
888 .record_auth_success(&token.user_id, elapsed)
889 .await;
890 }
891 AuthResult::Failure(reason) => {
892 self.monitoring_manager
893 .record_auth_failure(None, reason)
894 .await;
895 }
896 _ => {} }
898 }
899
900 result
901 }
902
903 async fn authenticate_internal(
905 &self,
906 method_name: &str,
907 credential: Credential,
908 metadata: CredentialMetadata,
909 ) -> Result<AuthResult> {
910 if let Some(ref rate_limiter) = self.rate_limiter {
912 let rate_key = format!(
913 "auth:{}:{}",
914 method_name,
915 metadata.client_ip.as_deref().unwrap_or("unknown")
916 );
917
918 if !rate_limiter.is_allowed(&rate_key) {
919 warn!(
920 "Rate limit exceeded for method '{}' from IP {:?}",
921 method_name, metadata.client_ip
922 );
923 return Err(AuthError::rate_limit("Too many authentication attempts"));
924 }
925 }
926
927 if method_name == "password"
931 && let Credential::Password {
932 ref username,
933 ref password,
934 } = credential
935 {
936 return self
937 .authenticate_password_builtin(username, password, &metadata)
938 .await;
939 }
940
941 if method_name == "jwt" {
942 return match credential {
943 Credential::Jwt { token } | Credential::Bearer { token } => {
944 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
945 .await
946 }
947 _ => Ok(AuthResult::Failure(
948 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
949 )),
950 };
951 }
952
953 if matches!(method_name, "api_key" | "api-key") {
954 return match credential {
955 Credential::ApiKey { key } => {
956 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
957 .await
958 }
959 _ => Ok(AuthResult::Failure(
960 "API key authentication expects Credential::api_key".to_string(),
961 )),
962 };
963 }
964
965 if method_name == "oauth2" {
966 return self
967 .authenticate_oauth2_builtin(credential, &metadata)
968 .await;
969 }
970
971 let method = self.methods.get(method_name).ok_or_else(|| {
973 AuthError::auth_method(method_name, "Authentication method not found".to_string())
974 })?;
975
976 debug!(
978 "Authentication attempt with method '{}' for credential: {}",
979 method_name,
980 credential.safe_display()
981 );
982
983 let result = method.authenticate(credential, metadata.clone()).await?;
985
986 match &result {
988 MethodResult::Success(token) => {
989 info!(
990 "Authentication successful for user '{}' with method '{}'",
991 token.user_id, method_name
992 );
993
994 self.storage.store_token(token).await?;
996
997 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
999 .await;
1000
1001 Ok(AuthResult::Success(token.clone()))
1002 }
1003
1004 MethodResult::MfaRequired(challenge) => {
1005 info!(
1006 "MFA required for user '{}' with method '{}'",
1007 challenge.user_id, method_name
1008 );
1009
1010 self.guard_and_store_mfa_challenge((**challenge).clone())
1012 .await?;
1013
1014 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
1016 .await;
1017
1018 Ok(AuthResult::MfaRequired(challenge.clone()))
1019 }
1020
1021 MethodResult::Failure { reason } => {
1022 warn!(
1023 "Authentication failed for method '{}': {}",
1024 method_name, reason
1025 );
1026
1027 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
1029 .await;
1030
1031 Ok(AuthResult::Failure(reason.clone()))
1032 }
1033 }
1034 }
1035
1036 async fn authenticate_jwt_builtin(
1037 &self,
1038 token: &str,
1039 metadata: &CredentialMetadata,
1040 auth_method: &str,
1041 ) -> Result<AuthResult> {
1042 if token.is_empty() {
1043 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
1044 }
1045
1046 match validate_access_jwt_with(
1047 &self.token_manager,
1048 self.storage.as_ref(),
1049 token,
1050 false,
1051 false,
1052 )
1053 .await
1054 {
1055 Ok(claims) => {
1056 let token =
1057 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
1058 Ok(AuthResult::Success(Box::new(token)))
1059 }
1060 Err(error) => {
1061 if let Some(reason) = Self::credential_failure_reason(&error) {
1062 Ok(AuthResult::Failure(reason))
1063 } else {
1064 Err(error)
1065 }
1066 }
1067 }
1068 }
1069
1070 async fn authenticate_api_key_builtin(
1071 &self,
1072 api_key: &str,
1073 metadata: &CredentialMetadata,
1074 auth_method: &str,
1075 ) -> Result<AuthResult> {
1076 if api_key.is_empty() {
1077 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
1078 }
1079
1080 match self.validate_api_key(api_key).await {
1081 Ok(user) => {
1082 let scopes: Vec<String> = if user.roles.is_empty() {
1083 vec!["api_user".to_string()]
1084 } else {
1085 user.roles.to_vec()
1086 };
1087 let mut token = self
1088 .token_manager
1089 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
1090 .with_roles(user.roles)
1091 .with_scopes(scopes);
1092 token.metadata.issued_ip = metadata.client_ip.clone();
1093 token.metadata.user_agent = metadata.user_agent.clone();
1094 Ok(AuthResult::Success(Box::new(token)))
1095 }
1096 Err(error) => {
1097 if let Some(reason) = Self::credential_failure_reason(&error) {
1098 Ok(AuthResult::Failure(reason))
1099 } else {
1100 Err(error)
1101 }
1102 }
1103 }
1104 }
1105
1106 async fn authenticate_oauth2_builtin(
1107 &self,
1108 credential: Credential,
1109 metadata: &CredentialMetadata,
1110 ) -> Result<AuthResult> {
1111 match credential {
1112 Credential::OAuth {
1113 authorization_code, ..
1114 } => {
1115 if authorization_code.is_empty() {
1116 return Ok(AuthResult::Failure(
1117 "OAuth authorization code cannot be empty".to_string(),
1118 ));
1119 }
1120 Ok(AuthResult::Failure(
1121 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
1122 .to_string(),
1123 ))
1124 }
1125 Credential::OAuthRefresh { refresh_token } => {
1126 if refresh_token.is_empty() {
1127 return Ok(AuthResult::Failure(
1128 "OAuth refresh token cannot be empty".to_string(),
1129 ));
1130 }
1131 Ok(AuthResult::Failure(
1132 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
1133 .to_string(),
1134 ))
1135 }
1136 Credential::Jwt { token }
1137 | Credential::Bearer { token }
1138 | Credential::OpenIdConnect { id_token: token, .. } => {
1139 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
1140 }
1141 _ => Ok(AuthResult::Failure(
1142 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
1143 .to_string(),
1144 )),
1145 }
1146 }
1147
1148 fn build_validated_jwt_auth_token(
1149 raw_token: &str,
1150 claims: crate::tokens::JwtClaims,
1151 metadata: &CredentialMetadata,
1152 auth_method: &str,
1153 ) -> AuthToken {
1154 let crate::tokens::JwtClaims {
1155 sub,
1156 iss,
1157 exp,
1158 iat,
1159 jti,
1160 scope,
1161 permissions,
1162 roles,
1163 client_id,
1164 ..
1165 } = claims;
1166
1167 let now = chrono::Utc::now();
1168 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
1169 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
1170 .unwrap_or(now + chrono::Duration::hours(1));
1171 let lifetime = (expires_at - now)
1172 .to_std()
1173 .unwrap_or_else(|_| Duration::from_secs(1));
1174 let scopes = if scope.trim().is_empty() {
1175 Vec::new()
1176 } else {
1177 scope.split_whitespace().map(str::to_string).collect()
1178 };
1179
1180 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
1181 .with_scopes(scopes)
1182 .with_permissions(permissions.unwrap_or_default())
1183 .with_roles(roles.unwrap_or_default());
1184 token.token_id = jti;
1185 token.subject = Some(sub);
1186 token.issuer = Some(iss);
1187 token.issued_at = issued_at;
1188 token.expires_at = expires_at;
1189 token.metadata.issued_ip = metadata.client_ip.clone();
1190 token.metadata.user_agent = metadata.user_agent.clone();
1191 if let Some(client_id) = client_id {
1192 token.client_id = Some(client_id);
1193 }
1194 token
1195 }
1196
1197 fn credential_failure_reason(error: &AuthError) -> Option<String> {
1198 match error {
1199 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
1200 AuthError::Validation { message } => Some(message.clone()),
1201 AuthError::UserNotFound => Some("User not found".to_string()),
1202 _ => None,
1203 }
1204 }
1205
1206 async fn authenticate_password_builtin(
1208 &self,
1209 username: &str,
1210 password: &str,
1211 metadata: &CredentialMetadata,
1212 ) -> Result<AuthResult> {
1213 use crate::auth_modular::user_manager::CredentialCheckResult;
1214
1215 if username.is_empty() || password.is_empty() {
1216 return Ok(AuthResult::Failure(
1217 "Username or password cannot be empty".to_string(),
1218 ));
1219 }
1220
1221 match self
1222 .user_manager
1223 .verify_login_credentials(username, password)
1224 .await?
1225 {
1226 None => {
1227 self.log_audit_event("auth_failure", "unknown", "password", metadata)
1228 .await;
1229 Ok(AuthResult::Failure(
1230 "Invalid username or password".to_string(),
1231 ))
1232 }
1233 Some(CredentialCheckResult {
1234 ref user_id,
1235 mfa_enabled: true,
1236 }) => {
1237 let now = chrono::Utc::now();
1238 let challenge = MfaChallenge {
1239 id: crate::utils::string::generate_id(Some("mfa")),
1240 mfa_type: crate::methods::MfaType::MultiMethod,
1241 user_id: user_id.clone(),
1242 created_at: now,
1243 expires_at: now + chrono::Duration::minutes(5),
1244 attempts: 0,
1245 max_attempts: 5,
1246 code_hash: None,
1247 message: Some(
1248 "Provide your current TOTP code or a backup code to complete login"
1249 .to_string(),
1250 ),
1251 data: HashMap::new(),
1252 };
1253 self.guard_and_store_mfa_challenge(challenge.clone())
1254 .await?;
1255 self.log_audit_event("mfa_required", user_id, "password", metadata)
1256 .await;
1257 info!(
1258 "Built-in password authentication requires MFA for user: {}",
1259 username
1260 );
1261 Ok(AuthResult::MfaRequired(Box::new(challenge)))
1262 }
1263 Some(CredentialCheckResult {
1264 ref user_id,
1265 mfa_enabled: false,
1266 }) => {
1267 let token = self
1268 .mint_and_store_token(
1269 user_id,
1270 vec!["read".to_string(), "write".to_string()],
1271 "password",
1272 None,
1273 )
1274 .await?;
1275 self.monitoring_manager.record_auth_request().await;
1276 self.log_audit_event("auth_success", user_id, "password", metadata)
1277 .await;
1278 info!(
1279 "Built-in password authentication successful for user: {}",
1280 username
1281 );
1282 Ok(AuthResult::Success(Box::new(token)))
1283 }
1284 }
1285 }
1286
1287 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1289 debug!("Completing MFA for challenge '{}'", challenge.id);
1290
1291 let stored_challenge = self
1294 .mfa_manager
1295 .begin_attempt(&challenge.id)
1296 .await?
1297 .ok_or(MfaError::ChallengeExpired)?;
1298
1299 if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1300 if stored_challenge.attempts >= stored_challenge.max_attempts {
1301 self.mfa_manager.remove_challenge(&challenge.id).await?;
1302 }
1303 return Err(MfaError::InvalidCode.into());
1304 }
1305
1306 self.mfa_manager.remove_challenge(&challenge.id).await?;
1307
1308 let user_id = stored_challenge.user_id.as_str();
1309 let scopes = self
1310 .user_manager
1311 .get_user_roles(user_id)
1312 .await
1313 .unwrap_or_else(|_| vec!["user".to_string()]);
1314
1315 let token = self
1316 .mint_and_store_token(user_id, scopes, "mfa", None)
1317 .await?;
1318
1319 info!("MFA completed successfully for user '{}'", user_id);
1320 Ok(token)
1321 }
1322
1323 pub async fn mfa_challenge_owner(&self, challenge_id: &str) -> Option<String> {
1325 self.mfa_manager
1326 .get_challenge(challenge_id)
1327 .await
1328 .ok()
1329 .flatten()
1330 .map(|c| c.user_id)
1331 }
1332
1333 pub(crate) async fn discard_mfa_challenge(&self, challenge_id: &str) {
1335 let _ = self.mfa_manager.remove_challenge(challenge_id).await;
1336 }
1337
1338 pub async fn complete_mfa_by_id(
1340 &self,
1341 challenge_id: &str,
1342 mfa_code: &str,
1343 ) -> Result<AuthToken> {
1344 let challenge = self
1345 .mfa_manager
1346 .get_challenge(challenge_id)
1347 .await?
1348 .ok_or(MfaError::ChallengeExpired)?;
1349
1350 self.complete_mfa(challenge, mfa_code).await
1351 }
1352
1353 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1355 self.require_initialized()?;
1356 let valid = token.is_valid()
1357 && self.token_manager.validate_auth_token(token).is_ok()
1358 && token_value_matches_jwt(&self.token_manager, token)
1359 && !access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token).await?
1360 && self.touch_stored_token(token).await?;
1361 self.monitoring_manager.record_token_validation(valid).await;
1362 Ok(valid)
1363 }
1364
1365 async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1366 let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1367 return Ok(false);
1368 };
1369 if stored.is_revoked() {
1370 return Ok(false);
1371 }
1372 if stored.access_token != token.access_token || stored.user_id != token.user_id {
1374 return Ok(false);
1375 }
1376 stored.mark_used();
1377 self.storage.update_token(&stored).await?;
1378 Ok(true)
1379 }
1380
1381 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1383 if !self.validate_token(token).await? {
1384 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1385 }
1386
1387 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1388
1389 match self.user_manager.get_user_info(&token_info.user_id).await {
1392 Ok(mut info) => {
1393 if !token_info.attributes.is_empty() {
1395 let string_attrs: HashMap<String, String> = token_info
1396 .attributes
1397 .into_iter()
1398 .map(|(k, v)| {
1399 (
1400 k,
1401 v.as_str()
1402 .map(|s| s.to_string())
1403 .unwrap_or_else(|| v.to_string()),
1404 )
1405 })
1406 .collect();
1407 info.attributes = string_attrs.into();
1408 }
1409 Ok(info)
1410 }
1411 Err(_) => {
1412 let string_attrs: HashMap<String, String> = token_info
1413 .attributes
1414 .into_iter()
1415 .map(|(k, v)| {
1416 (
1417 k,
1418 v.as_str()
1419 .map(|s| s.to_string())
1420 .unwrap_or_else(|| v.to_string()),
1421 )
1422 })
1423 .collect();
1424 Ok(UserInfo {
1425 id: token_info.user_id,
1426 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1427 email: token_info.email,
1428 name: token_info.name,
1429 roles: token_info.roles.into(),
1430 active: false,
1431 email_verified: false,
1432 attributes: string_attrs.into(),
1433 })
1434 }
1435 }
1436 }
1437
1438 pub async fn check_permission(
1465 &self,
1466 token: &AuthToken,
1467 action: &str,
1468 resource: &str,
1469 ) -> Result<bool> {
1470 let Some(proof) = self.validated_token(token).await? else {
1471 return Ok(false);
1472 };
1473 self.check_validated_permission(&proof, action, resource)
1474 .await
1475 }
1476
1477 pub async fn validated_token(
1479 &self,
1480 token: &AuthToken,
1481 ) -> Result<Option<crate::tokens::ValidatedToken>> {
1482 Ok(self
1483 .validate_token(token)
1484 .await?
1485 .then(|| crate::tokens::ValidatedToken::new(token.clone())))
1486 }
1487
1488 pub async fn check_validated_permission(
1490 &self,
1491 proof: &crate::tokens::ValidatedToken,
1492 action: &str,
1493 resource: &str,
1494 ) -> Result<bool> {
1495 self.authorization_manager
1496 .check_validated_permission(proof, action, resource)
1497 .await
1498 }
1499
1500 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1502 self.require_initialized()?;
1503 debug!("Refreshing token for user '{}'", token.user_id);
1504
1505 if let Some(method) = self.methods.get(&token.auth_method)
1507 && method.supports_refresh()
1508 && let Some(ref refresh_token) = token.refresh_token
1509 {
1510 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1511 self.storage.store_token(&new_token).await?;
1512 return Ok(new_token);
1513 }
1514
1515 if !self.validate_token(token).await? {
1519 return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1520 message: "Cannot refresh a token that is not valid".to_string(),
1521 }));
1522 }
1523 let stored = self
1525 .storage
1526 .get_token(&token.token_id)
1527 .await?
1528 .ok_or_else(|| {
1529 AuthError::Token(crate::errors::TokenError::Invalid {
1530 message: "Cannot refresh a token that is not stored".to_string(),
1531 })
1532 })?;
1533 let new_token = self.token_manager.refresh_token(&stored)?;
1534 self.storage.store_token(&new_token).await?;
1535
1536 info!("Token refreshed for user '{}'", token.user_id);
1537
1538 Ok(new_token)
1539 }
1540
1541 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1543 self.require_initialized()?;
1544 debug!("Revoking token for user '{}'", token.user_id);
1545
1546 let mut revoked_token = token.clone();
1548 revoked_token.revoke(Some("Manual revocation".to_string()));
1549
1550 self.storage.update_token(&revoked_token).await?;
1552
1553 let jti = self
1556 .token_manager
1557 .validate_jwt_token(&token.access_token)
1558 .map(|claims| claims.jti)
1559 .unwrap_or_else(|_| token.token_id.clone());
1560 let remaining = (token.expires_at - chrono::Utc::now())
1561 .to_std()
1562 .unwrap_or_default()
1563 .max(Duration::from_secs(60));
1564 self.storage
1565 .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1566 .await?;
1567
1568 info!("Token revoked for user '{}'", token.user_id);
1569
1570 Ok(())
1571 }
1572
1573 pub async fn create_api_key(
1575 &self,
1576 user_id: &str,
1577 expires_in: Option<Duration>,
1578 ) -> Result<String> {
1579 self.require_initialized()?;
1580 self.user_manager.create_api_key(user_id, expires_in).await
1581 }
1582
1583 pub async fn create_api_key_with_role(
1590 &self,
1591 user_id: &str,
1592 role: &str,
1593 expires_in: Option<Duration>,
1594 ) -> Result<String> {
1595 self.require_initialized()?;
1596 self.user_manager
1597 .create_api_key_with_role(user_id, role, expires_in)
1598 .await
1599 }
1600
1601 pub async fn rotate_api_key(&self, old_key: &str) -> Result<String> {
1607 self.require_initialized()?;
1608 self.user_manager.rotate_api_key(old_key).await
1609 }
1610
1611 pub async fn rotate_api_key_with_expiry(
1613 &self,
1614 old_key: &str,
1615 expires_in: Option<Duration>,
1616 ) -> Result<String> {
1617 self.require_initialized()?;
1618 self.user_manager
1619 .rotate_api_key_with_expiry(old_key, expires_in)
1620 .await
1621 }
1622
1623 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1625 self.require_initialized()?;
1626 self.user_manager.validate_api_key(api_key).await
1627 }
1628
1629 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1631 self.require_initialized()?;
1632 self.user_manager.revoke_api_key(api_key).await
1633 }
1634
1635 pub async fn create_session(
1637 &self,
1638 user_id: &str,
1639 expires_in: Duration,
1640 ip_address: Option<String>,
1641 user_agent: Option<String>,
1642 ) -> Result<String> {
1643 self.require_initialized()?;
1644 let (session_id, new_total) = self
1645 .session_manager
1646 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1647 .await?;
1648 self.monitoring_manager
1649 .update_session_count(new_total)
1650 .await;
1651 Ok(session_id)
1652 }
1653
1654 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1674 self.create_session(
1675 req.get_user_id(),
1676 req.get_expires_in(),
1677 req.get_ip_address().map(|s| s.to_string()),
1678 req.get_user_agent().map(|s| s.to_string()),
1679 )
1680 .await
1681 }
1682
1683 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1685 self.require_initialized()?;
1686 self.session_manager.get_session(session_id).await
1687 }
1688
1689 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1691 self.require_initialized()?;
1692 self.session_manager.delete_session(session_id).await?;
1693
1694 let remaining = self
1695 .session_manager
1696 .count_active_sessions()
1697 .await
1698 .unwrap_or(0);
1699 self.monitoring_manager
1700 .update_session_count(remaining)
1701 .await;
1702
1703 Ok(())
1704 }
1705
1706 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1708 self.require_initialized()?;
1709 self.storage.list_user_tokens(user_id).await
1710 }
1711
1712 pub async fn cleanup_expired_data(&self) -> Result<()> {
1714 debug!("Cleaning up expired data");
1715
1716 self.storage.cleanup_expired().await?;
1718
1719 self.mfa_manager.cleanup_expired_challenges().await?;
1721
1722 self.session_manager.cleanup_expired_sessions().await?;
1724
1725 if let Some(ref rate_limiter) = self.rate_limiter {
1727 let _ = rate_limiter.cleanup().ok();
1728 }
1729
1730 Ok(())
1731 }
1732
1733 fn is_production_environment() -> bool {
1736 if let Ok(env) = std::env::var("ENVIRONMENT")
1737 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1738 {
1739 return true;
1740 }
1741 if let Ok(env) = std::env::var("ENV")
1742 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1743 {
1744 return true;
1745 }
1746 if let Ok(env) = std::env::var("NODE_ENV")
1747 && env.to_lowercase() == "production"
1748 {
1749 return true;
1750 }
1751 if let Ok(env) = std::env::var("RUST_ENV")
1752 && env.to_lowercase() == "production"
1753 {
1754 return true;
1755 }
1756 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1757 || std::env::var("DOCKER_CONTAINER").is_ok()
1758 }
1759
1760 pub async fn get_stats(&self) -> Result<AuthStats> {
1762 let mut stats = AuthStats::default();
1763
1764 if let Err(e) = self.storage.cleanup_expired().await {
1765 warn!("Failed to cleanup expired data: {}", e);
1766 }
1767 if let Some(rate_limiter) = &self.rate_limiter {
1768 let _ = rate_limiter.cleanup().ok();
1769 }
1770
1771 let active_sessions = self
1772 .session_manager
1773 .count_active_sessions()
1774 .await
1775 .unwrap_or(0) as u32;
1776
1777 stats.registered_methods = self.methods.keys().cloned().collect();
1778 stats.active_sessions = active_sessions as u64;
1779 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1780 let perf = self.monitoring_manager.get_performance_metrics();
1782 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1783 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1784 + perf.get("auth_failures").copied().unwrap_or(0);
1785
1786 Ok(stats)
1787 }
1788
1789 pub fn token_manager(&self) -> &TokenManager {
1794 &self.token_manager
1795 }
1796
1797 pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1804 let claims = self.token_manager.validate_jwt_token(token)?;
1805 if !claims.is_refresh_token() {
1806 return Err(rejected("Expected a refresh token"));
1807 }
1808 let read = |key: String| async move {
1809 self.storage.get_kv(&key).await.map_err(|e| {
1810 tracing::error!("Could not read refresh-token state: {}", e);
1811 rejected("Unable to verify token status")
1812 })
1813 };
1814 let family = claims.refresh_family().to_string();
1815 if read(format!("revoked_token:{}", claims.jti))
1816 .await?
1817 .is_some()
1818 || read(format!("revoked_family:{family}")).await?.is_some()
1819 {
1820 return Err(rejected("Refresh token has been revoked"));
1821 }
1822 ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1823
1824 let remaining =
1825 Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1826 let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1828 let consumed_key = format!("refresh_consumed:{}", claims.jti);
1829 let first_use = self
1835 .storage
1836 .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1837 .await
1838 .map_err(|e| {
1839 tracing::error!("Could not record refresh token use: {}", e);
1840 rejected("Unable to record refresh token use")
1841 })?;
1842 if !first_use {
1843 warn!(
1844 "Refresh token reuse detected for user '{}'; revoking its chain",
1845 claims.sub
1846 );
1847 if let Err(e) = self
1848 .storage
1849 .store_kv(
1850 &format!("revoked_family:{family}"),
1851 b"reuse",
1852 Some(family_ttl),
1853 )
1854 .await
1855 {
1856 tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1857 }
1858 return Err(rejected("Refresh token has already been used"));
1859 }
1860
1861 let lifetime = self.config.refresh_token_lifetime;
1862 let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1863 &claims.sub,
1864 Some(lifetime),
1865 &family,
1866 )?;
1867 Ok(RefreshRedemption {
1868 claims,
1869 new_refresh_token,
1870 })
1871 }
1872
1873 pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1880 validate_access_jwt_with(
1881 &self.token_manager,
1882 self.storage.as_ref(),
1883 token,
1884 true,
1885 false,
1886 )
1887 .await
1888 }
1889
1890 pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1896 validate_access_jwt_with(
1897 &self.token_manager,
1898 self.storage.as_ref(),
1899 token,
1900 true,
1901 true,
1902 )
1903 .await
1904 }
1905
1906 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1916 self.user_manager.validate_username(username).await
1917 }
1918
1919 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1926 self.user_manager.validate_display_name(display_name).await
1927 }
1928
1929 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1938 self.user_manager.validate_password_strength(password).await
1939 }
1940
1941 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1946 Ok(crate::utils::validation::validate_user_input(input))
1947 }
1948
1949 pub async fn create_auth_token(
1969 &self,
1970 user_id: impl Into<String>,
1971 scopes: impl Into<crate::types::Scopes>,
1972 method_name: impl Into<String>,
1973 lifetime: Option<Duration>,
1974 ) -> Result<AuthToken> {
1975 let method_name = method_name.into();
1976 let user_id = user_id.into();
1977 let scopes: crate::types::Scopes = scopes.into();
1978
1979 let auth_method = self
1981 .methods
1982 .get(&method_name)
1983 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1984 auth_method.validate_config()?;
1985
1986 const MAX_TOKENS_PER_USER: usize = 100;
1988 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1989 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1990 warn!(
1991 "User '{}' has reached maximum tokens ({})",
1992 user_id, MAX_TOKENS_PER_USER
1993 );
1994 return Err(AuthError::rate_limit(
1995 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1996 ));
1997 }
1998
1999 let token = self
2000 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
2001 .await?;
2002 self.monitoring_manager
2003 .record_token_creation(&method_name)
2004 .await;
2005 Ok(token)
2006 }
2007
2008 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
2018 self.mfa_manager.sms.initiate_challenge(user_id).await
2019 }
2020
2021 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
2029 self.mfa_manager.sms.verify_code(challenge_id, code).await
2030 }
2031
2032 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
2039 self.mfa_manager.email.register_email(user_id, email).await
2040 }
2041
2042 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
2053 self.mfa_manager.totp.generate_secret(user_id).await
2054 }
2055
2056 pub async fn generate_totp_qr_code(
2064 &self,
2065 user_id: &str,
2066 app_name: &str,
2067 secret: &str,
2068 ) -> Result<String> {
2069 self.mfa_manager
2070 .totp
2071 .generate_qr_code(user_id, app_name, secret)
2072 .await
2073 }
2074
2075 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
2080 self.mfa_manager.totp.generate_code(secret).await
2081 }
2082
2083 pub async fn generate_totp_code_for_window(
2087 &self,
2088 secret: &str,
2089 time_window: Option<u64>,
2090 ) -> Result<String> {
2091 self.mfa_manager
2092 .totp
2093 .generate_code_for_window(secret, time_window)
2094 .await
2095 }
2096
2097 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2105 self.mfa_manager.totp.verify_code(user_id, code).await
2106 }
2107
2108 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2113 debug!("Checking IP rate limit for '{}'", ip);
2114 let Some(ref rate_limiter) = self.rate_limiter else {
2115 return Ok(true);
2116 };
2117 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2118 warn!("Rate limit exceeded for IP: {}", ip);
2119 return Err(AuthError::rate_limit(format!(
2120 "Too many requests from IP {}. Please try again later.",
2121 ip
2122 )));
2123 }
2124 Ok(true)
2125 }
2126
2127 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2132 debug!("Getting security metrics");
2133 let mut metrics = std::collections::HashMap::new();
2134 let total_active_sessions = self
2135 .session_manager
2136 .count_active_sessions()
2137 .await
2138 .unwrap_or(0);
2139 metrics.insert("active_sessions".to_string(), total_active_sessions);
2140 metrics.insert("total_tokens".to_string(), total_active_sessions);
2141 metrics.insert(
2142 "failed_attempts".to_string(),
2143 self.audit_manager
2144 .get_failed_login_count_24h()
2145 .await
2146 .unwrap_or(0),
2147 );
2148 metrics.insert(
2149 "successful_attempts".to_string(),
2150 self.audit_manager
2151 .get_successful_login_count_24h()
2152 .await
2153 .unwrap_or(0),
2154 );
2155 metrics.insert("expired_tokens".to_string(), 0u64);
2156 Ok(metrics)
2157 }
2158
2159 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2165 self.mfa_manager
2166 .sms
2167 .register_phone_number(user_id, phone_number)
2168 .await
2169 }
2170
2171 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2176 self.mfa_manager
2177 .backup_codes
2178 .generate_codes(user_id, count)
2179 .await
2180 }
2181 pub async fn grant_permission(
2193 &self,
2194 user_id: &str,
2195 action: &str,
2196 resource: &str,
2197 ) -> Result<()> {
2198 self.authorization_manager
2199 .grant_permission(user_id, action, resource)
2200 .await
2201 }
2202
2203 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2213 self.mfa_manager.email.initiate_challenge(user_id).await
2214 }
2215
2216 pub fn storage(&self) -> Arc<dyn AuthStorage> {
2221 self.storage.clone()
2222 }
2223
2224 pub fn config(&self) -> &AuthConfig {
2226 &self.config
2227 }
2228
2229 pub async fn reset_authorization_runtime(&self) {
2231 self.authorization_manager.reset_runtime_state().await;
2232 }
2233
2234 pub async fn register_user(
2257 &self,
2258 username: &str,
2259 email: &str,
2260 password: &str,
2261 ) -> Result<String> {
2262 self.require_initialized()?;
2263 self.user_manager
2264 .register_user(username, email, password)
2265 .await
2266 }
2267
2268 #[deprecated(
2295 since = "0.6.0",
2296 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2297 )]
2298 pub async fn list_users(
2299 &self,
2300 limit: Option<usize>,
2301 offset: Option<usize>,
2302 active_only: bool,
2303 ) -> Result<Vec<UserInfo>> {
2304 self.require_initialized()?;
2305 self.user_manager
2306 .list_users(limit, offset, active_only)
2307 .await
2308 }
2309
2310 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2329 self.require_initialized()?;
2330 self.user_manager
2331 .list_users(
2332 query.get_limit(),
2333 query.get_offset(),
2334 query.get_active_only(),
2335 )
2336 .await
2337 }
2338
2339 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2341 self.require_initialized()?;
2342 self.user_manager.get_user_info(user_id).await
2343 }
2344
2345 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2347 self.require_initialized()?;
2348 self.user_manager.update_user_roles(user_id, roles).await
2349 }
2350
2351 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2353 self.require_initialized()?;
2354 self.user_manager.set_user_active(user_id, active).await
2355 }
2356
2357 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2359 self.require_initialized()?;
2360 self.user_manager.update_user_email(user_id, email).await
2361 }
2362
2363 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2365 self.require_initialized()?;
2366 self.user_manager
2367 .verify_user_password(user_id, password)
2368 .await
2369 }
2370
2371 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2373 self.user_manager.get_username_by_id(user_id).await
2374 }
2375
2376 pub async fn username_exists(&self, username: &str) -> Result<bool> {
2378 self.user_manager.username_exists(username).await
2379 }
2380
2381 pub async fn email_exists(&self, email: &str) -> Result<bool> {
2383 self.user_manager.email_exists(email).await
2384 }
2385
2386 pub async fn get_user_by_username(
2388 &self,
2389 username: &str,
2390 ) -> Result<HashMap<String, serde_json::Value>> {
2391 self.user_manager.get_user_by_username(username).await
2392 }
2393
2394 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2396 self.require_initialized()?;
2397 self.user_manager
2398 .update_user_password(username, new_password)
2399 .await
2400 }
2401
2402 pub async fn update_user_password_by_id(
2404 &self,
2405 user_id: &str,
2406 new_password: &str,
2407 ) -> Result<()> {
2408 self.require_initialized()?;
2409 self.user_manager
2410 .update_user_password_by_id(user_id, new_password)
2411 .await
2412 }
2413
2414 pub async fn delete_user(&self, username: &str) -> Result<()> {
2416 self.require_initialized()?;
2417 self.user_manager.delete_user(username).await
2418 }
2419
2420 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2422 self.require_initialized()?;
2423 self.user_manager.delete_user_by_id(user_id).await
2424 }
2425
2426 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2428 self.mfa_manager
2429 .verify_challenge_code(challenge, code)
2430 .await
2431 }
2432
2433 async fn log_audit_event(
2435 &self,
2436 event_type: &str,
2437 user_id: &str,
2438 method: &str,
2439 metadata: &CredentialMetadata,
2440 ) {
2441 if !self.config.audit.enabled {
2442 return;
2443 }
2444 let should_log = match event_type {
2445 "auth_success" | "mfa_required" => self.config.audit.log_success,
2446 "auth_failure" => self.config.audit.log_failures,
2447 _ => true,
2448 };
2449 if should_log {
2450 self.audit_manager
2451 .log_auth_trace_event(
2452 event_type,
2453 user_id,
2454 method,
2455 metadata.client_ip.as_deref().unwrap_or("unknown"),
2456 metadata.user_agent.as_deref().unwrap_or("unknown"),
2457 )
2458 .await;
2459 }
2460 }
2461
2462 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2464 self.mfa_manager.guard_and_store(challenge).await
2465 }
2466
2467 async fn mint_and_store_token(
2469 &self,
2470 user_id: &str,
2471 scopes: impl Into<crate::types::Scopes>,
2472 method: &str,
2473 lifetime: Option<Duration>,
2474 ) -> Result<AuthToken> {
2475 let token = self
2476 .token_manager
2477 .create_auth_token(user_id, scopes, method, lifetime)?;
2478 self.storage.store_token(&token).await?;
2479 Ok(token)
2480 }
2481
2482 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2484 self.session_manager.coordinate_distributed_sessions().await
2485 }
2486
2487 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2489 self.session_manager.synchronize_session(session_id).await
2490 }
2491
2492 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2494 self.monitoring_manager.clone()
2495 }
2496
2497 #[cfg(feature = "api-server")]
2499 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2500 Some(self.security_manager.clone())
2501 }
2502
2503 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2505 self.monitoring_manager.get_performance_metrics()
2506 }
2507
2508 pub async fn health_check(
2510 &self,
2511 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2512 self.monitoring_manager.health_check().await
2513 }
2514
2515 pub async fn export_prometheus_metrics(&self) -> String {
2517 self.monitoring_manager.export_prometheus_metrics().await
2518 }
2519 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2521 self.require_initialized()?;
2522 self.authorization_manager.create_role(role).await
2523 }
2524
2525 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2527 self.authorization_manager.list_roles().await
2528 }
2529
2530 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2532 self.authorization_manager.get_role(role_name).await
2533 }
2534
2535 pub async fn add_role_permission(
2537 &self,
2538 role_name: &str,
2539 permission: crate::permissions::Permission,
2540 ) -> Result<()> {
2541 self.authorization_manager
2542 .add_role_permission(role_name, permission)
2543 .await
2544 }
2545
2546 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2548 self.require_initialized()?;
2549 self.authorization_manager
2550 .assign_role(user_id, role_name)
2551 .await
2552 }
2553
2554 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2556 self.require_initialized()?;
2557 self.authorization_manager
2558 .remove_role(user_id, role_name)
2559 .await
2560 }
2561
2562 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2564 self.require_initialized()?;
2565 self.authorization_manager
2566 .set_role_inheritance(child_role, parent_role)
2567 .await
2568 }
2569
2570 pub async fn revoke_permission(
2572 &self,
2573 user_id: &str,
2574 action: &str,
2575 resource: &str,
2576 ) -> Result<()> {
2577 self.require_initialized()?;
2578 self.authorization_manager
2579 .revoke_permission(user_id, action, resource)
2580 .await
2581 }
2582
2583 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2585 self.authorization_manager
2586 .user_has_role(user_id, role_name)
2587 .await
2588 }
2589
2590 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2592 self.authorization_manager.list_user_roles(user_id).await
2593 }
2594
2595 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2597 self.authorization_manager
2598 .get_effective_permissions(user_id)
2599 .await
2600 }
2601
2602 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2604 self.authorization_manager
2605 .create_abac_policy(name, description)
2606 .await
2607 }
2608
2609 pub async fn map_user_attribute(
2630 &self,
2631 user_id: &str,
2632 attribute: &str,
2633 value: &str,
2634 ) -> Result<()> {
2635 self.authorization_manager
2636 .map_user_attribute(user_id, attribute, value)
2637 .await
2638 }
2639
2640 pub async fn get_user_attribute(
2664 &self,
2665 user_id: &str,
2666 attribute: &str,
2667 ) -> Result<Option<String>> {
2668 self.authorization_manager
2669 .get_user_attribute(user_id, attribute)
2670 .await
2671 }
2672
2673 pub async fn check_dynamic_permission(
2704 &self,
2705 user_id: &str,
2706 action: &str,
2707 resource: &str,
2708 context: std::collections::HashMap<String, String>,
2709 ) -> Result<bool> {
2710 self.authorization_manager
2711 .check_dynamic_permission(user_id, action, resource, context)
2712 .await
2713 }
2714
2715 pub async fn check_dynamic_permission_with_context(
2735 &self,
2736 user_id: &str,
2737 action: &str,
2738 resource: &str,
2739 context: PermissionContext,
2740 ) -> Result<bool> {
2741 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2742 .await
2743 }
2744
2745 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2747 self.authorization_manager.create_resource(resource).await
2748 }
2749
2750 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2769 self.authorization_manager
2770 .delegate_permission(
2771 req.delegator_id(),
2772 req.delegatee_id(),
2773 req.action(),
2774 req.resource(),
2775 req.get_duration(),
2776 )
2777 .await
2778 }
2779
2780 pub async fn delegate_permission(
2785 &self,
2786 delegator_id: &str,
2787 delegatee_id: &str,
2788 action: &str,
2789 resource: &str,
2790 duration: std::time::Duration,
2791 ) -> Result<()> {
2792 self.authorization_manager
2793 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2794 .await
2795 }
2796
2797 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2799 self.authorization_manager
2800 .get_active_delegations(user_id)
2801 .await
2802 }
2803
2804 pub async fn get_permission_audit_logs(
2806 &self,
2807 user_id: Option<&str>,
2808 action: Option<&str>,
2809 resource: Option<&str>,
2810 limit: Option<usize>,
2811 ) -> Result<Vec<String>> {
2812 self.audit_manager
2813 .get_permission_audit_logs(user_id, action, resource, limit)
2814 .await
2815 }
2816
2817 pub async fn get_permission_audit_logs_with_query(
2837 &self,
2838 query: AuditLogQuery,
2839 ) -> Result<Vec<String>> {
2840 self.audit_manager
2841 .get_permission_audit_logs(
2842 query.get_user_id(),
2843 query.get_action(),
2844 query.get_resource(),
2845 query.get_limit(),
2846 )
2847 .await
2848 }
2849
2850 pub async fn get_permission_metrics(
2852 &self,
2853 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2854 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2855 let permission_checks_last_hour = self
2856 .audit_manager
2857 .get_permission_checks_last_hour()
2858 .await
2859 .unwrap_or(0);
2860 self.authorization_manager
2861 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2862 .await
2863 }
2864
2865 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2867 let active_sessions = self
2868 .session_manager
2869 .count_active_sessions()
2870 .await
2871 .unwrap_or(0);
2872 self.audit_manager
2873 .get_security_audit_stats(active_sessions)
2874 .await
2875 }
2876
2877 pub async fn get_user_profile(
2879 &self,
2880 user_id: &str,
2881 ) -> Result<crate::providers::ProviderProfile> {
2882 self.user_manager.get_user_profile(user_id).await
2883 }
2884}
2885
2886pub use crate::audit::SecurityAuditStats;
2887
2888pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2889
2890#[derive(Debug, Clone, Default)]
2892pub struct AuthStats {
2893 pub registered_methods: Vec<String>,
2895
2896 pub active_sessions: u64,
2898
2899 pub active_mfa_challenges: u64,
2901
2902 pub tokens_issued: u64,
2904
2905 pub auth_attempts: u64,
2907}
2908
2909#[cfg(test)]
2910mod tests {
2911 use super::*;
2912 use crate::config::{AuthConfig, SecurityConfig};
2913 #[tokio::test]
2914 async fn test_framework_initialization() {
2915 let config = AuthConfig::new().security(SecurityConfig {
2916 min_password_length: 8,
2917 require_password_complexity: false,
2918 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2919 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2920 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2921 secure_cookies: false,
2922 cookie_same_site: crate::config::CookieSameSite::Lax,
2923 csrf_protection: false,
2924 session_timeout: Duration::from_secs(3600),
2925 previous_secret_key: None,
2926 });
2927 let mut framework = AuthFramework::new(config);
2928
2929 assert!(framework.initialize().await.is_ok());
2930 assert!(framework.initialized);
2931 }
2932
2933 #[tokio::test]
2934 async fn test_method_registration() {
2935 let config = AuthConfig::new().security(SecurityConfig {
2940 min_password_length: 8,
2941 require_password_complexity: false,
2942 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2943 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2944 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2945 secure_cookies: false,
2946 cookie_same_site: crate::config::CookieSameSite::Lax,
2947 csrf_protection: false,
2948 session_timeout: Duration::from_secs(3600),
2949 previous_secret_key: None,
2950 });
2951 let framework = AuthFramework::new(config);
2952
2953 assert!(!framework.initialized);
2955
2956 }
2959
2960 #[tokio::test]
2961 async fn test_token_validation() {
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 token = framework
2978 .token_manager
2979 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2980 .unwrap();
2981
2982 framework.storage.store_token(&token).await.unwrap();
2984
2985 assert!(framework.validate_token(&token).await.unwrap());
2986 }
2987
2988 #[tokio::test]
2989 async fn test_session_management() {
2990 let config = AuthConfig::new().security(SecurityConfig {
2991 min_password_length: 8,
2992 require_password_complexity: false,
2993 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2994 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2995 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2996 secure_cookies: false,
2997 cookie_same_site: crate::config::CookieSameSite::Lax,
2998 csrf_protection: false,
2999 session_timeout: Duration::from_secs(3600),
3000 previous_secret_key: None,
3001 });
3002 let mut framework = AuthFramework::new(config);
3003 framework.initialize().await.unwrap();
3004
3005 let session_id = framework
3006 .create_session(
3007 "test-user",
3008 Duration::from_secs(3600),
3009 Some("192.168.1.1".to_string()),
3010 Some("Test Agent".to_string()),
3011 )
3012 .await
3013 .unwrap();
3014
3015 let session = framework.get_session(&session_id).await.unwrap();
3016 assert!(session.is_some());
3017
3018 framework.delete_session(&session_id).await.unwrap();
3019 let session = framework.get_session(&session_id).await.unwrap();
3020 assert!(session.is_none());
3021 }
3022
3023 #[tokio::test]
3024 async fn test_grouped_operations_accessors() {
3025 let config = AuthConfig::new().security(SecurityConfig {
3026 min_password_length: 8,
3027 require_password_complexity: false,
3028 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3029 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3030 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3031 secure_cookies: false,
3032 cookie_same_site: crate::config::CookieSameSite::Lax,
3033 csrf_protection: false,
3034 session_timeout: Duration::from_secs(3600),
3035 previous_secret_key: None,
3036 });
3037 let mut framework = AuthFramework::new(config);
3038 framework.initialize().await.unwrap();
3039
3040 let user_id = framework
3041 .users()
3042 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
3043 .await
3044 .unwrap();
3045 assert!(
3046 framework
3047 .users()
3048 .exists_by_username("grouped-user")
3049 .await
3050 .unwrap()
3051 );
3052
3053 let session_id = framework
3054 .sessions()
3055 .create(&user_id, Duration::from_secs(300), None, None)
3056 .await
3057 .unwrap();
3058 assert!(
3059 framework
3060 .sessions()
3061 .get(&session_id)
3062 .await
3063 .unwrap()
3064 .is_some()
3065 );
3066 assert_eq!(
3067 framework
3068 .sessions()
3069 .list_for_user(&user_id)
3070 .await
3071 .unwrap()
3072 .len(),
3073 1
3074 );
3075
3076 framework
3077 .authorization()
3078 .grant(&user_id, "read", "documents")
3079 .await
3080 .unwrap();
3081 let permissions = framework
3082 .authorization()
3083 .effective_permissions(&user_id)
3084 .await
3085 .unwrap();
3086 assert!(
3087 permissions
3088 .iter()
3089 .any(|permission| permission == "read:documents")
3090 );
3091
3092 framework.sessions().delete(&session_id).await.unwrap();
3093 assert!(
3094 framework
3095 .sessions()
3096 .get(&session_id)
3097 .await
3098 .unwrap()
3099 .is_none()
3100 );
3101 }
3102
3103 #[tokio::test]
3104 async fn test_cleanup_expired_data() {
3105 let config = AuthConfig::new().security(SecurityConfig {
3106 min_password_length: 8,
3107 require_password_complexity: false,
3108 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3109 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3110 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3111 secure_cookies: false,
3112 cookie_same_site: crate::config::CookieSameSite::Lax,
3113 csrf_protection: false,
3114 session_timeout: Duration::from_secs(3600),
3115 previous_secret_key: None,
3116 });
3117 let mut framework = AuthFramework::new(config);
3118 framework.initialize().await.unwrap();
3119
3120 assert!(framework.cleanup_expired_data().await.is_ok());
3122 }
3123
3124 #[cfg(feature = "redis-storage")]
3132 #[test]
3133 fn new_validated_redis_fails_closed_without_an_encryption_key() {
3134 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3135 unsafe {
3138 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3139 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3140 }
3141
3142 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3143 config.storage = crate::config::StorageConfig::Redis {
3144 url: "redis://127.0.0.1:1/".to_string(),
3145 key_prefix: "test:".to_string(),
3146 };
3147 let result = AuthFramework::new_validated(config);
3150 assert!(
3151 result.is_err(),
3152 "constructing with Redis storage and no encryption key configured must fail \
3153 closed, not silently build unwrapped (unencrypted) storage"
3154 );
3155 }
3156
3157 #[tokio::test]
3158 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3159 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3160 config.storage_encryption.require_wrapped_storage = true;
3161 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3162 assert!(
3163 framework.initialize().await.is_err(),
3164 "caller-supplied unwrapped storage must be refused when wrapping is required"
3165 );
3166 }
3167
3168 #[tokio::test]
3169 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3170 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3171 required.storage_encryption.require_wrapped_storage = true;
3172 let wrapped: Arc<dyn AuthStorage> =
3173 Arc::new(crate::storage::encryption::EncryptedStorage::new(
3174 MemoryStorage::new(),
3175 crate::storage::encryption::StorageEncryption::new_random(),
3176 false,
3177 false,
3178 ));
3179 let mut framework = AuthFramework::new_with_storage(required, wrapped);
3180 framework.initialize().await.unwrap();
3181
3182 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3184 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3185 framework.initialize().await.unwrap();
3186 }
3187
3188 #[tokio::test]
3189 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3190 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3191 config.storage_encryption.require_wrapped_storage = true;
3192 let mut framework = AuthFramework::new(config);
3193 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3195 framework.initialize().await.unwrap();
3196 }
3197}