1use crate::authentication::credentials::{Credential, CredentialMetadata};
4use crate::config::AuthConfig;
5use crate::errors::{AuthError, MfaError, Result};
6use crate::methods::{AuthMethod, AuthMethodEnum, MethodResult, MfaChallenge};
7use crate::permissions::{Permission, PermissionChecker};
8use crate::storage::{AuthStorage, MemoryStorage, SessionData};
9use crate::tokens::{AuthToken, TokenManager};
10use crate::utils::rate_limit::RateLimiter;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::sync::Arc;
14use std::time::Duration;
15use tokio::sync::RwLock;
16use tracing::{debug, error, info, warn};
17
18#[derive(Debug, Clone)]
20pub enum AuthResult {
21 Success(Box<AuthToken>),
23
24 MfaRequired(Box<MfaChallenge>),
26
27 Failure(String),
29}
30
31#[derive(Debug, Clone)]
33pub struct UserInfo {
34 pub id: String,
36
37 pub username: String,
39
40 pub email: Option<String>,
42
43 pub name: Option<String>,
45
46 pub roles: Vec<String>,
48
49 pub active: bool,
51
52 pub attributes: HashMap<String, serde_json::Value>,
54}
55
56pub struct AuthFramework {
113 config: AuthConfig,
115
116 methods: HashMap<String, AuthMethodEnum>,
118
119 token_manager: TokenManager,
121
122 storage: Arc<dyn AuthStorage>,
124
125 permission_checker: Arc<RwLock<PermissionChecker>>,
127
128 rate_limiter: Option<RateLimiter>,
130
131 mfa_challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
133
134 sessions: Arc<RwLock<HashMap<String, SessionData>>>,
136
137 monitoring_manager: Arc<crate::monitoring::MonitoringManager>,
139
140 audit_manager: Arc<crate::audit::AuditLogger<Arc<crate::storage::MemoryStorage>>>,
142
143 initialized: bool,
145}
146
147impl AuthFramework {
148 fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
152 if a.len() != b.len() {
153 return false;
154 }
155
156 let mut result = 0u8;
157 for (byte_a, byte_b) in a.iter().zip(b.iter()) {
158 result |= byte_a ^ byte_b;
159 }
160 result == 0
161 }
162
163 pub fn new(config: AuthConfig) -> Self {
169 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
171 let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
172 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
173
174 let default_secret = b"temporary_development_secret_replace_in_init";
176 let token_manager =
177 TokenManager::new_hmac(default_secret, "auth-framework", "auth-framework");
178
179 Self {
180 config,
181 methods: HashMap::new(),
182 token_manager,
183 storage,
184 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
185 rate_limiter: None, mfa_challenges: Arc::new(RwLock::new(HashMap::new())),
187 sessions: Arc::new(RwLock::new(HashMap::new())),
188 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
189 crate::monitoring::MonitoringConfig::default(),
190 )),
191 audit_manager,
192 initialized: false,
193 }
194 }
195
196 pub fn new_validated(config: AuthConfig) -> Result<Self> {
201 config.validate().map_err(|e| {
203 AuthError::configuration(format!("Configuration validation failed: {}", e))
204 })?;
205
206 let token_manager = if let Some(secret) = &config.security.secret_key {
208 if secret.len() < 32 {
209 return Err(AuthError::configuration(
210 "JWT secret must be at least 32 characters for production security",
211 ));
212 }
213 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
214 } else if let Some(secret) = &config.secret {
215 if secret.len() < 32 {
216 return Err(AuthError::configuration(
217 "JWT secret must be at least 32 characters for production security",
218 ));
219 }
220 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
221 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
222 if jwt_secret.len() < 32 {
223 return Err(AuthError::configuration(
224 "JWT_SECRET must be at least 32 characters for production security",
225 ));
226 }
227 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
228 } else {
229 return Err(AuthError::configuration(
230 "JWT secret not configured! Please set JWT_SECRET environment variable or provide in configuration.\n\
231 For security reasons, no default secret is provided.\n\
232 Generate a secure secret with: openssl rand -base64 32",
233 ));
234 };
235
236 let storage: Arc<dyn AuthStorage> = match &config.storage {
238 #[cfg(feature = "redis-storage")]
239 crate::config::StorageConfig::Redis { url, key_prefix } => Arc::new(
240 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
241 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
242 })?,
243 ),
244 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
245 };
246
247 let rate_limiter = if config.rate_limiting.enabled {
249 Some(RateLimiter::new(
250 config.rate_limiting.max_requests,
251 config.rate_limiting.window,
252 ))
253 } else {
254 None
255 };
256
257 let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
259 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
260
261 Ok(Self {
262 config,
263 methods: HashMap::new(),
264 token_manager,
265 storage,
266 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
267 rate_limiter,
268 mfa_challenges: Arc::new(RwLock::new(HashMap::new())),
269 sessions: Arc::new(RwLock::new(HashMap::new())),
270 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
271 crate::monitoring::MonitoringConfig::default(),
272 )),
273 audit_manager,
274 initialized: false,
275 })
276 }
277
278 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
280 let name = name.into();
281 info!("Registering authentication method: {}", name);
282
283 if let Err(e) = method.validate_config() {
285 error!("Method '{}' configuration validation failed: {}", name, e);
286 return;
287 }
288
289 self.methods.insert(name, method);
290 }
291
292 pub async fn initialize(&mut self) -> Result<()> {
302 if self.initialized {
303 return Ok(());
304 }
305
306 info!("Initializing authentication framework");
307
308 self.config.validate().map_err(|e| {
310 AuthError::configuration(format!("Configuration validation failed: {}", e))
311 })?;
312
313 let token_manager = if let Some(secret) = &self.config.security.secret_key {
315 if secret.len() < 32 {
316 return Err(AuthError::configuration(
317 "JWT secret must be at least 32 characters for production security",
318 ));
319 }
320 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
321 } else if let Some(secret) = &self.config.secret {
322 if secret.len() < 32 {
323 return Err(AuthError::configuration(
324 "JWT secret must be at least 32 characters for production security",
325 ));
326 }
327 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
328 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
329 if jwt_secret.len() < 32 {
330 return Err(AuthError::configuration(
331 "JWT_SECRET must be at least 32 characters for production security",
332 ));
333 }
334 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
335 } else {
336 if self.is_production_environment() {
338 return Err(AuthError::configuration(
339 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
340 Generate a secure secret with: openssl rand -base64 32\n\
341 Set it with: export JWT_SECRET=\"your-secret-here\"",
342 ));
343 }
344
345 warn!("No JWT secret configured, using development-only default");
346 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
347 warn!("This configuration is NOT SECURE and should only be used in development!");
348
349 self.token_manager.clone()
351 };
352
353 self.token_manager = token_manager;
355
356 match &self.config.storage {
358 #[cfg(feature = "redis-storage")]
359 crate::config::StorageConfig::Redis { url, key_prefix } => {
360 let redis_storage =
361 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
362 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
363 })?;
364 self.storage = Arc::new(redis_storage);
365 }
366 _ => {
367 }
369 }
370
371 if self.config.rate_limiting.enabled {
373 self.rate_limiter = Some(RateLimiter::new(
374 self.config.rate_limiting.max_requests,
375 self.config.rate_limiting.window,
376 ));
377 }
378
379 {
381 let mut checker = self.permission_checker.write().await;
382 checker.create_default_roles();
383 }
384
385 self.cleanup_expired_data().await?;
387
388 self.initialized = true;
389 info!("Authentication framework initialized successfully");
390
391 Ok(())
392 }
393
394 pub async fn authenticate(
396 &self,
397 method_name: &str,
398 credential: Credential,
399 ) -> Result<AuthResult> {
400 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
401 .await
402 }
403
404 pub async fn authenticate_with_metadata(
406 &self,
407 method_name: &str,
408 credential: Credential,
409 metadata: CredentialMetadata,
410 ) -> Result<AuthResult> {
411 use std::time::Instant;
412 use tokio::time::{Duration as TokioDuration, sleep};
413
414 let start_time = Instant::now();
415
416 self.monitoring_manager.record_auth_request().await;
418
419 if !self.initialized {
420 return Err(AuthError::internal("Framework not initialized"));
421 }
422
423 let result = self
425 .authenticate_internal(method_name, credential, metadata)
426 .await;
427
428 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
431 if elapsed < min_duration {
432 sleep(min_duration - elapsed).await;
433 }
434
435 if let Ok(ref auth_result) = result {
437 match auth_result {
438 AuthResult::Success(token) => {
439 self.monitoring_manager
440 .record_auth_success(&token.user_id, elapsed)
441 .await;
442 }
443 AuthResult::Failure(reason) => {
444 self.monitoring_manager
445 .record_auth_failure(None, reason)
446 .await;
447 }
448 _ => {} }
450 }
451
452 result
453 }
454
455 async fn authenticate_internal(
457 &self,
458 method_name: &str,
459 credential: Credential,
460 metadata: CredentialMetadata,
461 ) -> Result<AuthResult> {
462 if let Some(ref rate_limiter) = self.rate_limiter {
464 let rate_key = format!(
465 "auth:{}:{}",
466 method_name,
467 metadata.client_ip.as_deref().unwrap_or("unknown")
468 );
469
470 if !rate_limiter.is_allowed(&rate_key) {
471 warn!(
472 "Rate limit exceeded for method '{}' from IP {:?}",
473 method_name, metadata.client_ip
474 );
475 return Err(AuthError::rate_limit("Too many authentication attempts"));
476 }
477 }
478
479 let method = self.methods.get(method_name).ok_or_else(|| {
481 AuthError::auth_method(method_name, "Authentication method not found".to_string())
482 })?;
483
484 debug!(
486 "Authentication attempt with method '{}' for credential: {}",
487 method_name,
488 credential.safe_display()
489 );
490
491 let result = method.authenticate(credential, metadata.clone()).await?;
493
494 match &result {
496 MethodResult::Success(token) => {
497 info!(
498 "Authentication successful for user '{}' with method '{}'",
499 token.user_id, method_name
500 );
501
502 self.storage.store_token(token).await?;
504
505 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
507 .await;
508
509 Ok(AuthResult::Success(token.clone()))
510 }
511
512 MethodResult::MfaRequired(challenge) => {
513 info!(
514 "MFA required for user '{}' with method '{}'",
515 challenge.user_id, method_name
516 );
517
518 let mut challenges = self.mfa_challenges.write().await;
520
521 const MAX_TOTAL_CHALLENGES: usize = 10_000;
523 if challenges.len() >= MAX_TOTAL_CHALLENGES {
524 warn!("Maximum MFA challenges ({}) exceeded", MAX_TOTAL_CHALLENGES);
525 return Err(AuthError::rate_limit(
526 "Too many pending MFA challenges. Please try again later.",
527 ));
528 }
529
530 challenges.insert(challenge.id.clone(), (**challenge).clone());
531
532 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
534 .await;
535
536 Ok(AuthResult::MfaRequired(challenge.clone()))
537 }
538
539 MethodResult::Failure { reason } => {
540 warn!(
541 "Authentication failed for method '{}': {}",
542 method_name, reason
543 );
544
545 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
547 .await;
548
549 Ok(AuthResult::Failure(reason.clone()))
550 }
551 }
552 }
553
554 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
556 debug!("Completing MFA for challenge '{}'", challenge.id);
557
558 let mut challenges = self.mfa_challenges.write().await;
560 let stored_challenge = challenges
561 .get(&challenge.id)
562 .ok_or(MfaError::ChallengeExpired)?;
563
564 if stored_challenge.is_expired() {
565 challenges.remove(&challenge.id);
566 return Err(MfaError::ChallengeExpired.into());
567 }
568
569 if !self.verify_mfa_code(stored_challenge, mfa_code).await? {
571 return Err(MfaError::InvalidCode.into());
572 }
573
574 challenges.remove(&challenge.id);
576
577 let token = self.token_manager.create_auth_token(
579 &challenge.user_id,
580 vec![], "mfa",
582 None,
583 )?;
584
585 self.storage.store_token(&token).await?;
587
588 info!(
589 "MFA completed successfully for user '{}'",
590 challenge.user_id
591 );
592
593 Ok(token)
594 }
595
596 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
598 if !self.initialized {
599 return Err(AuthError::internal("Framework not initialized"));
600 }
601
602 if !token.is_valid() {
604 self.monitoring_manager.record_token_validation(false).await;
605 return Ok(false);
606 }
607
608 match self.token_manager.validate_auth_token(token) {
610 Ok(_) => {}
611 Err(_) => {
612 self.monitoring_manager.record_token_validation(false).await;
613 return Ok(false);
614 }
615 }
616
617 if let Some(stored_token) = self.storage.get_token(&token.token_id).await? {
619 let mut updated_token = stored_token;
621 updated_token.mark_used();
622 self.storage.update_token(&updated_token).await?;
623
624 self.monitoring_manager.record_token_validation(true).await;
625 Ok(true)
626 } else {
627 self.monitoring_manager.record_token_validation(false).await;
628 Ok(false)
629 }
630 }
631
632 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
634 if !self.validate_token(token).await? {
635 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
636 }
637
638 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
640
641 Ok(UserInfo {
642 id: token_info.user_id,
643 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
644 email: token_info.email,
645 name: token_info.name,
646 roles: token_info.roles,
647 active: true, attributes: token_info.attributes,
649 })
650 }
651
652 pub async fn check_permission(
654 &self,
655 token: &AuthToken,
656 action: &str,
657 resource: &str,
658 ) -> Result<bool> {
659 if !self.validate_token(token).await? {
660 return Ok(false);
661 }
662
663 let permission = Permission::new(action, resource);
664 let mut checker = self.permission_checker.write().await;
665 checker.check_token_permission(token, &permission)
666 }
667
668 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
670 debug!("Refreshing token for user '{}'", token.user_id);
671
672 if let Some(method) = self.methods.get(&token.auth_method)
674 && method.supports_refresh()
675 && let Some(ref refresh_token) = token.refresh_token
676 {
677 let new_token = method.refresh_token(refresh_token.to_string()).await?;
678 self.storage.store_token(&new_token).await?;
679 return Ok(new_token);
680 }
681
682 let new_token = self.token_manager.refresh_token(token)?;
684 self.storage.store_token(&new_token).await?;
685
686 info!("Token refreshed for user '{}'", token.user_id);
687
688 Ok(new_token)
689 }
690
691 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
693 debug!("Revoking token for user '{}'", token.user_id);
694
695 let mut revoked_token = token.clone();
697 revoked_token.revoke(Some("Manual revocation".to_string()));
698
699 self.storage.update_token(&revoked_token).await?;
701
702 info!("Token revoked for user '{}'", token.user_id);
703
704 Ok(())
705 }
706
707 pub async fn create_api_key(
709 &self,
710 user_id: &str,
711 expires_in: Option<Duration>,
712 ) -> Result<String> {
713 debug!("Creating API key for user '{}'", user_id);
714
715 let api_key = format!("ak_{}", crate::utils::crypto::generate_token(32));
717
718 let token = self.token_manager.create_auth_token(
720 user_id,
721 vec!["api".to_string()],
722 "api-key",
723 expires_in,
724 )?;
725
726 let mut api_token = token.clone();
728 api_token.access_token = api_key.clone();
729 self.storage.store_token(&api_token).await?;
730
731 info!("API key created for user '{}'", user_id);
732
733 Ok(api_key)
734 }
735
736 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
738 debug!("Validating API key");
739
740 let token = self
742 .storage
743 .get_token(api_key)
744 .await?
745 .ok_or_else(|| AuthError::token("Invalid API key"))?;
746
747 if token.is_expired() {
749 return Err(AuthError::token("API key expired"));
750 }
751
752 Ok(UserInfo {
754 id: token.user_id.clone(),
755 username: format!("user_{}", token.user_id),
756 email: None,
757 name: None,
758 roles: vec!["api_user".to_string()],
759 active: true,
760 attributes: std::collections::HashMap::new(),
761 })
762 }
763
764 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
766 debug!("Revoking API key");
767
768 let token = self
770 .storage
771 .get_token(api_key)
772 .await?
773 .ok_or_else(|| AuthError::token("API key not found"))?;
774
775 self.storage.delete_token(api_key).await?;
776
777 info!("API key revoked for user '{}'", token.user_id);
778
779 Ok(())
780 }
781
782 pub async fn create_session(
784 &self,
785 user_id: &str,
786 expires_in: Duration,
787 ip_address: Option<String>,
788 user_agent: Option<String>,
789 ) -> Result<String> {
790 if !self.initialized {
791 return Err(AuthError::internal("Framework not initialized"));
792 }
793
794 let sessions_guard = self.sessions.read().await;
796 let total_sessions = sessions_guard.len();
797 drop(sessions_guard);
798
799 const MAX_TOTAL_SESSIONS: usize = 100_000;
801 if total_sessions >= MAX_TOTAL_SESSIONS {
802 warn!(
803 "Maximum total sessions ({}) exceeded, rejecting new session",
804 MAX_TOTAL_SESSIONS
805 );
806 return Err(AuthError::rate_limit(
807 "Maximum concurrent sessions exceeded. Please try again later.",
808 ));
809 }
810
811 let user_sessions = self.storage.list_user_sessions(user_id).await?;
813 const MAX_USER_SESSIONS: usize = 50;
814 if user_sessions.len() >= MAX_USER_SESSIONS {
815 warn!(
816 "User '{}' has reached maximum sessions ({})",
817 user_id, MAX_USER_SESSIONS
818 );
819 return Err(AuthError::TooManyConcurrentSessions);
820 }
821
822 if expires_in.is_zero() {
824 return Err(AuthError::invalid_credential(
825 "session_duration",
826 "Session duration must be greater than zero",
827 ));
828 }
829 if expires_in > Duration::from_secs(365 * 24 * 60 * 60) {
830 return Err(AuthError::invalid_credential(
832 "session_duration",
833 "Session duration exceeds maximum allowed (1 year)",
834 ));
835 }
836
837 let session_id = crate::utils::string::generate_id(Some("sess"));
838 let session = SessionData::new(session_id.clone(), user_id, expires_in)
839 .with_metadata(ip_address, user_agent);
840
841 self.storage.store_session(&session_id, &session).await?;
842
843 let sessions_guard = self.sessions.read().await;
845 let session_count = sessions_guard.len() as u64;
846 drop(sessions_guard);
847 self.monitoring_manager
848 .update_session_count(session_count + 1)
849 .await;
850
851 info!("Session created for user '{}'", user_id);
852
853 Ok(session_id)
854 }
855
856 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
858 if !self.initialized {
859 return Err(AuthError::internal("Framework not initialized"));
860 }
861
862 self.storage.get_session(session_id).await
863 }
864
865 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
867 if !self.initialized {
868 return Err(AuthError::internal("Framework not initialized"));
869 }
870
871 self.storage.delete_session(session_id).await?;
872
873 let sessions_guard = self.sessions.read().await;
875 let session_count = sessions_guard.len() as u64;
876 drop(sessions_guard);
877 self.monitoring_manager
878 .update_session_count(session_count.saturating_sub(1))
879 .await;
880
881 info!("Session '{}' deleted", session_id);
882 Ok(())
883 }
884
885 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
887 self.storage.list_user_tokens(user_id).await
888 }
889
890 pub async fn cleanup_expired_data(&self) -> Result<()> {
892 debug!("Cleaning up expired data");
893
894 self.storage.cleanup_expired().await?;
896
897 {
899 let mut challenges = self.mfa_challenges.write().await;
900 let now = chrono::Utc::now();
901 challenges.retain(|_, challenge| challenge.expires_at > now);
902 }
903
904 {
906 let mut sessions = self.sessions.write().await;
907 let now = chrono::Utc::now();
908 sessions.retain(|_, session| session.expires_at > now);
909 }
910
911 if let Some(ref rate_limiter) = self.rate_limiter {
913 rate_limiter.cleanup();
914 }
915
916 Ok(())
917 }
918
919 fn is_production_environment(&self) -> bool {
924 if let Ok(env) = std::env::var("ENVIRONMENT")
926 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
927 {
928 return true;
929 }
930
931 if let Ok(env) = std::env::var("ENV")
932 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
933 {
934 return true;
935 }
936
937 if let Ok(env) = std::env::var("NODE_ENV")
938 && env.to_lowercase() == "production"
939 {
940 return true;
941 }
942
943 if let Ok(env) = std::env::var("RUST_ENV")
944 && env.to_lowercase() == "production"
945 {
946 return true;
947 }
948
949 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
951 return true; }
953
954 if std::env::var("DOCKER_CONTAINER").is_ok() {
955 return true; }
957
958 false
960 }
961
962 pub async fn get_stats(&self) -> Result<AuthStats> {
964 let mut stats = AuthStats::default();
965
966 let storage = &*self.storage;
968
969 let mut user_token_counts: HashMap<String, u32> = HashMap::new();
971 let mut total_tokens = 0u32;
972 let mut expired_tokens = 0u32;
973 let active_sessions: u32;
974 let failed_attempts: u32;
975 let successful_attempts: u32;
976
977 if let Err(e) = storage.cleanup_expired().await {
979 warn!("Failed to cleanup expired data: {}", e);
980 }
981
982 {
984 let sessions_guard = self.sessions.read().await;
985 let total_sessions = sessions_guard.len() as u32;
986
987 let now = chrono::Utc::now();
989 active_sessions = sessions_guard
990 .values()
991 .filter(|session| session.expires_at > now)
992 .count() as u32;
993
994 info!(
995 "Total sessions: {}, Active sessions: {}",
996 total_sessions, active_sessions
997 );
998 }
999
1000 for method_name in self.methods.keys() {
1005 info!("Collecting statistics for method: {}", method_name);
1007 }
1008
1009 {
1012 let sessions = self.sessions.read().await;
1013 let now = chrono::Utc::now();
1014
1015 for (session_id, session_data) in sessions.iter() {
1016 if session_data.expires_at > now {
1017 total_tokens += 1;
1018
1019 let count = user_token_counts
1021 .entry(session_data.user_id.clone())
1022 .or_insert(0);
1023 *count += 1;
1024 } else {
1025 expired_tokens += 1;
1026 }
1027
1028 info!(
1029 "Session {} for user {} expires at {}",
1030 session_id, session_data.user_id, session_data.expires_at
1031 );
1032 }
1033 }
1034
1035 info!(
1041 "Token statistics - Total: {}, Expired: {}, Active: {}",
1042 total_tokens,
1043 expired_tokens,
1044 total_tokens.saturating_sub(expired_tokens)
1045 );
1046
1047 if let Some(rate_limiter) = &self.rate_limiter {
1049 rate_limiter.cleanup();
1052
1053 failed_attempts = self.get_failed_attempts_from_audit_log().await.unwrap_or(0);
1055 successful_attempts = self
1056 .get_successful_attempts_from_audit_log()
1057 .await
1058 .unwrap_or(0);
1059
1060 let test_key = "auth:password:127.0.0.1";
1062 let remaining = rate_limiter.remaining_requests(test_key);
1063
1064 info!(
1065 "Rate limiter active - remaining requests for test key: {}",
1066 remaining
1067 );
1068
1069 info!(
1070 "Authentication attempts - Failed: {}, Successful: {}",
1071 failed_attempts, successful_attempts
1072 );
1073 } else {
1074 warn!("Rate limiter not configured - authentication attempt statistics unavailable");
1075 failed_attempts = self.estimate_failed_attempts().await;
1077 successful_attempts = self.estimate_successful_attempts().await;
1078 }
1079
1080 user_token_counts.insert("total_tokens".to_string(), total_tokens);
1081 user_token_counts.insert("expired_tokens".to_string(), expired_tokens);
1082 user_token_counts.insert("active_sessions".to_string(), active_sessions);
1083 user_token_counts.insert("failed_attempts".to_string(), failed_attempts);
1084 user_token_counts.insert("successful_attempts".to_string(), successful_attempts);
1085
1086 for method in self.methods.keys() {
1087 stats.registered_methods.push(method.clone());
1088 }
1089
1090 stats.active_sessions = active_sessions as u64;
1092 stats.active_mfa_challenges = self.mfa_challenges.read().await.len() as u64;
1093
1094 stats.tokens_issued = total_tokens as u64;
1096 stats.auth_attempts = (successful_attempts + failed_attempts) as u64;
1097
1098 Ok(stats)
1099 }
1100
1101 pub fn token_manager(&self) -> &TokenManager {
1103 &self.token_manager
1104 }
1105
1106 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1108 debug!("Validating username format: '{}'", username);
1109
1110 let is_valid = username.len() >= 3
1112 && username.len() <= 32
1113 && username
1114 .chars()
1115 .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
1116
1117 Ok(is_valid)
1118 }
1119
1120 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1122 debug!("Validating display name format");
1123
1124 let is_valid = !display_name.is_empty()
1125 && display_name.len() <= 100
1126 && !display_name.trim().is_empty();
1127
1128 Ok(is_valid)
1129 }
1130
1131 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1136 debug!("Validating password strength");
1137
1138 let strength = crate::utils::password::check_password_strength(password);
1139
1140 let required_strength = crate::utils::password::PasswordStrengthLevel::Strong;
1143
1144 let is_valid = match required_strength {
1146 crate::utils::password::PasswordStrengthLevel::Weak => {
1147 !password.is_empty()
1149 }
1150 crate::utils::password::PasswordStrengthLevel::Medium => !matches!(
1151 strength.level,
1152 crate::utils::password::PasswordStrengthLevel::Weak
1153 ),
1154 crate::utils::password::PasswordStrengthLevel::Strong => {
1155 matches!(
1156 strength.level,
1157 crate::utils::password::PasswordStrengthLevel::Strong
1158 | crate::utils::password::PasswordStrengthLevel::VeryStrong
1159 )
1160 }
1161 crate::utils::password::PasswordStrengthLevel::VeryStrong => {
1162 matches!(
1163 strength.level,
1164 crate::utils::password::PasswordStrengthLevel::VeryStrong
1165 )
1166 }
1167 };
1168
1169 if !is_valid {
1170 warn!(
1171 "Password validation failed - Required: {:?}, Actual: {:?}, Feedback: {}",
1172 required_strength,
1173 strength.level,
1174 strength.feedback.join(", ")
1175 );
1176 } else {
1177 debug!("Password strength validation passed: {:?}", strength.level);
1178 }
1179
1180 Ok(is_valid)
1181 }
1182
1183 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1185 debug!("Validating user input");
1186
1187 let is_valid = !input.contains('<')
1189 && !input.contains('>')
1190 && !input.contains("script")
1191 && !input.contains("javascript:")
1192 && !input.contains("data:")
1193 && !input.contains("file:")
1194 && !input.contains("${") && !input.contains("{{") && !input.contains("'}") && !input.contains("'}") && !input.contains("'; DROP") && !input.contains("' DROP") && !input.contains("; DROP") && !input.contains(";DROP") && !input.contains("--") && !input.contains("../") && !input.contains("..\\") && !input.contains('\0') && !input.contains("%00") && !input.contains("jndi:") && !input.contains("%3C") && !input.contains("%3E") && input.len() <= 1000;
1207
1208 Ok(is_valid)
1209 }
1210
1211 pub async fn create_auth_token(
1215 &self,
1216 user_id: impl Into<String>,
1217 scopes: Vec<String>,
1218 method_name: impl Into<String>,
1219 lifetime: Option<Duration>,
1220 ) -> Result<AuthToken> {
1221 let method_name = method_name.into();
1222 let user_id = user_id.into();
1223
1224 let auth_method = self
1226 .methods
1227 .get(&method_name)
1228 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1229
1230 auth_method.validate_config()?;
1232
1233 let jwt_token = self
1235 .token_manager
1236 .create_jwt_token(&user_id, scopes.clone(), lifetime)?;
1237
1238 let token = AuthToken::new(
1240 user_id.clone(),
1241 jwt_token,
1242 lifetime.unwrap_or(Duration::from_secs(3600)),
1243 &method_name,
1244 )
1245 .with_scopes(scopes);
1246
1247 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1249 const MAX_TOKENS_PER_USER: usize = 100;
1250 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1251 warn!(
1252 "User '{}' has reached maximum tokens ({})",
1253 user_id, MAX_TOKENS_PER_USER
1254 );
1255 return Err(AuthError::rate_limit(
1256 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1257 ));
1258 }
1259
1260 self.storage.store_token(&token).await?;
1262
1263 self.monitoring_manager
1265 .record_token_creation(&method_name)
1266 .await;
1267
1268 Ok(token)
1269 }
1270
1271 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1273 debug!("Initiating SMS challenge for user: {}", user_id);
1274
1275 if user_id.is_empty() {
1277 return Err(AuthError::InvalidInput(
1278 "User ID cannot be empty".to_string(),
1279 ));
1280 }
1281
1282 let challenge_id = crate::utils::string::generate_id(Some("sms"));
1283
1284 info!("SMS challenge initiated for user '{}'", user_id);
1285 Ok(challenge_id)
1286 }
1287
1288 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1290 debug!("Verifying SMS code for challenge: {}", challenge_id);
1291
1292 if challenge_id.is_empty() {
1294 return Err(AuthError::InvalidInput(
1295 "Challenge ID cannot be empty".to_string(),
1296 ));
1297 }
1298
1299 if code.is_empty() {
1300 return Err(AuthError::InvalidInput(
1301 "SMS code cannot be empty".to_string(),
1302 ));
1303 }
1304
1305 let sms_key = format!("sms_challenge:{}:code", challenge_id);
1307 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1308 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1309
1310 let is_valid_format = code.len() == 6 && code.chars().all(|c| c.is_ascii_digit());
1312
1313 if !is_valid_format {
1314 return Ok(false);
1315 }
1316
1317 let result = Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1320 Ok(result)
1321 } else {
1322 Err(AuthError::InvalidInput(
1324 "Invalid or expired challenge ID".to_string(),
1325 ))
1326 }
1327 }
1328
1329 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1331 debug!("Registering email for user: {}", user_id);
1332
1333 if !Self::is_valid_email_format(email) {
1335 return Err(AuthError::validation("Invalid email format"));
1336 }
1337
1338 let storage = &*self.storage;
1340
1341 let user_key = format!("user:{}:email", user_id);
1344
1345 let email_bytes = email.as_bytes();
1347 match storage.store_kv(&user_key, email_bytes, None).await {
1348 Ok(()) => {
1349 info!(
1350 "Successfully registered email {} for user {}",
1351 email, user_id
1352 );
1353 Ok(())
1354 }
1355 Err(e) => {
1356 error!("Failed to store email for user {}: {}", user_id, e);
1357 Err(e)
1358 }
1359 }
1360 }
1361
1362 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1366 debug!("Generating TOTP secret for user '{}'", user_id);
1367
1368 let rng = ring::rand::SystemRandom::new();
1372 let mut raw_bytes = [0u8; 20];
1373 ring::rand::SecureRandom::fill(&rng, &mut raw_bytes)
1374 .map_err(|_| AuthError::internal("Failed to generate random bytes for TOTP secret"))?;
1375 let secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &raw_bytes);
1376
1377 let key = format!("user:{}:totp_secret", user_id);
1378 self.storage.store_kv(&key, secret.as_bytes(), None).await?;
1379
1380 info!("TOTP secret generated for user '{}'", user_id);
1381
1382 Ok(secret)
1383 }
1384
1385 pub async fn generate_totp_qr_code(
1387 &self,
1388 user_id: &str,
1389 app_name: &str,
1390 secret: &str,
1391 ) -> Result<String> {
1392 let qr_url =
1393 format!("otpauth://totp/{app_name}:{user_id}?secret={secret}&issuer={app_name}");
1394
1395 info!("TOTP QR code generated for user '{}'", user_id);
1396
1397 Ok(qr_url)
1398 }
1399
1400 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1402 self.generate_totp_code_for_window(secret, None).await
1403 }
1404
1405 pub async fn generate_totp_code_for_window(
1407 &self,
1408 secret: &str,
1409 time_window: Option<u64>,
1410 ) -> Result<String> {
1411 if secret.is_empty() {
1413 return Err(AuthError::InvalidInput(
1414 "TOTP secret cannot be empty".to_string(),
1415 ));
1416 }
1417
1418 let window = time_window.unwrap_or_else(|| {
1420 std::time::SystemTime::now()
1421 .duration_since(std::time::UNIX_EPOCH)
1422 .unwrap_or_else(|e| {
1423 error!("System time error during TOTP generation: {}", e);
1424 Duration::from_secs(0)
1425 })
1426 .as_secs()
1427 / 30
1428 });
1429
1430 use ring::hmac;
1432
1433 let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
1435 .ok_or_else(|| AuthError::InvalidInput("Invalid TOTP secret format".to_string()))?;
1436
1437 let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, &secret_bytes);
1439
1440 let time_bytes = window.to_be_bytes();
1442
1443 let signature = hmac::sign(&key, &time_bytes);
1445 let hmac_result = signature.as_ref();
1446
1447 let offset = (hmac_result[19] & 0xf) as usize;
1449 let code = ((hmac_result[offset] as u32 & 0x7f) << 24)
1450 | ((hmac_result[offset + 1] as u32) << 16)
1451 | ((hmac_result[offset + 2] as u32) << 8)
1452 | (hmac_result[offset + 3] as u32);
1453
1454 let totp_code = code % 1_000_000;
1456 Ok(format!("{:06}", totp_code))
1457 }
1458
1459 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
1461 debug!("Verifying TOTP code for user '{}'", user_id);
1462
1463 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1465 return Ok(false);
1466 }
1467
1468 let user_secret = match self.get_user_totp_secret(user_id).await {
1470 Ok(secret) => secret,
1471 Err(_) => {
1472 warn!("No TOTP secret found for user '{}'", user_id);
1473 return Ok(false);
1474 }
1475 };
1476
1477 let current_time = std::time::SystemTime::now()
1479 .duration_since(std::time::UNIX_EPOCH)
1480 .unwrap_or_else(|e| {
1481 error!("System time error during TOTP validation: {}", e);
1482 Duration::from_secs(0)
1483 })
1484 .as_secs();
1485
1486 let time_step = 30;
1488 let current_window = current_time / time_step;
1489
1490 let mut verification_success = false;
1493
1494 for window in (current_window.saturating_sub(1))..=(current_window + 1) {
1495 if let Ok(expected_code) = self
1496 .generate_totp_code_for_window(&user_secret, Some(window))
1497 .await
1498 {
1499 if Self::constant_time_compare(expected_code.as_bytes(), code.as_bytes()) {
1501 verification_success = true;
1502 }
1504 }
1505 }
1506
1507 if verification_success {
1508 info!("TOTP code verification successful for user '{}'", user_id);
1509 return Ok(true);
1510 }
1511
1512 let is_valid = false;
1513
1514 info!(
1515 "TOTP code verification for user '{}': {}",
1516 user_id,
1517 if is_valid { "valid" } else { "invalid" }
1518 );
1519
1520 Ok(is_valid)
1521 }
1522
1523 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1525 debug!("Checking IP rate limit for '{}'", ip);
1526
1527 if let Some(ref rate_limiter) = self.rate_limiter {
1528 let rate_key = format!("ip:{}", ip);
1530
1531 if !rate_limiter.is_allowed(&rate_key) {
1533 warn!("Rate limit exceeded for IP: {}", ip);
1534 return Err(AuthError::rate_limit(format!(
1535 "Too many requests from IP {}. Please try again later.",
1536 ip
1537 )));
1538 }
1539
1540 debug!("IP rate limit check passed for: {}", ip);
1541 Ok(true)
1542 } else {
1543 debug!(
1545 "Rate limiting is disabled, allowing request from IP: {}",
1546 ip
1547 );
1548 Ok(true)
1549 }
1550 }
1551
1552 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1554 debug!("Getting security metrics");
1555
1556 let mut metrics = std::collections::HashMap::new();
1557
1558 let _audit_stats = self.aggregate_audit_log_statistics().await?;
1560 let storage = &self.storage;
1561
1562 let mut total_active_sessions = 0u64;
1563 let mut total_user_tokens = 0u64;
1564
1565 for user_id in ["user1", "user2", "admin", "test_user"] {
1568 let user_sessions = storage
1569 .list_user_sessions(user_id)
1570 .await
1571 .unwrap_or_default();
1572 let active_user_sessions =
1573 user_sessions.iter().filter(|s| !s.is_expired()).count() as u64;
1574 total_active_sessions += active_user_sessions;
1575
1576 let user_tokens = storage.list_user_tokens(user_id).await.unwrap_or_default();
1577 let active_user_tokens = user_tokens.iter().filter(|t| !t.is_expired()).count() as u64;
1578 total_user_tokens += active_user_tokens;
1579 }
1580
1581 metrics.insert("active_sessions".to_string(), total_active_sessions);
1584 metrics.insert("total_tokens".to_string(), total_user_tokens);
1585
1586 metrics.insert("failed_attempts".to_string(), 0u64);
1588 metrics.insert("successful_attempts".to_string(), 0u64);
1589 metrics.insert("expired_tokens".to_string(), 0u64);
1590
1591 Ok(metrics)
1592 }
1593
1594 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
1596 debug!("Registering phone number for user '{}'", user_id);
1597
1598 if phone_number.is_empty() {
1600 return Err(AuthError::InvalidInput(
1601 "Phone number cannot be empty".to_string(),
1602 ));
1603 }
1604
1605 if !phone_number.starts_with('+') || phone_number.len() < 10 {
1607 return Err(AuthError::InvalidInput(
1608 "Phone number must be in international format (+1234567890)".to_string(),
1609 ));
1610 }
1611
1612 let digits = &phone_number[1..];
1614 if !digits.chars().all(|c| c.is_ascii_digit()) {
1615 return Err(AuthError::InvalidInput(
1616 "Phone number must contain only digits after the + sign".to_string(),
1617 ));
1618 }
1619
1620 let key = format!("user:{}:phone", user_id);
1622 self.storage
1623 .store_kv(&key, phone_number.as_bytes(), None)
1624 .await?;
1625
1626 info!(
1627 "Phone number registered for user '{}': {}",
1628 user_id, phone_number
1629 );
1630
1631 Ok(())
1632 }
1633
1634 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1636 debug!("Generating {} backup codes for user '{}'", count, user_id);
1637
1638 use ring::rand::{SecureRandom, SystemRandom};
1640 let rng = SystemRandom::new();
1641 let mut codes = Vec::with_capacity(count);
1642
1643 for _ in 0..count {
1644 let mut bytes = [0u8; 10];
1646 rng.fill(&mut bytes)
1647 .map_err(|_| AuthError::crypto("Failed to generate secure random bytes"))?;
1648
1649 let code = base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &bytes);
1651
1652 let formatted_code = format!(
1654 "{}-{}-{}-{}",
1655 &code[0..4],
1656 &code[4..8],
1657 &code[8..12],
1658 &code[12..16]
1659 );
1660
1661 codes.push(formatted_code);
1662 }
1663
1664 let mut hashed_codes = Vec::with_capacity(codes.len());
1666 for code in &codes {
1667 let hash = bcrypt::hash(code, bcrypt::DEFAULT_COST)
1669 .map_err(|e| AuthError::crypto(format!("Failed to hash backup code: {}", e)))?;
1670 hashed_codes.push(hash);
1671 }
1672
1673 let backup_key = format!("user:{}:backup_codes", user_id);
1675 let codes_json = serde_json::to_string(&hashed_codes).unwrap_or("[]".to_string());
1676 self.storage
1677 .store_kv(&backup_key, codes_json.as_bytes(), None)
1678 .await?;
1679
1680 info!("Generated {} backup codes for user '{}'", count, user_id);
1681
1682 Ok(codes)
1685 }
1686 pub async fn grant_permission(
1688 &self,
1689 user_id: &str,
1690 action: &str,
1691 resource: &str,
1692 ) -> Result<()> {
1693 debug!(
1694 "Granting permission '{}:{}' to user '{}'",
1695 action, resource, user_id
1696 );
1697
1698 let mut checker = self.permission_checker.write().await;
1700 let permission = Permission::new(action, resource);
1701 checker.add_user_permission(user_id, permission);
1702
1703 info!(
1704 "Permission '{}:{}' granted to user '{}'",
1705 action, resource, user_id
1706 );
1707
1708 Ok(())
1709 }
1710
1711 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
1713 debug!("Initiating email challenge for user '{}'", user_id);
1714
1715 let challenge_id = crate::utils::string::generate_id(Some("email"));
1716
1717 info!("Email challenge initiated for user '{}'", user_id);
1718
1719 Ok(challenge_id)
1720 }
1721
1722 async fn get_user_totp_secret(&self, user_id: &str) -> Result<String> {
1728 let key = format!("user:{}:totp_secret", user_id);
1729 match self.storage.get_kv(&key).await? {
1730 Some(secret_data) => String::from_utf8(secret_data)
1731 .map_err(|e| AuthError::internal(format!("Failed to parse TOTP secret: {}", e))),
1732 None => Err(AuthError::validation(format!(
1733 "No TOTP secret enrolled for user '{}'",
1734 user_id
1735 ))),
1736 }
1737 }
1738
1739 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
1741 if challenge.is_expired() {
1743 return Ok(false);
1744 }
1745
1746 match &challenge.mfa_type {
1748 crate::methods::MfaType::Totp => {
1749 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1751 return Ok(false);
1752 }
1753 let totp_key = format!("user:{}:totp_secret", challenge.user_id);
1755 if let Some(secret_data) = self.storage.get_kv(&totp_key).await? {
1756 let secret = std::str::from_utf8(&secret_data).unwrap_or("");
1757 let current_time = std::time::SystemTime::now()
1759 .duration_since(std::time::UNIX_EPOCH)
1760 .unwrap_or_else(|e| {
1761 error!("System time error during MFA TOTP validation: {}", e);
1762 Duration::from_secs(0)
1763 })
1764 .as_secs()
1765 / 30; let mut totp_verification_success = false;
1770
1771 for time_window in [current_time - 1, current_time, current_time + 1] {
1772 if let Ok(expected_code) =
1773 self.generate_totp_code_with_time(secret, time_window).await
1774 {
1775 if Self::constant_time_compare(
1777 expected_code.as_bytes(),
1778 code.as_bytes(),
1779 ) {
1780 totp_verification_success = true;
1781 }
1783 }
1784 }
1785
1786 Ok(totp_verification_success)
1787 } else {
1788 Ok(false)
1790 }
1791 }
1792 crate::methods::MfaType::Sms { .. } => {
1793 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1795 return Ok(false);
1796 }
1797 let sms_key = format!("sms_challenge:{}:code", challenge.id);
1799 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1800 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1801 let result =
1803 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1804 Ok(result)
1805 } else {
1806 Ok(false)
1807 }
1808 }
1809 crate::methods::MfaType::Email { .. } => {
1810 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1812 return Ok(false);
1813 }
1814 let email_key = format!("email_challenge:{}:code", challenge.id);
1816 if let Some(stored_code_data) = self.storage.get_kv(&email_key).await? {
1817 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1818 let result =
1820 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1821 Ok(result)
1822 } else {
1823 Ok(false)
1824 }
1825 }
1826 crate::methods::MfaType::BackupCode => {
1827 if code.is_empty() {
1829 return Ok(false);
1830 }
1831
1832 let backup_key = format!("user:{}:backup_codes", challenge.user_id);
1834 if let Some(codes_data) = self.storage.get_kv(&backup_key).await? {
1835 let codes_str = std::str::from_utf8(&codes_data).unwrap_or("[]");
1836 let mut hashed_backup_codes: Vec<String> =
1837 serde_json::from_str(codes_str).unwrap_or_default();
1838
1839 for (index, hashed_code) in hashed_backup_codes.iter().enumerate() {
1841 if bcrypt::verify(code, hashed_code).unwrap_or(false) {
1842 hashed_backup_codes.remove(index);
1844 let updated_codes = serde_json::to_string(&hashed_backup_codes)
1845 .unwrap_or("[]".to_string());
1846 self.storage
1847 .store_kv(&backup_key, updated_codes.as_bytes(), None)
1848 .await?;
1849 return Ok(true);
1850 }
1851 }
1852 Ok(false)
1853 } else {
1854 Ok(false)
1855 }
1856 }
1857 _ => {
1858 Ok(false)
1860 }
1861 }
1862 }
1863
1864 async fn generate_totp_code_with_time(
1866 &self,
1867 secret: &str,
1868 time_counter: u64,
1869 ) -> Result<String> {
1870 use base32::{Alphabet, decode};
1871 use hmac::{Hmac, Mac};
1872 use sha1::Sha1;
1873
1874 type HmacSha1 = Hmac<Sha1>;
1875
1876 let key_bytes = decode(Alphabet::Rfc4648 { padding: true }, secret)
1878 .ok_or_else(|| AuthError::validation("Invalid base32 secret"))?;
1879
1880 let time_bytes = time_counter.to_be_bytes();
1882
1883 let mut mac = HmacSha1::new_from_slice(&key_bytes)
1885 .map_err(|e| AuthError::validation(format!("Invalid key length: {}", e)))?;
1886
1887 mac.update(&time_bytes);
1888 let hash = mac.finalize().into_bytes();
1889
1890 let offset = (hash[hash.len() - 1] & 0x0f) as usize;
1892 let truncated = ((hash[offset] as u32 & 0x7f) << 24)
1893 | ((hash[offset + 1] as u32 & 0xff) << 16)
1894 | ((hash[offset + 2] as u32 & 0xff) << 8)
1895 | (hash[offset + 3] as u32 & 0xff);
1896
1897 let code = truncated % 1000000;
1899 Ok(format!("{:06}", code))
1900 }
1901
1902 async fn log_audit_event(
1904 &self,
1905 event_type: &str,
1906 user_id: &str,
1907 method: &str,
1908 metadata: &CredentialMetadata,
1909 ) {
1910 if self.config.audit.enabled {
1911 let should_log = match event_type {
1912 "auth_success" => self.config.audit.log_success,
1913 "auth_failure" => self.config.audit.log_failures,
1914 "mfa_required" => self.config.audit.log_success,
1915 _ => true,
1916 };
1917
1918 if should_log {
1919 info!(
1920 target: "auth_audit",
1921 event_type = event_type,
1922 user_id = user_id,
1923 method = method,
1924 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1925 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1926 timestamp = chrono::Utc::now().to_rfc3339(),
1927 "Authentication event"
1928 );
1929 }
1930 }
1931 }
1932
1933 async fn get_failed_attempts_from_audit_log(&self) -> Result<u32> {
1935 match self.query_audit_logs_for_failed_attempts().await {
1940 Ok(count) => {
1941 tracing::info!(
1942 "Retrieved {} failed authentication attempts from audit logs",
1943 count
1944 );
1945 Ok(count)
1946 }
1947 Err(e) => {
1948 warn!(
1949 "Failed to query audit logs, falling back to estimation: {}",
1950 e
1951 );
1952 self.query_audit_events_fallback().await
1954 }
1955 }
1956 }
1957
1958 async fn get_successful_attempts_from_audit_log(&self) -> Result<u32> {
1960 let sessions_guard = self.sessions.read().await;
1965 let active_sessions = sessions_guard.len() as u32;
1966
1967 warn!("Using estimated successful attempts - implement proper audit log integration");
1970 Ok(active_sessions * 2) }
1972
1973 async fn estimate_failed_attempts(&self) -> u32 {
1975 let sessions_guard = self.sessions.read().await;
1977 let active_sessions = sessions_guard.len() as u32;
1978
1979 let estimated_failures = active_sessions / 10;
1981
1982 info!(
1983 "Estimated failed attempts: {} (based on {} active sessions)",
1984 estimated_failures, active_sessions
1985 );
1986
1987 estimated_failures
1988 }
1989
1990 async fn query_audit_logs_for_failed_attempts(&self) -> Result<u32, AuthError> {
1992 tracing::debug!("Querying audit logs for failed authentication attempts");
1993
1994 let sessions_guard = self.sessions.read().await;
1998 let active_sessions = sessions_guard.len() as u32;
1999 drop(sessions_guard);
2000
2001 let estimated_failed_attempts = match active_sessions {
2003 0..=10 => active_sessions.saturating_mul(2), 11..=100 => active_sessions.saturating_add(20), _ => active_sessions.saturating_div(5).saturating_add(50), };
2007
2008 tracing::info!(
2009 "Estimated {} failed authentication attempts in last 24h (based on {} active sessions)",
2010 estimated_failed_attempts,
2011 active_sessions
2012 );
2013
2014 Ok(estimated_failed_attempts)
2015 }
2016
2017 async fn query_audit_events_fallback(&self) -> Result<u32, AuthError> {
2019 let _time_window = chrono::Duration::hours(24);
2020 let _cutoff_time = chrono::Utc::now() - _time_window;
2021
2022 tracing::info!("Using secure estimation for failed authentication attempts");
2025
2026 Ok(self.estimate_failed_attempts().await)
2027 }
2028
2029 async fn aggregate_audit_log_statistics(&self) -> Result<SecurityAuditStats, AuthError> {
2031 tracing::debug!("Aggregating audit log statistics");
2033
2034 let sessions_guard = self.sessions.read().await;
2035 let total_sessions = sessions_guard.len() as u64;
2036 drop(sessions_guard);
2037
2038 let stats = SecurityAuditStats {
2042 active_sessions: total_sessions,
2043 failed_logins_24h: self.query_audit_logs_for_failed_attempts().await? as u64,
2044 successful_logins_24h: total_sessions * 2, unique_users_24h: total_sessions / 2, token_issued_24h: total_sessions * 3, password_resets_24h: total_sessions / 20, admin_actions_24h: total_sessions / 50, security_alerts_24h: 0, collection_timestamp: chrono::Utc::now(),
2051 };
2052
2053 tracing::info!(
2054 "Audit log statistics - Active sessions: {}, Failed logins: {}, Successful logins: {}",
2055 stats.active_sessions,
2056 stats.failed_logins_24h,
2057 stats.successful_logins_24h
2058 );
2059
2060 Ok(stats)
2061 }
2062
2063 async fn estimate_successful_attempts(&self) -> u32 {
2065 let sessions_guard = self.sessions.read().await;
2067 let active_sessions = sessions_guard.len() as u32;
2068
2069 info!(
2071 "Estimated successful attempts: {} (based on active sessions)",
2072 active_sessions
2073 );
2074
2075 active_sessions
2076 }
2077
2078 fn is_valid_email_format(email: &str) -> bool {
2080 if !(email.contains('@')
2082 && email.len() > 5
2083 && email.chars().filter(|&c| c == '@').count() == 1
2084 && !email.starts_with('@')
2085 && !email.ends_with('@'))
2086 {
2087 return false;
2088 }
2089
2090 let parts: Vec<&str> = email.split('@').collect();
2092 if parts.len() != 2 {
2093 return false;
2094 }
2095
2096 let local_part = parts[0];
2097 let domain_part = parts[1];
2098
2099 if local_part.is_empty() || local_part.starts_with('.') || local_part.ends_with('.') {
2101 return false;
2102 }
2103
2104 if domain_part.is_empty()
2106 || domain_part.starts_with('.')
2107 || domain_part.ends_with('.')
2108 || domain_part.starts_with('-')
2109 || domain_part.ends_with('-')
2110 || !domain_part.contains('.')
2111 {
2112 return false;
2113 }
2114
2115 let domain_parts: Vec<&str> = domain_part.split('.').collect();
2117 if domain_parts.len() < 2 {
2118 return false;
2119 }
2120
2121 for part in domain_parts {
2123 if part.is_empty() {
2124 return false;
2125 }
2126 }
2127
2128 true
2129 }
2130
2131 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2133 tracing::debug!("Coordinating distributed sessions across instances");
2135
2136 let sessions_guard = self.sessions.read().await;
2137 let local_sessions = sessions_guard.len();
2138 drop(sessions_guard);
2139
2140 let coordination_stats = SessionCoordinationStats {
2142 local_active_sessions: local_sessions as u64,
2143 remote_active_sessions: self.estimate_remote_sessions().await?,
2144 synchronized_sessions: self.count_synchronized_sessions().await?,
2145 coordination_conflicts: 0, last_coordination_time: chrono::Utc::now(),
2147 };
2148
2149 self.broadcast_session_state().await?;
2151
2152 self.resolve_session_conflicts().await?;
2154
2155 tracing::info!(
2156 "Session coordination complete - Local: {}, Remote: {}, Synchronized: {}",
2157 coordination_stats.local_active_sessions,
2158 coordination_stats.remote_active_sessions,
2159 coordination_stats.synchronized_sessions
2160 );
2161
2162 Ok(coordination_stats)
2163 }
2164
2165 async fn estimate_remote_sessions(&self) -> Result<u64> {
2167 let sessions_guard = self.sessions.read().await;
2170 let local_count = sessions_guard.len() as u64;
2171
2172 let estimated_remote = local_count * 2;
2174
2175 tracing::debug!("Estimated remote sessions: {}", estimated_remote);
2176 Ok(estimated_remote)
2177 }
2178
2179 async fn count_synchronized_sessions(&self) -> Result<u64> {
2181 let sessions_guard = self.sessions.read().await;
2182
2183 let synchronized = sessions_guard
2185 .values()
2186 .filter(|session| {
2187 session.data.contains_key("last_sync_time")
2189 && session.data.contains_key("instance_id")
2190 })
2191 .count() as u64;
2192
2193 tracing::debug!("Synchronized sessions count: {}", synchronized);
2194 Ok(synchronized)
2195 }
2196
2197 async fn broadcast_session_state(&self) -> Result<()> {
2199 let sessions_guard = self.sessions.read().await;
2201
2202 for (session_id, session) in sessions_guard.iter() {
2203 tracing::trace!(
2205 "Broadcasting session state - ID: {}, User: {}, Last Activity: {}",
2206 session_id,
2207 session.user_id,
2208 session.last_activity
2209 );
2210 }
2211
2212 tracing::debug!(
2213 "Session state broadcast completed for {} sessions",
2214 sessions_guard.len()
2215 );
2216 Ok(())
2217 }
2218
2219 async fn resolve_session_conflicts(&self) -> Result<()> {
2221 let mut sessions_guard = self.sessions.write().await;
2223
2224 for (session_id, session) in sessions_guard.iter_mut() {
2226 if let Some(last_sync_value) = session.data.get("last_sync_time")
2227 && let Some(last_sync_str) = last_sync_value.as_str()
2228 && let Ok(sync_time) = last_sync_str.parse::<i64>()
2229 {
2230 let current_time = chrono::Utc::now().timestamp();
2231
2232 if current_time - sync_time > 300 {
2234 session.data.insert(
2236 "conflict_resolution".to_string(),
2237 serde_json::Value::String("resolved_by_timestamp".to_string()),
2238 );
2239
2240 tracing::warn!(
2241 "Resolved session conflict for session {} using timestamp priority",
2242 session_id
2243 );
2244 }
2245 }
2246 }
2247
2248 tracing::debug!("Session conflict resolution completed");
2249 Ok(())
2250 }
2251
2252 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2254 tracing::debug!("Synchronizing session: {}", session_id);
2256
2257 let mut sessions_guard = self.sessions.write().await;
2258
2259 if let Some(session) = sessions_guard.get_mut(session_id) {
2260 let current_time = chrono::Utc::now();
2262 session.data.insert(
2263 "last_sync_time".to_string(),
2264 serde_json::Value::String(current_time.timestamp().to_string()),
2265 );
2266 session.data.insert(
2267 "instance_id".to_string(),
2268 serde_json::Value::String(self.get_instance_id()),
2269 );
2270 session.data.insert(
2271 "sync_version".to_string(),
2272 serde_json::Value::String("1".to_string()),
2273 );
2274
2275 tracing::info!(
2277 "Session {} synchronized - User: {}, Instance: {}",
2278 session_id,
2279 session.user_id,
2280 self.get_instance_id()
2281 );
2282 } else {
2283 return Err(AuthError::validation(format!(
2284 "Session {} not found",
2285 session_id
2286 )));
2287 }
2288
2289 Ok(())
2290 }
2291
2292 fn get_instance_id(&self) -> String {
2294 format!("auth-instance-{}", &uuid::Uuid::new_v4().to_string()[..8])
2296 }
2297
2298 pub fn get_monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2333 self.monitoring_manager.clone()
2334 }
2335
2336 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2338 self.monitoring_manager.get_performance_metrics()
2339 }
2340
2341 pub async fn health_check(
2343 &self,
2344 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2345 self.monitoring_manager.health_check().await
2346 }
2347
2348 pub async fn export_prometheus_metrics(&self) -> String {
2350 self.monitoring_manager.export_prometheus_metrics().await
2351 }
2352 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2354 debug!("Creating role '{}'", role.name);
2355
2356 if role.name.is_empty() {
2358 return Err(AuthError::validation("Role name cannot be empty"));
2359 }
2360
2361 let mut checker = self.permission_checker.write().await;
2363 checker.add_role(role.clone());
2364
2365 info!("Role '{}' created", role.name);
2366 Ok(())
2367 }
2368
2369 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2371 debug!("Assigning role '{}' to user '{}'", role_name, user_id);
2372
2373 if user_id.is_empty() {
2375 return Err(AuthError::validation("User ID cannot be empty"));
2376 }
2377 if role_name.is_empty() {
2378 return Err(AuthError::validation("Role name cannot be empty"));
2379 }
2380
2381 let mut checker = self.permission_checker.write().await;
2383 checker.assign_role_to_user(user_id, role_name)?;
2384
2385 info!("Role '{}' assigned to user '{}'", role_name, user_id);
2386 Ok(())
2387 }
2388
2389 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2391 debug!(
2392 "Setting inheritance: '{}' inherits from '{}'",
2393 child_role, parent_role
2394 );
2395
2396 if child_role.is_empty() || parent_role.is_empty() {
2398 return Err(AuthError::validation("Role names cannot be empty"));
2399 }
2400
2401 let mut checker = self.permission_checker.write().await;
2403 checker.set_role_inheritance(child_role, parent_role)?;
2404
2405 info!(
2406 "Role inheritance set: '{}' inherits from '{}'",
2407 child_role, parent_role
2408 );
2409 Ok(())
2410 }
2411
2412 pub async fn revoke_permission(
2414 &self,
2415 user_id: &str,
2416 action: &str,
2417 resource: &str,
2418 ) -> Result<()> {
2419 debug!(
2420 "Revoking permission '{}:{}' from user '{}'",
2421 action, resource, user_id
2422 );
2423
2424 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2426 return Err(AuthError::validation(
2427 "User ID, action, and resource cannot be empty",
2428 ));
2429 }
2430
2431 let mut checker = self.permission_checker.write().await;
2433 let permission = Permission::new(action, resource);
2434 checker.remove_user_permission(user_id, &permission);
2435
2436 info!(
2437 "Permission '{}:{}' revoked from user '{}'",
2438 action, resource, user_id
2439 );
2440 Ok(())
2441 }
2442
2443 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2445 debug!("Checking if user '{}' has role '{}'", user_id, role_name);
2446
2447 if user_id.is_empty() || role_name.is_empty() {
2449 return Err(AuthError::validation(
2450 "User ID and role name cannot be empty",
2451 ));
2452 }
2453
2454 let checker = self.permission_checker.read().await;
2456 let has_role = checker.user_has_role(user_id, role_name);
2457
2458 debug!("User '{}' has role '{}': {}", user_id, role_name, has_role);
2459 Ok(has_role)
2460 }
2461
2462 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2464 debug!("Getting effective permissions for user '{}'", user_id);
2465
2466 if user_id.is_empty() {
2468 return Err(AuthError::validation("User ID cannot be empty"));
2469 }
2470
2471 let checker = self.permission_checker.read().await;
2473 let permissions = checker.get_effective_permissions(user_id);
2474
2475 debug!(
2476 "User '{}' has {} effective permissions",
2477 user_id,
2478 permissions.len()
2479 );
2480 Ok(permissions)
2481 }
2482
2483 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2485 debug!("Creating ABAC policy '{}'", name);
2486
2487 if name.is_empty() {
2489 return Err(AuthError::validation("Policy name cannot be empty"));
2490 }
2491 if description.is_empty() {
2492 return Err(AuthError::validation("Policy description cannot be empty"));
2493 }
2494
2495 let policy_data = serde_json::json!({
2497 "name": name,
2498 "description": description,
2499 "created_at": chrono::Utc::now(),
2500 "rules": [],
2501 "active": true
2502 });
2503
2504 let key = format!("abac:policy:{}", name);
2506 let policy_json = serde_json::to_vec(&policy_data)
2507 .map_err(|e| AuthError::validation(format!("Failed to serialize policy: {}", e)))?;
2508 self.storage.store_kv(&key, &policy_json, None).await?;
2509
2510 info!(
2511 "ABAC policy '{}' created with description: {}",
2512 name, description
2513 );
2514 Ok(())
2515 }
2516
2517 pub async fn map_user_attribute(
2519 &self,
2520 user_id: &str,
2521 attribute: &str,
2522 value: &str,
2523 ) -> Result<()> {
2524 debug!(
2525 "Mapping attribute '{}' = '{}' for user '{}'",
2526 attribute, value, user_id
2527 );
2528
2529 if user_id.is_empty() || attribute.is_empty() {
2531 return Err(AuthError::validation(
2532 "User ID and attribute name cannot be empty",
2533 ));
2534 }
2535
2536 let attrs_key = format!("user:{}:attributes", user_id);
2538 let mut user_attrs = if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2539 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2540 .unwrap_or_default()
2541 } else {
2542 std::collections::HashMap::new()
2543 };
2544
2545 user_attrs.insert(attribute.to_string(), value.to_string());
2546
2547 let attrs_json = serde_json::to_vec(&user_attrs)
2548 .map_err(|e| AuthError::validation(format!("Failed to serialize attributes: {}", e)))?;
2549 self.storage.store_kv(&attrs_key, &attrs_json, None).await?;
2550
2551 info!("Attribute '{}' mapped for user '{}'", attribute, user_id);
2552 Ok(())
2553 }
2554
2555 pub async fn get_user_attribute(
2557 &self,
2558 user_id: &str,
2559 attribute: &str,
2560 ) -> Result<Option<String>> {
2561 debug!("Getting attribute '{}' for user '{}'", attribute, user_id);
2562
2563 if user_id.is_empty() || attribute.is_empty() {
2565 return Err(AuthError::validation(
2566 "User ID and attribute name cannot be empty",
2567 ));
2568 }
2569
2570 let attrs_key = format!("user:{}:attributes", user_id);
2572 if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2573 let user_attrs: std::collections::HashMap<String, String> =
2574 serde_json::from_slice(&attrs_data).unwrap_or_default();
2575 Ok(user_attrs.get(attribute).cloned())
2576 } else {
2577 Ok(None)
2578 }
2579 }
2580
2581 pub async fn check_dynamic_permission(
2583 &self,
2584 user_id: &str,
2585 action: &str,
2586 resource: &str,
2587 context: std::collections::HashMap<String, String>,
2588 ) -> Result<bool> {
2589 debug!(
2590 "Checking dynamic permission for user '{}': {}:{} with context: {:?}",
2591 user_id, action, resource, context
2592 );
2593
2594 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2596 return Err(AuthError::validation(
2597 "User ID, action, and resource cannot be empty",
2598 ));
2599 }
2600
2601 let user_attrs_key = format!("user:{}:attributes", user_id);
2603 let user_attrs = if let Some(attrs_data) = self.storage.get_kv(&user_attrs_key).await? {
2604 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2605 .unwrap_or_default()
2606 } else {
2607 std::collections::HashMap::new()
2608 };
2609
2610 let mut permission_granted = false;
2612
2613 let mut checker = self.permission_checker.write().await;
2615 let permission = Permission::new(action, resource);
2616 if checker
2617 .check_permission(user_id, &permission)
2618 .unwrap_or(false)
2619 {
2620 permission_granted = true;
2621 }
2622 drop(checker);
2623
2624 if permission_granted {
2626 if let Some(time_restriction) = context.get("time_restriction") {
2628 let current_hour = chrono::Utc::now()
2629 .format("%H")
2630 .to_string()
2631 .parse::<u32>()
2632 .unwrap_or(0);
2633 if time_restriction == "business_hours" && !(9..=17).contains(¤t_hour) {
2634 permission_granted = false;
2635 debug!("Access denied: outside business hours");
2636 }
2637 }
2638
2639 if let Some(required_location) = context.get("required_location")
2641 && let Some(user_location) = user_attrs.get("location")
2642 && user_location != required_location
2643 {
2644 permission_granted = false;
2645 debug!(
2646 "Access denied: user location {} != required {}",
2647 user_location, required_location
2648 );
2649 }
2650
2651 if let Some(required_clearance) = context.get("required_clearance")
2653 && let Some(user_clearance) = user_attrs.get("clearance_level")
2654 {
2655 let required_level = required_clearance.parse::<u32>().unwrap_or(0);
2656 let user_level = user_clearance.parse::<u32>().unwrap_or(0);
2657 if user_level < required_level {
2658 permission_granted = false;
2659 debug!(
2660 "Access denied: user clearance {} < required {}",
2661 user_level, required_level
2662 );
2663 }
2664 }
2665 }
2666
2667 debug!(
2668 "Dynamic permission check result for user '{}': {}",
2669 user_id, permission_granted
2670 );
2671 Ok(permission_granted)
2672 }
2673
2674 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2676 debug!("Creating resource '{}'", resource);
2677
2678 if resource.is_empty() {
2680 return Err(AuthError::validation("Resource name cannot be empty"));
2681 }
2682
2683 let resource_data = serde_json::json!({
2685 "name": resource,
2686 "created_at": chrono::Utc::now(),
2687 "active": true
2688 });
2689
2690 let key = format!("resource:{}", resource);
2691 let resource_json = serde_json::to_vec(&resource_data)
2692 .map_err(|e| AuthError::validation(format!("Failed to serialize resource: {}", e)))?;
2693 self.storage.store_kv(&key, &resource_json, None).await?;
2694
2695 info!("Resource '{}' created", resource);
2696 Ok(())
2697 }
2698
2699 pub async fn delegate_permission(
2701 &self,
2702 delegator_id: &str,
2703 delegatee_id: &str,
2704 action: &str,
2705 resource: &str,
2706 duration: std::time::Duration,
2707 ) -> Result<()> {
2708 debug!(
2709 "Delegating permission '{}:{}' from '{}' to '{}' for {:?}",
2710 action, resource, delegator_id, delegatee_id, duration
2711 );
2712
2713 if delegator_id.is_empty()
2715 || delegatee_id.is_empty()
2716 || action.is_empty()
2717 || resource.is_empty()
2718 {
2719 return Err(AuthError::validation(
2720 "All delegation parameters cannot be empty",
2721 ));
2722 }
2723
2724 let permission = Permission::new(action, resource);
2726 let mut checker = self.permission_checker.write().await;
2727 if !checker
2728 .check_permission(delegator_id, &permission)
2729 .unwrap_or(false)
2730 {
2731 return Err(AuthError::authorization(
2732 "Delegator does not have the permission to delegate",
2733 ));
2734 }
2735 drop(checker);
2736
2737 let delegation_id = uuid::Uuid::new_v4().to_string();
2739 let expires_at = std::time::SystemTime::now() + duration;
2740 let delegation_data = serde_json::json!({
2741 "id": delegation_id,
2742 "delegator_id": delegator_id,
2743 "delegatee_id": delegatee_id,
2744 "action": action,
2745 "resource": resource,
2746 "created_at": chrono::Utc::now(),
2747 "expires_at": expires_at.duration_since(std::time::UNIX_EPOCH)
2748 .unwrap_or_else(|e| {
2749 error!("System time error during delegation creation: {}", e);
2750 Duration::from_secs(0)
2751 })
2752 .as_secs()
2753 });
2754
2755 let key = format!("delegation:{}", delegation_id);
2757 let delegation_json = serde_json::to_vec(&delegation_data)
2758 .map_err(|e| AuthError::validation(format!("Failed to serialize delegation: {}", e)))?;
2759 self.storage
2760 .store_kv(&key, &delegation_json, Some(duration))
2761 .await?;
2762
2763 info!(
2764 "Permission '{}:{}' delegated from '{}' to '{}' for {:?}",
2765 action, resource, delegator_id, delegatee_id, duration
2766 );
2767 Ok(())
2768 }
2769
2770 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2772 debug!("Getting active delegations for user '{}'", user_id);
2773
2774 if user_id.is_empty() {
2776 return Err(AuthError::validation("User ID cannot be empty"));
2777 }
2778
2779 let delegations = vec![
2782 format!("read:document:delegated_to_{}", user_id),
2783 format!("write:report:delegated_to_{}", user_id),
2784 ];
2785
2786 debug!(
2787 "Found {} active delegations for user '{}'",
2788 delegations.len(),
2789 user_id
2790 );
2791 Ok(delegations)
2792 }
2793
2794 pub async fn get_permission_audit_logs(
2796 &self,
2797 user_id: Option<&str>,
2798 action: Option<&str>,
2799 resource: Option<&str>,
2800 limit: Option<usize>,
2801 ) -> Result<Vec<String>> {
2802 debug!(
2803 "Getting permission audit logs with filters - user: {:?}, action: {:?}, resource: {:?}, limit: {:?}",
2804 user_id, action, resource, limit
2805 );
2806
2807 use crate::audit::{AuditEventType, AuditQuery, SortOrder};
2808
2809 let query = AuditQuery {
2812 event_types: Some(vec![
2813 AuditEventType::PermissionGranted,
2814 AuditEventType::PermissionDenied,
2815 AuditEventType::RoleAssigned,
2816 AuditEventType::RoleRevoked,
2817 AuditEventType::RoleCreated,
2818 AuditEventType::RoleUpdated,
2819 AuditEventType::RoleDeleted,
2820 ]),
2821 user_id: user_id.map(str::to_string),
2822 risk_level: None,
2823 outcome: None,
2824 time_range: None,
2825 ip_address: None,
2826 resource_type: None,
2827 actor_id: None,
2828 correlation_id: None,
2829 limit: None,
2830 offset: None,
2831 sort_order: SortOrder::TimestampDesc,
2832 };
2833
2834 let action = action.map(str::to_lowercase);
2835 let mut logs: Vec<String> = self
2836 .audit_manager
2837 .query_events(&query)
2838 .await?
2839 .into_iter()
2840 .filter(|e| {
2841 action.as_deref().is_none_or(|a| {
2842 e.description.to_lowercase().contains(a)
2843 || e.details.values().any(|v| v.to_lowercase().contains(a))
2844 })
2845 })
2846 .filter(|e| {
2847 resource.is_none_or(|r| {
2848 e.resource
2849 .as_ref()
2850 .is_some_and(|ri| ri.resource_type == r || ri.resource_id == r)
2851 })
2852 })
2853 .map(|e| {
2854 let ts =
2855 chrono::DateTime::<chrono::Utc>::from(e.timestamp).format("%Y-%m-%dT%H:%M:%SZ");
2856 format!(
2857 "{} - {:?} user={} outcome={:?} - {}",
2858 ts,
2859 e.event_type,
2860 e.user_id.as_deref().unwrap_or("system"),
2861 e.outcome,
2862 e.description
2863 )
2864 })
2865 .collect();
2866
2867 if let Some(limit_value) = limit {
2868 logs.truncate(limit_value);
2869 }
2870
2871 debug!("Retrieved {} audit log entries", logs.len());
2872 Ok(logs)
2873 }
2874
2875 pub async fn get_permission_metrics(
2877 &self,
2878 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2879 debug!("Getting permission metrics");
2880
2881 let mut metrics = std::collections::HashMap::new();
2882
2883 metrics.insert("total_users_with_permissions".to_string(), 150u64);
2885 metrics.insert("total_roles".to_string(), 25u64);
2886 metrics.insert("total_permissions".to_string(), 500u64);
2887 metrics.insert("active_delegations".to_string(), 12u64);
2888 metrics.insert("abac_policies".to_string(), 8u64);
2889 metrics.insert("permission_checks_last_hour".to_string(), 1250u64);
2890
2891 debug!("Retrieved {} permission metrics", metrics.len());
2892 Ok(metrics)
2893 }
2894
2895 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2898 let now = std::time::SystemTime::now();
2899 let _twenty_four_hours_ago = now - std::time::Duration::from_secs(24 * 60 * 60);
2900
2901 let sessions_guard = self.sessions.read().await;
2903 let active_sessions = sessions_guard.len() as u64;
2904 drop(sessions_guard);
2905
2906 let failed_logins_24h = self
2908 .audit_manager
2909 .get_failed_login_count_24h()
2910 .await
2911 .unwrap_or(0);
2912 let successful_logins_24h = self
2913 .audit_manager
2914 .get_successful_login_count_24h()
2915 .await
2916 .unwrap_or(active_sessions * 2);
2917 let token_issued_24h = self
2918 .audit_manager
2919 .get_token_issued_count_24h()
2920 .await
2921 .unwrap_or(active_sessions * 3);
2922
2923 let unique_users_24h = self
2925 .audit_manager
2926 .get_unique_users_24h()
2927 .await
2928 .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
2929
2930 let password_resets_24h = self
2932 .audit_manager
2933 .get_password_reset_count_24h()
2934 .await
2935 .unwrap_or(0);
2936 let admin_actions_24h = self
2937 .audit_manager
2938 .get_admin_action_count_24h()
2939 .await
2940 .unwrap_or(0);
2941 let security_alerts_24h = self
2942 .audit_manager
2943 .get_security_alert_count_24h()
2944 .await
2945 .unwrap_or(0);
2946
2947 Ok(SecurityAuditStats {
2948 active_sessions,
2949 failed_logins_24h,
2950 successful_logins_24h,
2951 unique_users_24h,
2952 token_issued_24h,
2953 password_resets_24h,
2954 admin_actions_24h,
2955 security_alerts_24h,
2956 collection_timestamp: chrono::Utc::now(),
2957 })
2958 }
2959
2960 pub async fn get_user_profile(&self, user_id: &str) -> Result<crate::providers::UserProfile> {
2962 if let Ok(Some(_session)) = self.storage.get_session(user_id).await {
2964 return Ok(crate::providers::UserProfile {
2966 id: Some(user_id.to_string()),
2967 provider: Some("local".to_string()),
2968 username: Some(format!("user_{}", user_id)),
2969 name: Some("User".to_string()),
2970 email: Some(format!("{}@example.com", user_id)),
2971 email_verified: Some(false),
2972 picture: None,
2973 locale: None,
2974 additional_data: std::collections::HashMap::new(),
2975 });
2976 }
2977
2978 Ok(crate::providers::UserProfile {
2980 id: Some(user_id.to_string()),
2981 provider: Some("local".to_string()),
2982 username: Some(format!("user_{}", user_id)),
2983 name: Some("Unknown User".to_string()),
2984 email: Some(format!("{}@example.com", user_id)),
2985 email_verified: Some(false),
2986 picture: None,
2987 locale: None,
2988 additional_data: std::collections::HashMap::new(),
2989 })
2990 }
2991}
2992
2993#[derive(Debug, Clone, Serialize, Deserialize)]
2996pub struct SecurityAuditStats {
2997 pub active_sessions: u64,
2998 pub failed_logins_24h: u64,
2999 pub successful_logins_24h: u64,
3000 pub unique_users_24h: u64,
3001 pub token_issued_24h: u64,
3002 pub password_resets_24h: u64,
3003 pub admin_actions_24h: u64,
3004 pub security_alerts_24h: u64,
3005 pub collection_timestamp: chrono::DateTime<chrono::Utc>,
3006}
3007
3008impl SecurityAuditStats {
3009 pub fn security_score(&self) -> f64 {
3012 let mut score = 1.0;
3013
3014 if self.successful_logins_24h > 0 {
3016 let failure_rate = self.failed_logins_24h as f64
3017 / (self.successful_logins_24h + self.failed_logins_24h) as f64;
3018 if failure_rate > 0.1 {
3019 score -= failure_rate * 0.3;
3020 } }
3022
3023 if self.security_alerts_24h > 0 {
3025 score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
3026 }
3027
3028 if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
3030 score += 0.05;
3031 }
3032
3033 score.clamp(0.0, 1.0)
3034 }
3035
3036 pub fn requires_immediate_attention(&self) -> bool {
3063 self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3 }
3067
3068 pub fn security_alert_message(&self) -> Option<String> {
3097 if !self.requires_immediate_attention() {
3098 return None;
3099 }
3100
3101 let mut alerts = Vec::new();
3102
3103 if self.failed_logins_24h > 100 {
3104 alerts.push(format!(
3105 "High failed login attempts: {}",
3106 self.failed_logins_24h
3107 ));
3108 }
3109
3110 if self.security_alerts_24h > 5 {
3111 alerts.push(format!(
3112 "Multiple security alerts: {}",
3113 self.security_alerts_24h
3114 ));
3115 }
3116
3117 if self.security_score() < 0.3 {
3118 alerts.push(format!(
3119 "Critical security score: {:.2}",
3120 self.security_score()
3121 ));
3122 }
3123
3124 Some(format!(
3125 "🚨 SECURITY ATTENTION REQUIRED: {}",
3126 alerts.join(", ")
3127 ))
3128 }
3129}
3130
3131#[derive(Debug)]
3133pub struct SessionCoordinationStats {
3134 pub local_active_sessions: u64,
3135 pub remote_active_sessions: u64,
3136 pub synchronized_sessions: u64,
3137 pub coordination_conflicts: u64,
3138 pub last_coordination_time: chrono::DateTime<chrono::Utc>,
3139}
3140
3141#[derive(Debug, Clone, Default)]
3143pub struct AuthStats {
3144 pub registered_methods: Vec<String>,
3146
3147 pub active_sessions: u64,
3149
3150 pub active_mfa_challenges: u64,
3152
3153 pub tokens_issued: u64,
3155
3156 pub auth_attempts: u64,
3158}
3159
3160#[cfg(test)]
3161mod tests {
3162 use super::*;
3163 use crate::config::{AuthConfig, SecurityConfig};
3164 #[tokio::test]
3165 async fn test_framework_initialization() {
3166 let config = AuthConfig::new().security(SecurityConfig {
3167 min_password_length: 8,
3168 require_password_complexity: false,
3169 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3170 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3171 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3172 secure_cookies: false,
3173 cookie_same_site: crate::config::CookieSameSite::Lax,
3174 csrf_protection: false,
3175 session_timeout: Duration::from_secs(3600),
3176 });
3177 let mut framework = AuthFramework::new(config);
3178
3179 assert!(framework.initialize().await.is_ok());
3180 assert!(framework.initialized);
3181 }
3182
3183 #[tokio::test]
3192 async fn test_verify_totp_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
3193 let config = AuthConfig::new()
3194 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3195 let mut framework = AuthFramework::new(config);
3196 framework.initialize().await.unwrap();
3197 let user_id = "totp_facade_unenrolled_user";
3198
3199 use sha2::{Digest, Sha256};
3200 let mut hasher = Sha256::new();
3201 hasher.update(user_id.as_bytes());
3202 hasher.update(b"totp_secret_salt_2024");
3203 let hash = hasher.finalize();
3204 let would_be_derived_secret =
3205 base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
3206
3207 let code_for_derived_secret = framework
3208 .generate_totp_code(&would_be_derived_secret)
3209 .await
3210 .unwrap();
3211
3212 assert!(
3213 !framework
3214 .verify_totp_code(user_id, &code_for_derived_secret)
3215 .await
3216 .unwrap(),
3217 "an unenrolled user must not be verifiable via the old predictable fallback secret"
3218 );
3219 }
3220
3221 #[tokio::test]
3226 async fn test_generate_totp_secret_then_verify_totp_code_round_trips() {
3227 let config = AuthConfig::new()
3228 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3229 let mut framework = AuthFramework::new(config);
3230 framework.initialize().await.unwrap();
3231 let user_id = "totp_facade_enrolled_user";
3232
3233 let secret = framework.generate_totp_secret(user_id).await.unwrap();
3234 let code = framework.generate_totp_code(&secret).await.unwrap();
3235
3236 assert!(
3237 framework.verify_totp_code(user_id, &code).await.unwrap(),
3238 "a code generated from a properly enrolled secret must verify"
3239 );
3240 }
3241
3242 #[tokio::test]
3243 async fn test_method_registration() {
3244 let config = AuthConfig::new().security(SecurityConfig {
3249 min_password_length: 8,
3250 require_password_complexity: false,
3251 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3252 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3253 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3254 secure_cookies: false,
3255 cookie_same_site: crate::config::CookieSameSite::Lax,
3256 csrf_protection: false,
3257 session_timeout: Duration::from_secs(3600),
3258 });
3259 let framework = AuthFramework::new(config);
3260
3261 assert!(!framework.initialized);
3263
3264 }
3267
3268 #[tokio::test]
3269 async fn test_token_validation() {
3270 let config = AuthConfig::new().security(SecurityConfig {
3271 min_password_length: 8,
3272 require_password_complexity: false,
3273 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3274 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3275 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3276 secure_cookies: false,
3277 cookie_same_site: crate::config::CookieSameSite::Lax,
3278 csrf_protection: false,
3279 session_timeout: Duration::from_secs(3600),
3280 });
3281 let mut framework = AuthFramework::new(config);
3282 framework.initialize().await.unwrap();
3283
3284 let token = framework
3285 .token_manager
3286 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
3287 .unwrap();
3288
3289 framework.storage.store_token(&token).await.unwrap();
3291
3292 assert!(framework.validate_token(&token).await.unwrap());
3293 }
3294
3295 #[tokio::test]
3296 async fn test_session_management() {
3297 let config = AuthConfig::new().security(SecurityConfig {
3298 min_password_length: 8,
3299 require_password_complexity: false,
3300 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3301 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3302 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3303 secure_cookies: false,
3304 cookie_same_site: crate::config::CookieSameSite::Lax,
3305 csrf_protection: false,
3306 session_timeout: Duration::from_secs(3600),
3307 });
3308 let mut framework = AuthFramework::new(config);
3309 framework.initialize().await.unwrap();
3310
3311 let session_id = framework
3312 .create_session(
3313 "test-user",
3314 Duration::from_secs(3600),
3315 Some("192.168.1.1".to_string()),
3316 Some("Test Agent".to_string()),
3317 )
3318 .await
3319 .unwrap();
3320
3321 let session = framework.get_session(&session_id).await.unwrap();
3322 assert!(session.is_some());
3323
3324 framework.delete_session(&session_id).await.unwrap();
3325 let session = framework.get_session(&session_id).await.unwrap();
3326 assert!(session.is_none());
3327 }
3328
3329 #[tokio::test]
3330 async fn test_cleanup_expired_data() {
3331 let config = AuthConfig::new().security(SecurityConfig {
3332 min_password_length: 8,
3333 require_password_complexity: false,
3334 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3335 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3336 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3337 secure_cookies: false,
3338 cookie_same_site: crate::config::CookieSameSite::Lax,
3339 csrf_protection: false,
3340 session_timeout: Duration::from_secs(3600),
3341 });
3342 let mut framework = AuthFramework::new(config);
3343 framework.initialize().await.unwrap();
3344
3345 assert!(framework.cleanup_expired_data().await.is_ok());
3347 }
3348}
3349
3350#[cfg(test)]
3351mod permission_audit_log_tests {
3352 use super::*;
3353 use crate::audit::{RequestMetadata, ResourceInfo};
3354 use std::collections::HashMap;
3355
3356 fn framework() -> AuthFramework {
3357 AuthFramework::new(
3358 AuthConfig::new().secret("test-secret-with-at-least-32-characters".to_string()),
3359 )
3360 }
3361
3362 fn meta() -> RequestMetadata {
3363 RequestMetadata {
3364 ip_address: None,
3365 user_agent: None,
3366 request_id: None,
3367 endpoint: None,
3368 http_method: None,
3369 geolocation: None,
3370 device_info: None,
3371 }
3372 }
3373
3374 fn resource(kind: &str) -> ResourceInfo {
3375 ResourceInfo {
3376 resource_type: kind.to_string(),
3377 resource_id: format!("{kind}-1"),
3378 resource_name: None,
3379 attributes: HashMap::new(),
3380 }
3381 }
3382
3383 #[tokio::test]
3386 async fn empty_audit_log_returns_no_entries() {
3387 let fw = framework();
3388 let logs = fw
3389 .get_permission_audit_logs(None, None, None, None)
3390 .await
3391 .unwrap();
3392 assert!(logs.is_empty(), "fabricated entries returned: {logs:?}");
3393 }
3394
3395 #[tokio::test]
3396 async fn returns_recorded_events_and_applies_filters() {
3397 let fw = framework();
3398 fw.audit_manager
3399 .log_permission_denied("alice", resource("document"), "read", meta())
3400 .await
3401 .unwrap();
3402 fw.audit_manager
3403 .log_permission_denied("bob", resource("invoice"), "write", meta())
3404 .await
3405 .unwrap();
3406
3407 let all = fw
3408 .get_permission_audit_logs(None, None, None, None)
3409 .await
3410 .unwrap();
3411 assert_eq!(all.len(), 2, "{all:?}");
3412 assert!(all.iter().all(|l| l.contains("user=")));
3413
3414 let alice = fw
3415 .get_permission_audit_logs(Some("alice"), None, None, None)
3416 .await
3417 .unwrap();
3418 assert_eq!(alice.len(), 1, "{alice:?}");
3419 assert!(alice[0].contains("user=alice") && alice[0].contains("document"));
3420
3421 let by_action = fw
3422 .get_permission_audit_logs(None, Some("WRITE"), None, None)
3423 .await
3424 .unwrap();
3425 assert_eq!(by_action.len(), 1, "{by_action:?}");
3426 assert!(by_action[0].contains("user=bob"));
3427
3428 let by_resource = fw
3429 .get_permission_audit_logs(None, None, Some("document"), None)
3430 .await
3431 .unwrap();
3432 assert_eq!(by_resource.len(), 1, "{by_resource:?}");
3433
3434 let limited = fw
3435 .get_permission_audit_logs(None, None, None, Some(1))
3436 .await
3437 .unwrap();
3438 assert_eq!(limited.len(), 1);
3439 }
3440}