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 maintenance(&self) -> MaintenanceOperations<'_> {
418 MaintenanceOperations { framework: self }
419 }
420
421 pub async fn runtime_config(&self) -> crate::config::RuntimeConfig {
423 self.runtime_config.read().await.clone()
424 }
425
426 #[deprecated(since = "0.6.0", note = "Use `runtime_config()` instead")]
427 #[doc(hidden)]
428 pub async fn get_runtime_config(&self) -> crate::config::RuntimeConfig {
429 self.runtime_config().await
430 }
431
432 pub async fn update_runtime_config(
437 &self,
438 update: crate::config::RuntimeConfig,
439 ) -> Result<crate::config::RuntimeConfig> {
440 if update.token_lifetime_secs == 0 {
442 return Err(AuthError::config("token_lifetime_secs must be > 0"));
443 }
444 if update.refresh_token_lifetime_secs == 0 {
445 return Err(AuthError::config("refresh_token_lifetime_secs must be > 0"));
446 }
447 if update.refresh_token_lifetime_secs <= update.token_lifetime_secs {
448 return Err(AuthError::config(
449 "refresh_token_lifetime_secs must be greater than token_lifetime_secs",
450 ));
451 }
452 if update.min_password_length == 0 {
453 return Err(AuthError::config("min_password_length must be > 0"));
454 }
455 let mut cfg = self.runtime_config.write().await;
456 *cfg = update.clone();
457 Ok(update)
458 }
459
460 pub fn admin(&self) -> AdminOperations<'_> {
462 AdminOperations { framework: self }
463 }
464
465 pub fn new(config: AuthConfig) -> Self {
473 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
475 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
476 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
477
478 let ephemeral_secret = {
484 let rng = ring::rand::SystemRandom::new();
485 let mut buf = [0u8; 32];
486 ring::rand::SecureRandom::fill(&rng, &mut buf)
487 .expect("AuthFramework fatal: system CSPRNG unavailable — the operating system cannot provide cryptographic randomness");
488 buf
489 };
490 let token_manager =
491 TokenManager::new_hmac(&ephemeral_secret, "auth-framework", "auth-framework");
492
493 let user_manager = crate::auth_modular::user_manager::UserManager::new(
494 storage.clone(),
495 config.security.password_hash_algorithm.clone(),
496 );
497 let session_manager =
498 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
499 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
500 let authorization_manager =
501 crate::auth_modular::authorization_manager::AuthorizationManager::new(
502 Arc::new(RwLock::new(PermissionChecker::new())),
503 storage.clone(),
504 );
505
506 Self {
507 config,
508 methods: HashMap::new(),
509 token_manager,
510 storage,
511 authorization_manager,
512 rate_limiter: None, monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
514 crate::monitoring::MonitoringConfig::default(),
515 )),
516 audit_manager,
517 #[cfg(feature = "api-server")]
518 security_manager: Arc::new(crate::api::SecurityManager::new()),
519 runtime_config: Arc::new(tokio::sync::RwLock::new(
520 crate::config::RuntimeConfig::default(),
521 )),
522 user_manager,
523 session_manager,
524 mfa_manager,
525 initialized: false,
526 storage_overridden: false,
527 storage_from_caller: false,
528 }
529 }
530
531 pub fn new_validated(config: AuthConfig) -> Result<Self> {
536 config.validate().map_err(|e| {
538 AuthError::configuration(format!("Configuration validation failed: {}", e))
539 })?;
540
541 let current_secret_bytes = resolve_jwt_secret_bytes(&config)?;
543
544 let mut token_manager =
545 TokenManager::new_hmac(¤t_secret_bytes, "auth-framework", "auth-framework");
546
547 if let Some(prev_secret) = &config.security.previous_secret_key {
549 token_manager =
551 TokenManager::new_hmac(prev_secret.as_bytes(), "auth-framework", "auth-framework");
552 token_manager.rotate_hmac_key(¤t_secret_bytes);
553 }
554
555 let storage: Arc<dyn AuthStorage> = match &config.storage {
564 #[cfg(feature = "redis-storage")]
565 crate::config::StorageConfig::Redis { url, key_prefix } => {
566 let redis: Arc<dyn AuthStorage> = Arc::new(
567 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
568 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
569 })?,
570 );
571 crate::storage::factory::wrap_with_encryption_if_enabled(
572 redis,
573 &config.storage_encryption,
574 )?
575 }
576 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
577 };
578
579 let rate_limiter = if config.rate_limiting.enabled {
581 Some(RateLimiter::new(
582 config.rate_limiting.max_requests,
583 config.rate_limiting.window,
584 ))
585 } else {
586 None
587 };
588
589 let audit_storage = crate::audit::build_audit_storage(&config.audit.storage);
591 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
592
593 let user_manager = crate::auth_modular::user_manager::UserManager::new(
594 storage.clone(),
595 config.security.password_hash_algorithm.clone(),
596 );
597 let session_manager =
598 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
599 let mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
600 let authorization_manager =
601 crate::auth_modular::authorization_manager::AuthorizationManager::new(
602 Arc::new(RwLock::new(PermissionChecker::new())),
603 storage.clone(),
604 );
605
606 Ok(Self {
607 config: config.clone(),
608 methods: HashMap::new(),
609 token_manager,
610 storage,
611 authorization_manager,
612 rate_limiter,
613 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
614 crate::monitoring::MonitoringConfig::default(),
615 )),
616 audit_manager,
617 #[cfg(feature = "api-server")]
618 security_manager: Arc::new(crate::api::SecurityManager::new()),
619 runtime_config: Arc::new(tokio::sync::RwLock::new(
620 crate::config::RuntimeConfig::from_auth_config(&config),
621 )),
622 user_manager,
623 session_manager,
624 mfa_manager,
625 initialized: false,
626 storage_overridden: false,
627 storage_from_caller: false,
628 })
629 }
630
631 pub fn replace_storage(&mut self, storage: std::sync::Arc<dyn AuthStorage>) {
638 self.storage = storage.clone();
639 self.user_manager = crate::auth_modular::user_manager::UserManager::new(
640 storage.clone(),
641 self.config.security.password_hash_algorithm.clone(),
642 );
643 self.session_manager =
644 crate::auth_modular::session_manager::SessionManager::new(storage.clone());
645 self.mfa_manager = crate::auth_modular::mfa::MfaManager::new(storage.clone());
646 self.authorization_manager =
647 crate::auth_modular::authorization_manager::AuthorizationManager::new(
648 Arc::new(RwLock::new(PermissionChecker::new())),
649 storage,
650 );
651 self.storage_overridden = true;
652 self.storage_from_caller = true;
653 }
654
655 pub(crate) fn replace_storage_from_factory(
659 &mut self,
660 storage: std::sync::Arc<dyn AuthStorage>,
661 ) {
662 self.replace_storage(storage);
663 self.storage_from_caller = false;
664 }
665
666 pub fn set_distributed_store(&mut self, store: Arc<dyn DistributedSessionStore>) {
673 self.session_manager.set_distributed_store(store);
674 }
675
676 pub fn new_with_storage(config: AuthConfig, storage: std::sync::Arc<dyn AuthStorage>) -> Self {
678 let mut framework = Self::new(config);
679 framework.replace_storage(storage);
680 framework
681 }
682
683 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
685 let name = name.into();
686 info!("Registering authentication method: {}", name);
687
688 if let Err(e) = method.validate_config() {
690 error!("Method '{}' configuration validation failed: {}", name, e);
691 return;
692 }
693
694 self.methods.insert(name, method);
695 }
696
697 fn require_initialized(&self) -> Result<()> {
703 if self.initialized {
704 Ok(())
705 } else {
706 Err(AuthError::configuration(
707 "Framework not initialized. Call `initialize().await` first, \
708 or use `AuthFramework::builder().build().await` which initializes automatically.",
709 ))
710 }
711 }
712
713 pub async fn initialize(&mut self) -> Result<()> {
723 if self.initialized {
724 return Ok(());
725 }
726
727 info!("Initializing authentication framework");
728
729 self.config.validate().map_err(|e| {
731 AuthError::configuration(format!("Configuration validation failed: {}", e))
732 })?;
733
734 let token_manager = match resolve_jwt_secret_bytes(&self.config) {
736 Ok(bytes) => TokenManager::new_hmac(&bytes, "auth-framework", "auth-framework"),
737 Err(_) => {
738 if Self::is_production_environment() {
739 return Err(AuthError::configuration(
740 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
741 Generate a secure secret with: openssl rand -base64 32\n\
742 Set it with: export JWT_SECRET=\"your-secret-here\"",
743 ));
744 }
745 warn!("No JWT secret configured, using development-only default");
746 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
747 warn!("This configuration is NOT SECURE and should only be used in development!");
748 self.token_manager.clone()
749 }
750 };
751
752 self.token_manager = token_manager;
754
755 if self.storage_from_caller {
759 crate::storage::factory::check_overridden_storage(
760 &self.storage,
761 &self.config.storage_encryption,
762 )?;
763 }
764
765 if !self.storage_overridden {
767 let storage = crate::storage::factory::build_storage_backend_with_encryption(
768 &self.config.storage,
769 None,
770 &self.config.storage_encryption,
771 )
772 .await?;
773 self.replace_storage(storage);
774 self.storage_overridden = false;
775 self.storage_from_caller = false;
776 }
777
778 if self.config.rate_limiting.enabled {
780 self.rate_limiter = Some(RateLimiter::new(
781 self.config.rate_limiting.max_requests,
782 self.config.rate_limiting.window,
783 ));
784 }
785
786 self.authorization_manager.create_default_roles().await;
788
789 self.authorization_manager.load_persisted_roles().await?;
791
792 self.cleanup_expired_data().await?;
794
795 self.initialized = true;
796 info!("Authentication framework initialized successfully");
797
798 Ok(())
799 }
800
801 pub async fn authenticate(
829 &self,
830 method_name: &str,
831 credential: Credential,
832 ) -> Result<AuthResult> {
833 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
834 .await
835 }
836
837 pub async fn authenticate_with_metadata(
839 &self,
840 method_name: &str,
841 credential: Credential,
842 metadata: CredentialMetadata,
843 ) -> Result<AuthResult> {
844 use std::time::Instant;
845 use tokio::time::{Duration as TokioDuration, sleep};
846
847 let start_time = Instant::now();
848
849 self.monitoring_manager.record_auth_request().await;
851
852 self.require_initialized()?;
853
854 let result = self
856 .authenticate_internal(method_name, credential, metadata)
857 .await;
858
859 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
862 if elapsed < min_duration {
863 sleep(min_duration - elapsed).await;
864 }
865
866 if let Ok(ref auth_result) = result {
868 match auth_result {
869 AuthResult::Success(token) => {
870 self.monitoring_manager
871 .record_auth_success(&token.user_id, elapsed)
872 .await;
873 }
874 AuthResult::Failure(reason) => {
875 self.monitoring_manager
876 .record_auth_failure(None, reason)
877 .await;
878 }
879 _ => {} }
881 }
882
883 result
884 }
885
886 async fn authenticate_internal(
888 &self,
889 method_name: &str,
890 credential: Credential,
891 metadata: CredentialMetadata,
892 ) -> Result<AuthResult> {
893 if let Some(ref rate_limiter) = self.rate_limiter {
895 let rate_key = format!(
896 "auth:{}:{}",
897 method_name,
898 metadata.client_ip.as_deref().unwrap_or("unknown")
899 );
900
901 if !rate_limiter.is_allowed(&rate_key) {
902 warn!(
903 "Rate limit exceeded for method '{}' from IP {:?}",
904 method_name, metadata.client_ip
905 );
906 return Err(AuthError::rate_limit("Too many authentication attempts"));
907 }
908 }
909
910 if method_name == "password"
914 && let Credential::Password {
915 ref username,
916 ref password,
917 } = credential
918 {
919 return self
920 .authenticate_password_builtin(username, password, &metadata)
921 .await;
922 }
923
924 if method_name == "jwt" {
925 return match credential {
926 Credential::Jwt { token } | Credential::Bearer { token } => {
927 self.authenticate_jwt_builtin(&token, &metadata, "jwt")
928 .await
929 }
930 _ => Ok(AuthResult::Failure(
931 "JWT authentication expects Credential::jwt or Credential::bearer".to_string(),
932 )),
933 };
934 }
935
936 if matches!(method_name, "api_key" | "api-key") {
937 return match credential {
938 Credential::ApiKey { key } => {
939 self.authenticate_api_key_builtin(&key, &metadata, "api_key")
940 .await
941 }
942 _ => Ok(AuthResult::Failure(
943 "API key authentication expects Credential::api_key".to_string(),
944 )),
945 };
946 }
947
948 if method_name == "oauth2" {
949 return self
950 .authenticate_oauth2_builtin(credential, &metadata)
951 .await;
952 }
953
954 let method = self.methods.get(method_name).ok_or_else(|| {
956 AuthError::auth_method(method_name, "Authentication method not found".to_string())
957 })?;
958
959 debug!(
961 "Authentication attempt with method '{}' for credential: {}",
962 method_name,
963 credential.safe_display()
964 );
965
966 let result = method.authenticate(credential, metadata.clone()).await?;
968
969 match &result {
971 MethodResult::Success(token) => {
972 info!(
973 "Authentication successful for user '{}' with method '{}'",
974 token.user_id, method_name
975 );
976
977 self.storage.store_token(token).await?;
979
980 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
982 .await;
983
984 Ok(AuthResult::Success(token.clone()))
985 }
986
987 MethodResult::MfaRequired(challenge) => {
988 info!(
989 "MFA required for user '{}' with method '{}'",
990 challenge.user_id, method_name
991 );
992
993 self.guard_and_store_mfa_challenge((**challenge).clone())
995 .await?;
996
997 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
999 .await;
1000
1001 Ok(AuthResult::MfaRequired(challenge.clone()))
1002 }
1003
1004 MethodResult::Failure { reason } => {
1005 warn!(
1006 "Authentication failed for method '{}': {}",
1007 method_name, reason
1008 );
1009
1010 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
1012 .await;
1013
1014 Ok(AuthResult::Failure(reason.clone()))
1015 }
1016 }
1017 }
1018
1019 async fn authenticate_jwt_builtin(
1020 &self,
1021 token: &str,
1022 metadata: &CredentialMetadata,
1023 auth_method: &str,
1024 ) -> Result<AuthResult> {
1025 if token.is_empty() {
1026 return Ok(AuthResult::Failure("JWT token cannot be empty".to_string()));
1027 }
1028
1029 match validate_access_jwt_with(
1030 &self.token_manager,
1031 self.storage.as_ref(),
1032 token,
1033 false,
1034 false,
1035 )
1036 .await
1037 {
1038 Ok(claims) => {
1039 let token =
1040 Self::build_validated_jwt_auth_token(token, claims, metadata, auth_method);
1041 Ok(AuthResult::Success(Box::new(token)))
1042 }
1043 Err(error) => {
1044 if let Some(reason) = Self::credential_failure_reason(&error) {
1045 Ok(AuthResult::Failure(reason))
1046 } else {
1047 Err(error)
1048 }
1049 }
1050 }
1051 }
1052
1053 async fn authenticate_api_key_builtin(
1054 &self,
1055 api_key: &str,
1056 metadata: &CredentialMetadata,
1057 auth_method: &str,
1058 ) -> Result<AuthResult> {
1059 if api_key.is_empty() {
1060 return Ok(AuthResult::Failure("API key cannot be empty".to_string()));
1061 }
1062
1063 match self.validate_api_key(api_key).await {
1064 Ok(user) => {
1065 let scopes: Vec<String> = if user.roles.is_empty() {
1066 vec!["api_user".to_string()]
1067 } else {
1068 user.roles.to_vec()
1069 };
1070 let mut token = self
1071 .token_manager
1072 .create_auth_token(&user.id, scopes.clone(), auth_method, None)?
1073 .with_roles(user.roles)
1074 .with_scopes(scopes);
1075 token.metadata.issued_ip = metadata.client_ip.clone();
1076 token.metadata.user_agent = metadata.user_agent.clone();
1077 Ok(AuthResult::Success(Box::new(token)))
1078 }
1079 Err(error) => {
1080 if let Some(reason) = Self::credential_failure_reason(&error) {
1081 Ok(AuthResult::Failure(reason))
1082 } else {
1083 Err(error)
1084 }
1085 }
1086 }
1087 }
1088
1089 async fn authenticate_oauth2_builtin(
1090 &self,
1091 credential: Credential,
1092 metadata: &CredentialMetadata,
1093 ) -> Result<AuthResult> {
1094 match credential {
1095 Credential::OAuth {
1096 authorization_code, ..
1097 } => {
1098 if authorization_code.is_empty() {
1099 return Ok(AuthResult::Failure(
1100 "OAuth authorization code cannot be empty".to_string(),
1101 ));
1102 }
1103 Ok(AuthResult::Failure(
1104 "OAuth 2.0 authorization codes must be exchanged through an OAuth provider or server endpoint before authentication completes"
1105 .to_string(),
1106 ))
1107 }
1108 Credential::OAuthRefresh { refresh_token } => {
1109 if refresh_token.is_empty() {
1110 return Ok(AuthResult::Failure(
1111 "OAuth refresh token cannot be empty".to_string(),
1112 ));
1113 }
1114 Ok(AuthResult::Failure(
1115 "OAuth 2.0 refresh tokens must be exchanged through an OAuth provider or server endpoint before authentication completes"
1116 .to_string(),
1117 ))
1118 }
1119 Credential::Jwt { token }
1120 | Credential::Bearer { token }
1121 | Credential::OpenIdConnect { id_token: token, .. } => {
1122 self.authenticate_jwt_builtin(&token, metadata, "oauth2").await
1123 }
1124 _ => Ok(AuthResult::Failure(
1125 "OAuth2 authentication expects Credential::oauth_code, Credential::oauth_refresh, Credential::jwt, Credential::bearer, or Credential::openid_connect"
1126 .to_string(),
1127 )),
1128 }
1129 }
1130
1131 fn build_validated_jwt_auth_token(
1132 raw_token: &str,
1133 claims: crate::tokens::JwtClaims,
1134 metadata: &CredentialMetadata,
1135 auth_method: &str,
1136 ) -> AuthToken {
1137 let crate::tokens::JwtClaims {
1138 sub,
1139 iss,
1140 exp,
1141 iat,
1142 jti,
1143 scope,
1144 permissions,
1145 roles,
1146 client_id,
1147 ..
1148 } = claims;
1149
1150 let now = chrono::Utc::now();
1151 let issued_at = chrono::DateTime::<chrono::Utc>::from_timestamp(iat, 0).unwrap_or(now);
1152 let expires_at = chrono::DateTime::<chrono::Utc>::from_timestamp(exp, 0)
1153 .unwrap_or(now + chrono::Duration::hours(1));
1154 let lifetime = (expires_at - now)
1155 .to_std()
1156 .unwrap_or_else(|_| Duration::from_secs(1));
1157 let scopes = if scope.trim().is_empty() {
1158 Vec::new()
1159 } else {
1160 scope.split_whitespace().map(str::to_string).collect()
1161 };
1162
1163 let mut token = AuthToken::new(sub.clone(), raw_token.to_string(), lifetime, auth_method)
1164 .with_scopes(scopes)
1165 .with_permissions(permissions.unwrap_or_default())
1166 .with_roles(roles.unwrap_or_default());
1167 token.token_id = jti;
1168 token.subject = Some(sub);
1169 token.issuer = Some(iss);
1170 token.issued_at = issued_at;
1171 token.expires_at = expires_at;
1172 token.metadata.issued_ip = metadata.client_ip.clone();
1173 token.metadata.user_agent = metadata.user_agent.clone();
1174 if let Some(client_id) = client_id {
1175 token.client_id = Some(client_id);
1176 }
1177 token
1178 }
1179
1180 fn credential_failure_reason(error: &AuthError) -> Option<String> {
1181 match error {
1182 AuthError::Token(_) | AuthError::Jwt(_) => Some(error.to_string()),
1183 AuthError::Validation { message } => Some(message.clone()),
1184 AuthError::UserNotFound => Some("User not found".to_string()),
1185 _ => None,
1186 }
1187 }
1188
1189 async fn authenticate_password_builtin(
1191 &self,
1192 username: &str,
1193 password: &str,
1194 metadata: &CredentialMetadata,
1195 ) -> Result<AuthResult> {
1196 use crate::auth_modular::user_manager::CredentialCheckResult;
1197
1198 if username.is_empty() || password.is_empty() {
1199 return Ok(AuthResult::Failure(
1200 "Username or password cannot be empty".to_string(),
1201 ));
1202 }
1203
1204 match self
1205 .user_manager
1206 .verify_login_credentials(username, password)
1207 .await?
1208 {
1209 None => {
1210 self.log_audit_event("auth_failure", "unknown", "password", metadata)
1211 .await;
1212 Ok(AuthResult::Failure(
1213 "Invalid username or password".to_string(),
1214 ))
1215 }
1216 Some(CredentialCheckResult {
1217 ref user_id,
1218 mfa_enabled: true,
1219 }) => {
1220 let now = chrono::Utc::now();
1221 let challenge = MfaChallenge {
1222 id: crate::utils::string::generate_id(Some("mfa")),
1223 mfa_type: crate::methods::MfaType::MultiMethod,
1224 user_id: user_id.clone(),
1225 created_at: now,
1226 expires_at: now + chrono::Duration::minutes(5),
1227 attempts: 0,
1228 max_attempts: 5,
1229 code_hash: None,
1230 message: Some(
1231 "Provide your current TOTP code or a backup code to complete login"
1232 .to_string(),
1233 ),
1234 data: HashMap::new(),
1235 };
1236 self.guard_and_store_mfa_challenge(challenge.clone())
1237 .await?;
1238 self.log_audit_event("mfa_required", user_id, "password", metadata)
1239 .await;
1240 info!(
1241 "Built-in password authentication requires MFA for user: {}",
1242 username
1243 );
1244 Ok(AuthResult::MfaRequired(Box::new(challenge)))
1245 }
1246 Some(CredentialCheckResult {
1247 ref user_id,
1248 mfa_enabled: false,
1249 }) => {
1250 let token = self
1251 .mint_and_store_token(
1252 user_id,
1253 vec!["read".to_string(), "write".to_string()],
1254 "password",
1255 None,
1256 )
1257 .await?;
1258 self.monitoring_manager.record_auth_request().await;
1259 self.log_audit_event("auth_success", user_id, "password", metadata)
1260 .await;
1261 info!(
1262 "Built-in password authentication successful for user: {}",
1263 username
1264 );
1265 Ok(AuthResult::Success(Box::new(token)))
1266 }
1267 }
1268 }
1269
1270 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
1272 debug!("Completing MFA for challenge '{}'", challenge.id);
1273
1274 let stored_challenge = self
1277 .mfa_manager
1278 .begin_attempt(&challenge.id)
1279 .await?
1280 .ok_or(MfaError::ChallengeExpired)?;
1281
1282 if !self.verify_mfa_code(&stored_challenge, mfa_code).await? {
1283 if stored_challenge.attempts >= stored_challenge.max_attempts {
1284 self.mfa_manager.remove_challenge(&challenge.id).await?;
1285 }
1286 return Err(MfaError::InvalidCode.into());
1287 }
1288
1289 self.mfa_manager.remove_challenge(&challenge.id).await?;
1290
1291 let user_id = stored_challenge.user_id.as_str();
1292 let scopes = self
1293 .user_manager
1294 .get_user_roles(user_id)
1295 .await
1296 .unwrap_or_else(|_| vec!["user".to_string()]);
1297
1298 let token = self
1299 .mint_and_store_token(user_id, scopes, "mfa", None)
1300 .await?;
1301
1302 info!("MFA completed successfully for user '{}'", user_id);
1303 Ok(token)
1304 }
1305
1306 pub async fn mfa_challenge_owner(&self, challenge_id: &str) -> Option<String> {
1308 self.mfa_manager
1309 .get_challenge(challenge_id)
1310 .await
1311 .ok()
1312 .flatten()
1313 .map(|c| c.user_id)
1314 }
1315
1316 pub(crate) async fn discard_mfa_challenge(&self, challenge_id: &str) {
1318 let _ = self.mfa_manager.remove_challenge(challenge_id).await;
1319 }
1320
1321 pub async fn complete_mfa_by_id(
1323 &self,
1324 challenge_id: &str,
1325 mfa_code: &str,
1326 ) -> Result<AuthToken> {
1327 let challenge = self
1328 .mfa_manager
1329 .get_challenge(challenge_id)
1330 .await?
1331 .ok_or(MfaError::ChallengeExpired)?;
1332
1333 self.complete_mfa(challenge, mfa_code).await
1334 }
1335
1336 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
1338 self.require_initialized()?;
1339 let valid = token.is_valid()
1340 && self.token_manager.validate_auth_token(token).is_ok()
1341 && token_value_matches_jwt(&self.token_manager, token)
1342 && !access_token_is_revoked(&self.token_manager, self.storage.as_ref(), token).await?
1343 && self.touch_stored_token(token).await?;
1344 self.monitoring_manager.record_token_validation(valid).await;
1345 Ok(valid)
1346 }
1347
1348 async fn touch_stored_token(&self, token: &AuthToken) -> Result<bool> {
1349 let Some(mut stored) = self.storage.get_token(&token.token_id).await? else {
1350 return Ok(false);
1351 };
1352 if stored.is_revoked() {
1353 return Ok(false);
1354 }
1355 if stored.access_token != token.access_token || stored.user_id != token.user_id {
1357 return Ok(false);
1358 }
1359 stored.mark_used();
1360 self.storage.update_token(&stored).await?;
1361 Ok(true)
1362 }
1363
1364 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
1366 if !self.validate_token(token).await? {
1367 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
1368 }
1369
1370 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
1371
1372 match self.user_manager.get_user_info(&token_info.user_id).await {
1375 Ok(mut info) => {
1376 if !token_info.attributes.is_empty() {
1378 let string_attrs: HashMap<String, String> = token_info
1379 .attributes
1380 .into_iter()
1381 .map(|(k, v)| {
1382 (
1383 k,
1384 v.as_str()
1385 .map(|s| s.to_string())
1386 .unwrap_or_else(|| v.to_string()),
1387 )
1388 })
1389 .collect();
1390 info.attributes = string_attrs.into();
1391 }
1392 Ok(info)
1393 }
1394 Err(_) => {
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 Ok(UserInfo {
1408 id: token_info.user_id,
1409 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
1410 email: token_info.email,
1411 name: token_info.name,
1412 roles: token_info.roles.into(),
1413 active: false,
1414 email_verified: false,
1415 attributes: string_attrs.into(),
1416 })
1417 }
1418 }
1419 }
1420
1421 pub async fn check_permission(
1448 &self,
1449 token: &AuthToken,
1450 action: &str,
1451 resource: &str,
1452 ) -> Result<bool> {
1453 let Some(proof) = self.validated_token(token).await? else {
1454 return Ok(false);
1455 };
1456 self.check_validated_permission(&proof, action, resource)
1457 .await
1458 }
1459
1460 pub async fn validated_token(
1462 &self,
1463 token: &AuthToken,
1464 ) -> Result<Option<crate::tokens::ValidatedToken>> {
1465 Ok(self
1466 .validate_token(token)
1467 .await?
1468 .then(|| crate::tokens::ValidatedToken::new(token.clone())))
1469 }
1470
1471 pub async fn check_validated_permission(
1473 &self,
1474 proof: &crate::tokens::ValidatedToken,
1475 action: &str,
1476 resource: &str,
1477 ) -> Result<bool> {
1478 self.authorization_manager
1479 .check_validated_permission(proof, action, resource)
1480 .await
1481 }
1482
1483 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1485 self.require_initialized()?;
1486 debug!("Refreshing token for user '{}'", token.user_id);
1487
1488 if let Some(method) = self.methods.get(&token.auth_method)
1490 && method.supports_refresh()
1491 && let Some(ref refresh_token) = token.refresh_token
1492 {
1493 let new_token = method.refresh_token(refresh_token.to_string()).await?;
1494 self.storage.store_token(&new_token).await?;
1495 return Ok(new_token);
1496 }
1497
1498 if !self.validate_token(token).await? {
1502 return Err(AuthError::Token(crate::errors::TokenError::Invalid {
1503 message: "Cannot refresh a token that is not valid".to_string(),
1504 }));
1505 }
1506 let stored = self
1508 .storage
1509 .get_token(&token.token_id)
1510 .await?
1511 .ok_or_else(|| {
1512 AuthError::Token(crate::errors::TokenError::Invalid {
1513 message: "Cannot refresh a token that is not stored".to_string(),
1514 })
1515 })?;
1516 let new_token = self.token_manager.refresh_token(&stored)?;
1517 self.storage.store_token(&new_token).await?;
1518
1519 info!("Token refreshed for user '{}'", token.user_id);
1520
1521 Ok(new_token)
1522 }
1523
1524 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
1526 self.require_initialized()?;
1527 debug!("Revoking token for user '{}'", token.user_id);
1528
1529 let mut revoked_token = token.clone();
1531 revoked_token.revoke(Some("Manual revocation".to_string()));
1532
1533 self.storage.update_token(&revoked_token).await?;
1535
1536 let jti = self
1539 .token_manager
1540 .validate_jwt_token(&token.access_token)
1541 .map(|claims| claims.jti)
1542 .unwrap_or_else(|_| token.token_id.clone());
1543 let remaining = (token.expires_at - chrono::Utc::now())
1544 .to_std()
1545 .unwrap_or_default()
1546 .max(Duration::from_secs(60));
1547 self.storage
1548 .store_kv(&format!("revoked_token:{jti}"), b"revoked", Some(remaining))
1549 .await?;
1550
1551 info!("Token revoked for user '{}'", token.user_id);
1552
1553 Ok(())
1554 }
1555
1556 pub async fn create_api_key(
1558 &self,
1559 user_id: &str,
1560 expires_in: Option<Duration>,
1561 ) -> Result<String> {
1562 self.require_initialized()?;
1563 self.user_manager.create_api_key(user_id, expires_in).await
1564 }
1565
1566 pub async fn create_api_key_with_role(
1573 &self,
1574 user_id: &str,
1575 role: &str,
1576 expires_in: Option<Duration>,
1577 ) -> Result<String> {
1578 self.require_initialized()?;
1579 self.user_manager
1580 .create_api_key_with_role(user_id, role, expires_in)
1581 .await
1582 }
1583
1584 pub async fn rotate_api_key(&self, old_key: &str) -> Result<String> {
1590 self.require_initialized()?;
1591 self.user_manager.rotate_api_key(old_key).await
1592 }
1593
1594 pub async fn rotate_api_key_with_expiry(
1596 &self,
1597 old_key: &str,
1598 expires_in: Option<Duration>,
1599 ) -> Result<String> {
1600 self.require_initialized()?;
1601 self.user_manager
1602 .rotate_api_key_with_expiry(old_key, expires_in)
1603 .await
1604 }
1605
1606 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
1608 self.require_initialized()?;
1609 self.user_manager.validate_api_key(api_key).await
1610 }
1611
1612 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
1614 self.require_initialized()?;
1615 self.user_manager.revoke_api_key(api_key).await
1616 }
1617
1618 pub async fn create_session(
1620 &self,
1621 user_id: &str,
1622 expires_in: Duration,
1623 ip_address: Option<String>,
1624 user_agent: Option<String>,
1625 ) -> Result<String> {
1626 self.require_initialized()?;
1627 let (session_id, new_total) = self
1628 .session_manager
1629 .create_session_limited(user_id, expires_in, ip_address, user_agent)
1630 .await?;
1631 self.monitoring_manager
1632 .update_session_count(new_total)
1633 .await;
1634 Ok(session_id)
1635 }
1636
1637 pub async fn create_session_with_request(&self, req: SessionCreateRequest) -> Result<String> {
1657 self.create_session(
1658 req.get_user_id(),
1659 req.get_expires_in(),
1660 req.get_ip_address().map(|s| s.to_string()),
1661 req.get_user_agent().map(|s| s.to_string()),
1662 )
1663 .await
1664 }
1665
1666 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
1668 self.require_initialized()?;
1669 self.session_manager.get_session(session_id).await
1670 }
1671
1672 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
1674 self.require_initialized()?;
1675 self.session_manager.delete_session(session_id).await?;
1676
1677 let remaining = self
1678 .session_manager
1679 .count_active_sessions()
1680 .await
1681 .unwrap_or(0);
1682 self.monitoring_manager
1683 .update_session_count(remaining)
1684 .await;
1685
1686 Ok(())
1687 }
1688
1689 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
1691 self.require_initialized()?;
1692 self.storage.list_user_tokens(user_id).await
1693 }
1694
1695 pub async fn cleanup_expired_data(&self) -> Result<()> {
1697 debug!("Cleaning up expired data");
1698
1699 self.storage.cleanup_expired().await?;
1701
1702 self.mfa_manager.cleanup_expired_challenges().await?;
1704
1705 self.session_manager.cleanup_expired_sessions().await?;
1707
1708 if let Some(ref rate_limiter) = self.rate_limiter {
1710 let _ = rate_limiter.cleanup().ok();
1711 }
1712
1713 Ok(())
1714 }
1715
1716 fn is_production_environment() -> bool {
1719 if let Ok(env) = std::env::var("ENVIRONMENT")
1720 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1721 {
1722 return true;
1723 }
1724 if let Ok(env) = std::env::var("ENV")
1725 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
1726 {
1727 return true;
1728 }
1729 if let Ok(env) = std::env::var("NODE_ENV")
1730 && env.to_lowercase() == "production"
1731 {
1732 return true;
1733 }
1734 if let Ok(env) = std::env::var("RUST_ENV")
1735 && env.to_lowercase() == "production"
1736 {
1737 return true;
1738 }
1739 std::env::var("KUBERNETES_SERVICE_HOST").is_ok()
1740 || std::env::var("DOCKER_CONTAINER").is_ok()
1741 }
1742
1743 pub async fn get_stats(&self) -> Result<AuthStats> {
1745 let mut stats = AuthStats::default();
1746
1747 if let Err(e) = self.storage.cleanup_expired().await {
1748 warn!("Failed to cleanup expired data: {}", e);
1749 }
1750 if let Some(rate_limiter) = &self.rate_limiter {
1751 let _ = rate_limiter.cleanup().ok();
1752 }
1753
1754 let active_sessions = self
1755 .session_manager
1756 .count_active_sessions()
1757 .await
1758 .unwrap_or(0) as u32;
1759
1760 stats.registered_methods = self.methods.keys().cloned().collect();
1761 stats.active_sessions = active_sessions as u64;
1762 stats.active_mfa_challenges = self.mfa_manager.get_active_challenge_count().await as u64;
1763 let perf = self.monitoring_manager.get_performance_metrics();
1765 stats.tokens_issued = perf.get("token_creations").copied().unwrap_or(0);
1766 stats.auth_attempts = perf.get("auth_successes").copied().unwrap_or(0)
1767 + perf.get("auth_failures").copied().unwrap_or(0);
1768
1769 Ok(stats)
1770 }
1771
1772 pub fn token_manager(&self) -> &TokenManager {
1777 &self.token_manager
1778 }
1779
1780 pub async fn redeem_refresh_jwt(&self, token: &str) -> Result<RefreshRedemption> {
1787 let claims = self.token_manager.validate_jwt_token(token)?;
1788 if !claims.is_refresh_token() {
1789 return Err(rejected("Expected a refresh token"));
1790 }
1791 let read = |key: String| async move {
1792 self.storage.get_kv(&key).await.map_err(|e| {
1793 tracing::error!("Could not read refresh-token state: {}", e);
1794 rejected("Unable to verify token status")
1795 })
1796 };
1797 let family = claims.refresh_family().to_string();
1798 if read(format!("revoked_token:{}", claims.jti))
1799 .await?
1800 .is_some()
1801 || read(format!("revoked_family:{family}")).await?.is_some()
1802 {
1803 return Err(rejected("Refresh token has been revoked"));
1804 }
1805 ensure_account_active(self.storage.as_ref(), &claims.sub, true).await?;
1806
1807 let remaining =
1808 Duration::from_secs((claims.exp - chrono::Utc::now().timestamp()).max(60) as u64);
1809 let family_ttl = self.config.refresh_token_lifetime + Duration::from_secs(60);
1811 let consumed_key = format!("refresh_consumed:{}", claims.jti);
1812 let first_use = self
1818 .storage
1819 .store_kv_if_absent(&consumed_key, b"used", Some(remaining))
1820 .await
1821 .map_err(|e| {
1822 tracing::error!("Could not record refresh token use: {}", e);
1823 rejected("Unable to record refresh token use")
1824 })?;
1825 if !first_use {
1826 warn!(
1827 "Refresh token reuse detected for user '{}'; revoking its chain",
1828 claims.sub
1829 );
1830 if let Err(e) = self
1831 .storage
1832 .store_kv(
1833 &format!("revoked_family:{family}"),
1834 b"reuse",
1835 Some(family_ttl),
1836 )
1837 .await
1838 {
1839 tracing::error!("Could not revoke refresh chain after reuse: {}", e);
1840 }
1841 return Err(rejected("Refresh token has already been used"));
1842 }
1843
1844 let lifetime = self.config.refresh_token_lifetime;
1845 let new_refresh_token = self.token_manager.create_refresh_jwt_token_in_family(
1846 &claims.sub,
1847 Some(lifetime),
1848 &family,
1849 )?;
1850 Ok(RefreshRedemption {
1851 claims,
1852 new_refresh_token,
1853 })
1854 }
1855
1856 pub async fn validate_access_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1863 validate_access_jwt_with(
1864 &self.token_manager,
1865 self.storage.as_ref(),
1866 token,
1867 true,
1868 false,
1869 )
1870 .await
1871 }
1872
1873 pub async fn validate_delegated_jwt(&self, token: &str) -> Result<crate::tokens::JwtClaims> {
1879 validate_access_jwt_with(
1880 &self.token_manager,
1881 self.storage.as_ref(),
1882 token,
1883 true,
1884 true,
1885 )
1886 .await
1887 }
1888
1889 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1899 self.user_manager.validate_username(username).await
1900 }
1901
1902 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1909 self.user_manager.validate_display_name(display_name).await
1910 }
1911
1912 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1921 self.user_manager.validate_password_strength(password).await
1922 }
1923
1924 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1929 Ok(crate::utils::validation::validate_user_input(input))
1930 }
1931
1932 pub async fn create_auth_token(
1952 &self,
1953 user_id: impl Into<String>,
1954 scopes: impl Into<crate::types::Scopes>,
1955 method_name: impl Into<String>,
1956 lifetime: Option<Duration>,
1957 ) -> Result<AuthToken> {
1958 let method_name = method_name.into();
1959 let user_id = user_id.into();
1960 let scopes: crate::types::Scopes = scopes.into();
1961
1962 let auth_method = self
1964 .methods
1965 .get(&method_name)
1966 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1967 auth_method.validate_config()?;
1968
1969 const MAX_TOKENS_PER_USER: usize = 100;
1971 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1972 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1973 warn!(
1974 "User '{}' has reached maximum tokens ({})",
1975 user_id, MAX_TOKENS_PER_USER
1976 );
1977 return Err(AuthError::rate_limit(
1978 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1979 ));
1980 }
1981
1982 let token = self
1983 .mint_and_store_token(&user_id, scopes, &method_name, lifetime)
1984 .await?;
1985 self.monitoring_manager
1986 .record_token_creation(&method_name)
1987 .await;
1988 Ok(token)
1989 }
1990
1991 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
2001 self.mfa_manager.sms.initiate_challenge(user_id).await
2002 }
2003
2004 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
2012 self.mfa_manager.sms.verify_code(challenge_id, code).await
2013 }
2014
2015 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
2022 self.mfa_manager.email.register_email(user_id, email).await
2023 }
2024
2025 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
2036 self.mfa_manager.totp.generate_secret(user_id).await
2037 }
2038
2039 pub async fn generate_totp_qr_code(
2047 &self,
2048 user_id: &str,
2049 app_name: &str,
2050 secret: &str,
2051 ) -> Result<String> {
2052 self.mfa_manager
2053 .totp
2054 .generate_qr_code(user_id, app_name, secret)
2055 .await
2056 }
2057
2058 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
2063 self.mfa_manager.totp.generate_code(secret).await
2064 }
2065
2066 pub async fn generate_totp_code_for_window(
2070 &self,
2071 secret: &str,
2072 time_window: Option<u64>,
2073 ) -> Result<String> {
2074 self.mfa_manager
2075 .totp
2076 .generate_code_for_window(secret, time_window)
2077 .await
2078 }
2079
2080 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
2088 self.mfa_manager.totp.verify_code(user_id, code).await
2089 }
2090
2091 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
2096 debug!("Checking IP rate limit for '{}'", ip);
2097 let Some(ref rate_limiter) = self.rate_limiter else {
2098 return Ok(true);
2099 };
2100 if !rate_limiter.is_allowed(&format!("ip:{}", ip)) {
2101 warn!("Rate limit exceeded for IP: {}", ip);
2102 return Err(AuthError::rate_limit(format!(
2103 "Too many requests from IP {}. Please try again later.",
2104 ip
2105 )));
2106 }
2107 Ok(true)
2108 }
2109
2110 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
2115 debug!("Getting security metrics");
2116 let mut metrics = std::collections::HashMap::new();
2117 let total_active_sessions = self
2118 .session_manager
2119 .count_active_sessions()
2120 .await
2121 .unwrap_or(0);
2122 metrics.insert("active_sessions".to_string(), total_active_sessions);
2123 metrics.insert("total_tokens".to_string(), total_active_sessions);
2124 metrics.insert(
2125 "failed_attempts".to_string(),
2126 self.audit_manager
2127 .get_failed_login_count_24h()
2128 .await
2129 .unwrap_or(0),
2130 );
2131 metrics.insert(
2132 "successful_attempts".to_string(),
2133 self.audit_manager
2134 .get_successful_login_count_24h()
2135 .await
2136 .unwrap_or(0),
2137 );
2138 metrics.insert("expired_tokens".to_string(), 0u64);
2139 Ok(metrics)
2140 }
2141
2142 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
2148 self.mfa_manager
2149 .sms
2150 .register_phone_number(user_id, phone_number)
2151 .await
2152 }
2153
2154 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
2159 self.mfa_manager
2160 .backup_codes
2161 .generate_codes(user_id, count)
2162 .await
2163 }
2164 pub async fn grant_permission(
2176 &self,
2177 user_id: &str,
2178 action: &str,
2179 resource: &str,
2180 ) -> Result<()> {
2181 self.authorization_manager
2182 .grant_permission(user_id, action, resource)
2183 .await
2184 }
2185
2186 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
2196 self.mfa_manager.email.initiate_challenge(user_id).await
2197 }
2198
2199 pub fn storage(&self) -> Arc<dyn AuthStorage> {
2204 self.storage.clone()
2205 }
2206
2207 pub fn config(&self) -> &AuthConfig {
2209 &self.config
2210 }
2211
2212 pub async fn reset_authorization_runtime(&self) {
2214 self.authorization_manager.reset_runtime_state().await;
2215 }
2216
2217 pub async fn register_user(
2240 &self,
2241 username: &str,
2242 email: &str,
2243 password: &str,
2244 ) -> Result<String> {
2245 self.require_initialized()?;
2246 self.user_manager
2247 .register_user(username, email, password)
2248 .await
2249 }
2250
2251 #[deprecated(
2278 since = "0.6.0",
2279 note = "use `list_users_with_query(UserListQuery::new().limit(n).active_only())` instead"
2280 )]
2281 pub async fn list_users(
2282 &self,
2283 limit: Option<usize>,
2284 offset: Option<usize>,
2285 active_only: bool,
2286 ) -> Result<Vec<UserInfo>> {
2287 self.require_initialized()?;
2288 self.user_manager
2289 .list_users(limit, offset, active_only)
2290 .await
2291 }
2292
2293 pub async fn list_users_with_query(&self, query: UserListQuery) -> Result<Vec<UserInfo>> {
2312 self.require_initialized()?;
2313 self.user_manager
2314 .list_users(
2315 query.get_limit(),
2316 query.get_offset(),
2317 query.get_active_only(),
2318 )
2319 .await
2320 }
2321
2322 pub async fn get_user_record(&self, user_id: &str) -> Result<UserInfo> {
2324 self.require_initialized()?;
2325 self.user_manager.get_user_info(user_id).await
2326 }
2327
2328 pub async fn update_user_roles(&self, user_id: &str, roles: &[String]) -> Result<()> {
2330 self.require_initialized()?;
2331 self.user_manager.update_user_roles(user_id, roles).await
2332 }
2333
2334 pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()> {
2336 self.require_initialized()?;
2337 self.user_manager.set_user_active(user_id, active).await
2338 }
2339
2340 pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()> {
2342 self.require_initialized()?;
2343 self.user_manager.update_user_email(user_id, email).await
2344 }
2345
2346 pub async fn verify_user_password(&self, user_id: &str, password: &str) -> Result<bool> {
2348 self.require_initialized()?;
2349 self.user_manager
2350 .verify_user_password(user_id, password)
2351 .await
2352 }
2353
2354 pub async fn get_username_by_id(&self, user_id: &str) -> Result<String> {
2356 self.user_manager.get_username_by_id(user_id).await
2357 }
2358
2359 pub async fn username_exists(&self, username: &str) -> Result<bool> {
2361 self.user_manager.username_exists(username).await
2362 }
2363
2364 pub async fn email_exists(&self, email: &str) -> Result<bool> {
2366 self.user_manager.email_exists(email).await
2367 }
2368
2369 pub async fn get_user_by_username(
2371 &self,
2372 username: &str,
2373 ) -> Result<HashMap<String, serde_json::Value>> {
2374 self.user_manager.get_user_by_username(username).await
2375 }
2376
2377 pub async fn update_user_password(&self, username: &str, new_password: &str) -> Result<()> {
2379 self.require_initialized()?;
2380 self.user_manager
2381 .update_user_password(username, new_password)
2382 .await
2383 }
2384
2385 pub async fn update_user_password_by_id(
2387 &self,
2388 user_id: &str,
2389 new_password: &str,
2390 ) -> Result<()> {
2391 self.require_initialized()?;
2392 self.user_manager
2393 .update_user_password_by_id(user_id, new_password)
2394 .await
2395 }
2396
2397 pub async fn delete_user(&self, username: &str) -> Result<()> {
2399 self.require_initialized()?;
2400 self.user_manager.delete_user(username).await
2401 }
2402
2403 pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()> {
2405 self.require_initialized()?;
2406 self.user_manager.delete_user_by_id(user_id).await
2407 }
2408
2409 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
2411 self.mfa_manager
2412 .verify_challenge_code(challenge, code)
2413 .await
2414 }
2415
2416 async fn log_audit_event(
2418 &self,
2419 event_type: &str,
2420 user_id: &str,
2421 method: &str,
2422 metadata: &CredentialMetadata,
2423 ) {
2424 if !self.config.audit.enabled {
2425 return;
2426 }
2427 let should_log = match event_type {
2428 "auth_success" | "mfa_required" => self.config.audit.log_success,
2429 "auth_failure" => self.config.audit.log_failures,
2430 _ => true,
2431 };
2432 if should_log {
2433 self.audit_manager
2434 .log_auth_trace_event(
2435 event_type,
2436 user_id,
2437 method,
2438 metadata.client_ip.as_deref().unwrap_or("unknown"),
2439 metadata.user_agent.as_deref().unwrap_or("unknown"),
2440 )
2441 .await;
2442 }
2443 }
2444
2445 async fn guard_and_store_mfa_challenge(&self, challenge: MfaChallenge) -> Result<()> {
2447 self.mfa_manager.guard_and_store(challenge).await
2448 }
2449
2450 async fn mint_and_store_token(
2452 &self,
2453 user_id: &str,
2454 scopes: impl Into<crate::types::Scopes>,
2455 method: &str,
2456 lifetime: Option<Duration>,
2457 ) -> Result<AuthToken> {
2458 let token = self
2459 .token_manager
2460 .create_auth_token(user_id, scopes, method, lifetime)?;
2461 self.storage.store_token(&token).await?;
2462 Ok(token)
2463 }
2464
2465 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2467 self.session_manager.coordinate_distributed_sessions().await
2468 }
2469
2470 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2472 self.session_manager.synchronize_session(session_id).await
2473 }
2474
2475 pub fn monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2477 self.monitoring_manager.clone()
2478 }
2479
2480 #[cfg(feature = "api-server")]
2482 pub fn security_manager(&self) -> Option<Arc<crate::api::SecurityManager>> {
2483 Some(self.security_manager.clone())
2484 }
2485
2486 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2488 self.monitoring_manager.get_performance_metrics()
2489 }
2490
2491 pub async fn health_check(
2493 &self,
2494 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2495 self.monitoring_manager.health_check().await
2496 }
2497
2498 pub async fn export_prometheus_metrics(&self) -> String {
2500 self.monitoring_manager.export_prometheus_metrics().await
2501 }
2502 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2504 self.require_initialized()?;
2505 self.authorization_manager.create_role(role).await
2506 }
2507
2508 pub async fn list_roles(&self) -> Vec<crate::permissions::Role> {
2510 self.authorization_manager.list_roles().await
2511 }
2512
2513 pub async fn get_role(&self, role_name: &str) -> Result<crate::permissions::Role> {
2515 self.authorization_manager.get_role(role_name).await
2516 }
2517
2518 pub async fn add_role_permission(
2520 &self,
2521 role_name: &str,
2522 permission: crate::permissions::Permission,
2523 ) -> Result<()> {
2524 self.authorization_manager
2525 .add_role_permission(role_name, permission)
2526 .await
2527 }
2528
2529 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2531 self.require_initialized()?;
2532 self.authorization_manager
2533 .assign_role(user_id, role_name)
2534 .await
2535 }
2536
2537 pub async fn remove_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2539 self.require_initialized()?;
2540 self.authorization_manager
2541 .remove_role(user_id, role_name)
2542 .await
2543 }
2544
2545 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2547 self.require_initialized()?;
2548 self.authorization_manager
2549 .set_role_inheritance(child_role, parent_role)
2550 .await
2551 }
2552
2553 pub async fn revoke_permission(
2555 &self,
2556 user_id: &str,
2557 action: &str,
2558 resource: &str,
2559 ) -> Result<()> {
2560 self.require_initialized()?;
2561 self.authorization_manager
2562 .revoke_permission(user_id, action, resource)
2563 .await
2564 }
2565
2566 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2568 self.authorization_manager
2569 .user_has_role(user_id, role_name)
2570 .await
2571 }
2572
2573 pub async fn list_user_roles(&self, user_id: &str) -> Result<Vec<String>> {
2575 self.authorization_manager.list_user_roles(user_id).await
2576 }
2577
2578 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2580 self.authorization_manager
2581 .get_effective_permissions(user_id)
2582 .await
2583 }
2584
2585 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2587 self.authorization_manager
2588 .create_abac_policy(name, description)
2589 .await
2590 }
2591
2592 pub async fn map_user_attribute(
2613 &self,
2614 user_id: &str,
2615 attribute: &str,
2616 value: &str,
2617 ) -> Result<()> {
2618 self.authorization_manager
2619 .map_user_attribute(user_id, attribute, value)
2620 .await
2621 }
2622
2623 pub async fn get_user_attribute(
2647 &self,
2648 user_id: &str,
2649 attribute: &str,
2650 ) -> Result<Option<String>> {
2651 self.authorization_manager
2652 .get_user_attribute(user_id, attribute)
2653 .await
2654 }
2655
2656 pub async fn check_dynamic_permission(
2687 &self,
2688 user_id: &str,
2689 action: &str,
2690 resource: &str,
2691 context: std::collections::HashMap<String, String>,
2692 ) -> Result<bool> {
2693 self.authorization_manager
2694 .check_dynamic_permission(user_id, action, resource, context)
2695 .await
2696 }
2697
2698 pub async fn check_dynamic_permission_with_context(
2718 &self,
2719 user_id: &str,
2720 action: &str,
2721 resource: &str,
2722 context: PermissionContext,
2723 ) -> Result<bool> {
2724 self.check_dynamic_permission(user_id, action, resource, context.into_attributes())
2725 .await
2726 }
2727
2728 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2730 self.authorization_manager.create_resource(resource).await
2731 }
2732
2733 pub async fn delegate_permission_with_request(&self, req: DelegationRequest) -> Result<()> {
2752 self.authorization_manager
2753 .delegate_permission(
2754 req.delegator_id(),
2755 req.delegatee_id(),
2756 req.action(),
2757 req.resource(),
2758 req.get_duration(),
2759 )
2760 .await
2761 }
2762
2763 pub async fn delegate_permission(
2768 &self,
2769 delegator_id: &str,
2770 delegatee_id: &str,
2771 action: &str,
2772 resource: &str,
2773 duration: std::time::Duration,
2774 ) -> Result<()> {
2775 self.authorization_manager
2776 .delegate_permission(delegator_id, delegatee_id, action, resource, duration)
2777 .await
2778 }
2779
2780 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2782 self.authorization_manager
2783 .get_active_delegations(user_id)
2784 .await
2785 }
2786
2787 pub async fn get_permission_audit_logs(
2789 &self,
2790 user_id: Option<&str>,
2791 action: Option<&str>,
2792 resource: Option<&str>,
2793 limit: Option<usize>,
2794 ) -> Result<Vec<String>> {
2795 self.audit_manager
2796 .get_permission_audit_logs(user_id, action, resource, limit)
2797 .await
2798 }
2799
2800 pub async fn get_permission_audit_logs_with_query(
2820 &self,
2821 query: AuditLogQuery,
2822 ) -> Result<Vec<String>> {
2823 self.audit_manager
2824 .get_permission_audit_logs(
2825 query.get_user_id(),
2826 query.get_action(),
2827 query.get_resource(),
2828 query.get_limit(),
2829 )
2830 .await
2831 }
2832
2833 pub async fn get_permission_metrics(
2835 &self,
2836 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2837 let active_sessions = self.storage.count_active_sessions().await.unwrap_or(0);
2838 let permission_checks_last_hour = self
2839 .audit_manager
2840 .get_permission_checks_last_hour()
2841 .await
2842 .unwrap_or(0);
2843 self.authorization_manager
2844 .get_permission_metrics(active_sessions, permission_checks_last_hour)
2845 .await
2846 }
2847
2848 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2850 let active_sessions = self
2851 .session_manager
2852 .count_active_sessions()
2853 .await
2854 .unwrap_or(0);
2855 self.audit_manager
2856 .get_security_audit_stats(active_sessions)
2857 .await
2858 }
2859
2860 pub async fn get_user_profile(
2862 &self,
2863 user_id: &str,
2864 ) -> Result<crate::providers::ProviderProfile> {
2865 self.user_manager.get_user_profile(user_id).await
2866 }
2867}
2868
2869pub use crate::audit::SecurityAuditStats;
2870
2871pub use crate::auth_modular::session_manager::SessionCoordinationStats;
2872
2873#[derive(Debug, Clone, Default)]
2875pub struct AuthStats {
2876 pub registered_methods: Vec<String>,
2878
2879 pub active_sessions: u64,
2881
2882 pub active_mfa_challenges: u64,
2884
2885 pub tokens_issued: u64,
2887
2888 pub auth_attempts: u64,
2890}
2891
2892#[cfg(test)]
2893mod tests {
2894 use super::*;
2895 use crate::config::{AuthConfig, SecurityConfig};
2896 #[tokio::test]
2897 async fn test_framework_initialization() {
2898 let config = AuthConfig::new().security(SecurityConfig {
2899 min_password_length: 8,
2900 require_password_complexity: false,
2901 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2902 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2903 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2904 secure_cookies: false,
2905 cookie_same_site: crate::config::CookieSameSite::Lax,
2906 csrf_protection: false,
2907 session_timeout: Duration::from_secs(3600),
2908 previous_secret_key: None,
2909 });
2910 let mut framework = AuthFramework::new(config);
2911
2912 assert!(framework.initialize().await.is_ok());
2913 assert!(framework.initialized);
2914 }
2915
2916 #[tokio::test]
2917 async fn test_method_registration() {
2918 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 framework = AuthFramework::new(config);
2935
2936 assert!(!framework.initialized);
2938
2939 }
2942
2943 #[tokio::test]
2944 async fn test_token_validation() {
2945 let config = AuthConfig::new().security(SecurityConfig {
2946 min_password_length: 8,
2947 require_password_complexity: false,
2948 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2949 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2950 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2951 secure_cookies: false,
2952 cookie_same_site: crate::config::CookieSameSite::Lax,
2953 csrf_protection: false,
2954 session_timeout: Duration::from_secs(3600),
2955 previous_secret_key: None,
2956 });
2957 let mut framework = AuthFramework::new(config);
2958 framework.initialize().await.unwrap();
2959
2960 let token = framework
2961 .token_manager
2962 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
2963 .unwrap();
2964
2965 framework.storage.store_token(&token).await.unwrap();
2967
2968 assert!(framework.validate_token(&token).await.unwrap());
2969 }
2970
2971 #[tokio::test]
2972 async fn test_session_management() {
2973 let config = AuthConfig::new().security(SecurityConfig {
2974 min_password_length: 8,
2975 require_password_complexity: false,
2976 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
2977 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
2978 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
2979 secure_cookies: false,
2980 cookie_same_site: crate::config::CookieSameSite::Lax,
2981 csrf_protection: false,
2982 session_timeout: Duration::from_secs(3600),
2983 previous_secret_key: None,
2984 });
2985 let mut framework = AuthFramework::new(config);
2986 framework.initialize().await.unwrap();
2987
2988 let session_id = framework
2989 .create_session(
2990 "test-user",
2991 Duration::from_secs(3600),
2992 Some("192.168.1.1".to_string()),
2993 Some("Test Agent".to_string()),
2994 )
2995 .await
2996 .unwrap();
2997
2998 let session = framework.get_session(&session_id).await.unwrap();
2999 assert!(session.is_some());
3000
3001 framework.delete_session(&session_id).await.unwrap();
3002 let session = framework.get_session(&session_id).await.unwrap();
3003 assert!(session.is_none());
3004 }
3005
3006 #[tokio::test]
3007 async fn test_grouped_operations_accessors() {
3008 let config = AuthConfig::new().security(SecurityConfig {
3009 min_password_length: 8,
3010 require_password_complexity: false,
3011 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3012 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3013 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3014 secure_cookies: false,
3015 cookie_same_site: crate::config::CookieSameSite::Lax,
3016 csrf_protection: false,
3017 session_timeout: Duration::from_secs(3600),
3018 previous_secret_key: None,
3019 });
3020 let mut framework = AuthFramework::new(config);
3021 framework.initialize().await.unwrap();
3022
3023 let user_id = framework
3024 .users()
3025 .register("grouped-user", "grouped-user@example.com", "P@ssw0rd123")
3026 .await
3027 .unwrap();
3028 assert!(
3029 framework
3030 .users()
3031 .exists_by_username("grouped-user")
3032 .await
3033 .unwrap()
3034 );
3035
3036 let session_id = framework
3037 .sessions()
3038 .create(&user_id, Duration::from_secs(300), None, None)
3039 .await
3040 .unwrap();
3041 assert!(
3042 framework
3043 .sessions()
3044 .get(&session_id)
3045 .await
3046 .unwrap()
3047 .is_some()
3048 );
3049 assert_eq!(
3050 framework
3051 .sessions()
3052 .list_for_user(&user_id)
3053 .await
3054 .unwrap()
3055 .len(),
3056 1
3057 );
3058
3059 framework
3060 .authorization()
3061 .grant(&user_id, "read", "documents")
3062 .await
3063 .unwrap();
3064 let permissions = framework
3065 .authorization()
3066 .effective_permissions(&user_id)
3067 .await
3068 .unwrap();
3069 assert!(
3070 permissions
3071 .iter()
3072 .any(|permission| permission == "read:documents")
3073 );
3074
3075 framework.sessions().delete(&session_id).await.unwrap();
3076 assert!(
3077 framework
3078 .sessions()
3079 .get(&session_id)
3080 .await
3081 .unwrap()
3082 .is_none()
3083 );
3084 }
3085
3086 #[tokio::test]
3087 async fn test_cleanup_expired_data() {
3088 let config = AuthConfig::new().security(SecurityConfig {
3089 min_password_length: 8,
3090 require_password_complexity: false,
3091 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3092 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3093 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string().into()),
3094 secure_cookies: false,
3095 cookie_same_site: crate::config::CookieSameSite::Lax,
3096 csrf_protection: false,
3097 session_timeout: Duration::from_secs(3600),
3098 previous_secret_key: None,
3099 });
3100 let mut framework = AuthFramework::new(config);
3101 framework.initialize().await.unwrap();
3102
3103 assert!(framework.cleanup_expired_data().await.is_ok());
3105 }
3106
3107 #[cfg(feature = "redis-storage")]
3115 #[test]
3116 fn new_validated_redis_fails_closed_without_an_encryption_key() {
3117 let _lock = crate::storage::encryption::TEST_ENCRYPTION_ENV_LOCK.blocking_lock();
3118 unsafe {
3121 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEY");
3122 std::env::remove_var("AUTH_STORAGE_ENCRYPTION_KEYS_FILE");
3123 }
3124
3125 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3126 config.storage = crate::config::StorageConfig::Redis {
3127 url: "redis://127.0.0.1:1/".to_string(),
3128 key_prefix: "test:".to_string(),
3129 };
3130 let result = AuthFramework::new_validated(config);
3133 assert!(
3134 result.is_err(),
3135 "constructing with Redis storage and no encryption key configured must fail \
3136 closed, not silently build unwrapped (unencrypted) storage"
3137 );
3138 }
3139
3140 #[tokio::test]
3141 async fn initialize_refuses_unwrapped_custom_storage_when_wrapping_is_required() {
3142 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3143 config.storage_encryption.require_wrapped_storage = true;
3144 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3145 assert!(
3146 framework.initialize().await.is_err(),
3147 "caller-supplied unwrapped storage must be refused when wrapping is required"
3148 );
3149 }
3150
3151 #[tokio::test]
3152 async fn initialize_accepts_wrapped_or_unrequired_custom_storage() {
3153 let mut required = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3154 required.storage_encryption.require_wrapped_storage = true;
3155 let wrapped: Arc<dyn AuthStorage> =
3156 Arc::new(crate::storage::encryption::EncryptedStorage::new(
3157 MemoryStorage::new(),
3158 crate::storage::encryption::StorageEncryption::new_random(),
3159 false,
3160 false,
3161 ));
3162 let mut framework = AuthFramework::new_with_storage(required, wrapped);
3163 framework.initialize().await.unwrap();
3164
3165 let config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3167 let mut framework = AuthFramework::new_with_storage(config, Arc::new(MemoryStorage::new()));
3168 framework.initialize().await.unwrap();
3169 }
3170
3171 #[tokio::test]
3172 async fn factory_built_storage_is_not_treated_as_caller_supplied() {
3173 let mut config = AuthConfig::new().secret("test_secret_key_32_bytes_long!!!!");
3174 config.storage_encryption.require_wrapped_storage = true;
3175 let mut framework = AuthFramework::new(config);
3176 framework.replace_storage_from_factory(Arc::new(MemoryStorage::new()));
3178 framework.initialize().await.unwrap();
3179 }
3180}