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!(
882 "Session '{}' deleted",
883 crate::utils::redact::fingerprint(session_id)
884 );
885 Ok(())
886 }
887
888 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
890 self.storage.list_user_tokens(user_id).await
891 }
892
893 pub async fn cleanup_expired_data(&self) -> Result<()> {
895 debug!("Cleaning up expired data");
896
897 self.storage.cleanup_expired().await?;
899
900 {
902 let mut challenges = self.mfa_challenges.write().await;
903 let now = chrono::Utc::now();
904 challenges.retain(|_, challenge| challenge.expires_at > now);
905 }
906
907 {
909 let mut sessions = self.sessions.write().await;
910 let now = chrono::Utc::now();
911 sessions.retain(|_, session| session.expires_at > now);
912 }
913
914 if let Some(ref rate_limiter) = self.rate_limiter {
916 rate_limiter.cleanup();
917 }
918
919 Ok(())
920 }
921
922 fn is_production_environment(&self) -> bool {
927 if let Ok(env) = std::env::var("ENVIRONMENT")
929 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
930 {
931 return true;
932 }
933
934 if let Ok(env) = std::env::var("ENV")
935 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
936 {
937 return true;
938 }
939
940 if let Ok(env) = std::env::var("NODE_ENV")
941 && env.to_lowercase() == "production"
942 {
943 return true;
944 }
945
946 if let Ok(env) = std::env::var("RUST_ENV")
947 && env.to_lowercase() == "production"
948 {
949 return true;
950 }
951
952 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
954 return true; }
956
957 if std::env::var("DOCKER_CONTAINER").is_ok() {
958 return true; }
960
961 false
963 }
964
965 pub async fn get_stats(&self) -> Result<AuthStats> {
967 let mut stats = AuthStats::default();
968
969 let storage = &*self.storage;
971
972 let mut user_token_counts: HashMap<String, u32> = HashMap::new();
974 let mut total_tokens = 0u32;
975 let mut expired_tokens = 0u32;
976 let active_sessions: u32;
977 let failed_attempts: u32;
978 let successful_attempts: u32;
979
980 if let Err(e) = storage.cleanup_expired().await {
982 warn!("Failed to cleanup expired data: {}", e);
983 }
984
985 {
987 let sessions_guard = self.sessions.read().await;
988 let total_sessions = sessions_guard.len() as u32;
989
990 let now = chrono::Utc::now();
992 active_sessions = sessions_guard
993 .values()
994 .filter(|session| session.expires_at > now)
995 .count() as u32;
996
997 info!(
998 "Total sessions: {}, Active sessions: {}",
999 total_sessions, active_sessions
1000 );
1001 }
1002
1003 for method_name in self.methods.keys() {
1008 info!("Collecting statistics for method: {}", method_name);
1010 }
1011
1012 {
1015 let sessions = self.sessions.read().await;
1016 let now = chrono::Utc::now();
1017
1018 for (session_id, session_data) in sessions.iter() {
1019 if session_data.expires_at > now {
1020 total_tokens += 1;
1021
1022 let count = user_token_counts
1024 .entry(session_data.user_id.clone())
1025 .or_insert(0);
1026 *count += 1;
1027 } else {
1028 expired_tokens += 1;
1029 }
1030
1031 info!(
1032 "Session {} for user {} expires at {}",
1033 crate::utils::redact::fingerprint(session_id),
1034 session_data.user_id,
1035 session_data.expires_at
1036 );
1037 }
1038 }
1039
1040 info!(
1046 "Token statistics - Total: {}, Expired: {}, Active: {}",
1047 total_tokens,
1048 expired_tokens,
1049 total_tokens.saturating_sub(expired_tokens)
1050 );
1051
1052 if let Some(rate_limiter) = &self.rate_limiter {
1054 rate_limiter.cleanup();
1057
1058 failed_attempts = self.get_failed_attempts_from_audit_log().await.unwrap_or(0);
1060 successful_attempts = self
1061 .get_successful_attempts_from_audit_log()
1062 .await
1063 .unwrap_or(0);
1064
1065 let test_key = "auth:password:127.0.0.1";
1067 let remaining = rate_limiter.remaining_requests(test_key);
1068
1069 info!(
1070 "Rate limiter active - remaining requests for test key: {}",
1071 remaining
1072 );
1073
1074 info!(
1075 "Authentication attempts - Failed: {}, Successful: {}",
1076 failed_attempts, successful_attempts
1077 );
1078 } else {
1079 warn!("Rate limiter not configured - authentication attempt statistics unavailable");
1080 failed_attempts = self.estimate_failed_attempts().await;
1082 successful_attempts = self.estimate_successful_attempts().await;
1083 }
1084
1085 user_token_counts.insert("total_tokens".to_string(), total_tokens);
1086 user_token_counts.insert("expired_tokens".to_string(), expired_tokens);
1087 user_token_counts.insert("active_sessions".to_string(), active_sessions);
1088 user_token_counts.insert("failed_attempts".to_string(), failed_attempts);
1089 user_token_counts.insert("successful_attempts".to_string(), successful_attempts);
1090
1091 for method in self.methods.keys() {
1092 stats.registered_methods.push(method.clone());
1093 }
1094
1095 stats.active_sessions = active_sessions as u64;
1097 stats.active_mfa_challenges = self.mfa_challenges.read().await.len() as u64;
1098
1099 stats.tokens_issued = total_tokens as u64;
1101 stats.auth_attempts = (successful_attempts + failed_attempts) as u64;
1102
1103 Ok(stats)
1104 }
1105
1106 pub fn token_manager(&self) -> &TokenManager {
1108 &self.token_manager
1109 }
1110
1111 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1113 debug!("Validating username format: '{}'", username);
1114
1115 let is_valid = username.len() >= 3
1117 && username.len() <= 32
1118 && username
1119 .chars()
1120 .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
1121
1122 Ok(is_valid)
1123 }
1124
1125 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1127 debug!("Validating display name format");
1128
1129 let is_valid = !display_name.is_empty()
1130 && display_name.len() <= 100
1131 && !display_name.trim().is_empty();
1132
1133 Ok(is_valid)
1134 }
1135
1136 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1141 debug!("Validating password strength");
1142
1143 let strength = crate::utils::password::check_password_strength(password);
1144
1145 let required_strength = crate::utils::password::PasswordStrengthLevel::Strong;
1148
1149 let is_valid = match required_strength {
1151 crate::utils::password::PasswordStrengthLevel::Weak => {
1152 !password.is_empty()
1154 }
1155 crate::utils::password::PasswordStrengthLevel::Medium => !matches!(
1156 strength.level,
1157 crate::utils::password::PasswordStrengthLevel::Weak
1158 ),
1159 crate::utils::password::PasswordStrengthLevel::Strong => {
1160 matches!(
1161 strength.level,
1162 crate::utils::password::PasswordStrengthLevel::Strong
1163 | crate::utils::password::PasswordStrengthLevel::VeryStrong
1164 )
1165 }
1166 crate::utils::password::PasswordStrengthLevel::VeryStrong => {
1167 matches!(
1168 strength.level,
1169 crate::utils::password::PasswordStrengthLevel::VeryStrong
1170 )
1171 }
1172 };
1173
1174 if !is_valid {
1175 warn!(
1176 "Password validation failed - Required: {:?}, Actual: {:?}, Feedback: {}",
1177 required_strength,
1178 strength.level,
1179 strength.feedback.join(", ")
1180 );
1181 } else {
1182 debug!("Password strength validation passed: {:?}", strength.level);
1183 }
1184
1185 Ok(is_valid)
1186 }
1187
1188 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1190 debug!("Validating user input");
1191
1192 let is_valid = !input.contains('<')
1194 && !input.contains('>')
1195 && !input.contains("script")
1196 && !input.contains("javascript:")
1197 && !input.contains("data:")
1198 && !input.contains("file:")
1199 && !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;
1212
1213 Ok(is_valid)
1214 }
1215
1216 pub async fn create_auth_token(
1220 &self,
1221 user_id: impl Into<String>,
1222 scopes: Vec<String>,
1223 method_name: impl Into<String>,
1224 lifetime: Option<Duration>,
1225 ) -> Result<AuthToken> {
1226 let method_name = method_name.into();
1227 let user_id = user_id.into();
1228
1229 let auth_method = self
1231 .methods
1232 .get(&method_name)
1233 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1234
1235 auth_method.validate_config()?;
1237
1238 let jwt_token = self
1240 .token_manager
1241 .create_jwt_token(&user_id, scopes.clone(), lifetime)?;
1242
1243 let token = AuthToken::new(
1245 user_id.clone(),
1246 jwt_token,
1247 lifetime.unwrap_or(Duration::from_secs(3600)),
1248 &method_name,
1249 )
1250 .with_scopes(scopes);
1251
1252 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1254 const MAX_TOKENS_PER_USER: usize = 100;
1255 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1256 warn!(
1257 "User '{}' has reached maximum tokens ({})",
1258 user_id, MAX_TOKENS_PER_USER
1259 );
1260 return Err(AuthError::rate_limit(
1261 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1262 ));
1263 }
1264
1265 self.storage.store_token(&token).await?;
1267
1268 self.monitoring_manager
1270 .record_token_creation(&method_name)
1271 .await;
1272
1273 Ok(token)
1274 }
1275
1276 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1278 debug!("Initiating SMS challenge for user: {}", user_id);
1279
1280 if user_id.is_empty() {
1282 return Err(AuthError::InvalidInput(
1283 "User ID cannot be empty".to_string(),
1284 ));
1285 }
1286
1287 let challenge_id = crate::utils::string::generate_id(Some("sms"));
1288
1289 info!("SMS challenge initiated for user '{}'", user_id);
1290 Ok(challenge_id)
1291 }
1292
1293 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1295 debug!("Verifying SMS code for challenge: {}", challenge_id);
1296
1297 if challenge_id.is_empty() {
1299 return Err(AuthError::InvalidInput(
1300 "Challenge ID cannot be empty".to_string(),
1301 ));
1302 }
1303
1304 if code.is_empty() {
1305 return Err(AuthError::InvalidInput(
1306 "SMS code cannot be empty".to_string(),
1307 ));
1308 }
1309
1310 let sms_key = format!("sms_challenge:{}:code", challenge_id);
1312 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1313 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1314
1315 let is_valid_format = code.len() == 6 && code.chars().all(|c| c.is_ascii_digit());
1317
1318 if !is_valid_format {
1319 return Ok(false);
1320 }
1321
1322 let result = Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1325 Ok(result)
1326 } else {
1327 Err(AuthError::InvalidInput(
1329 "Invalid or expired challenge ID".to_string(),
1330 ))
1331 }
1332 }
1333
1334 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1336 debug!("Registering email for user: {}", user_id);
1337
1338 if !Self::is_valid_email_format(email) {
1340 return Err(AuthError::validation("Invalid email format"));
1341 }
1342
1343 let storage = &*self.storage;
1345
1346 let user_key = format!("user:{}:email", user_id);
1349
1350 let email_bytes = email.as_bytes();
1352 match storage.store_kv(&user_key, email_bytes, None).await {
1353 Ok(()) => {
1354 info!(
1355 "Successfully registered email {} for user {}",
1356 email, user_id
1357 );
1358 Ok(())
1359 }
1360 Err(e) => {
1361 error!("Failed to store email for user {}: {}", user_id, e);
1362 Err(e)
1363 }
1364 }
1365 }
1366
1367 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1371 debug!("Generating TOTP secret for user '{}'", user_id);
1372
1373 let rng = ring::rand::SystemRandom::new();
1377 let mut raw_bytes = [0u8; 20];
1378 ring::rand::SecureRandom::fill(&rng, &mut raw_bytes)
1379 .map_err(|_| AuthError::internal("Failed to generate random bytes for TOTP secret"))?;
1380 let secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &raw_bytes);
1381
1382 let key = format!("user:{}:totp_secret", user_id);
1383 self.storage.store_kv(&key, secret.as_bytes(), None).await?;
1384
1385 info!("TOTP secret generated for user '{}'", user_id);
1386
1387 Ok(secret)
1388 }
1389
1390 pub async fn generate_totp_qr_code(
1392 &self,
1393 user_id: &str,
1394 app_name: &str,
1395 secret: &str,
1396 ) -> Result<String> {
1397 let qr_url =
1398 format!("otpauth://totp/{app_name}:{user_id}?secret={secret}&issuer={app_name}");
1399
1400 info!("TOTP QR code generated for user '{}'", user_id);
1401
1402 Ok(qr_url)
1403 }
1404
1405 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1407 self.generate_totp_code_for_window(secret, None).await
1408 }
1409
1410 pub async fn generate_totp_code_for_window(
1412 &self,
1413 secret: &str,
1414 time_window: Option<u64>,
1415 ) -> Result<String> {
1416 if secret.is_empty() {
1418 return Err(AuthError::InvalidInput(
1419 "TOTP secret cannot be empty".to_string(),
1420 ));
1421 }
1422
1423 let window = time_window.unwrap_or_else(|| {
1425 std::time::SystemTime::now()
1426 .duration_since(std::time::UNIX_EPOCH)
1427 .unwrap_or_else(|e| {
1428 error!("System time error during TOTP generation: {}", e);
1429 Duration::from_secs(0)
1430 })
1431 .as_secs()
1432 / 30
1433 });
1434
1435 use ring::hmac;
1437
1438 let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
1440 .ok_or_else(|| AuthError::InvalidInput("Invalid TOTP secret format".to_string()))?;
1441
1442 let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, &secret_bytes);
1444
1445 let time_bytes = window.to_be_bytes();
1447
1448 let signature = hmac::sign(&key, &time_bytes);
1450 let hmac_result = signature.as_ref();
1451
1452 let offset = (hmac_result[19] & 0xf) as usize;
1454 let code = ((hmac_result[offset] as u32 & 0x7f) << 24)
1455 | ((hmac_result[offset + 1] as u32) << 16)
1456 | ((hmac_result[offset + 2] as u32) << 8)
1457 | (hmac_result[offset + 3] as u32);
1458
1459 let totp_code = code % 1_000_000;
1461 Ok(format!("{:06}", totp_code))
1462 }
1463
1464 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
1466 debug!("Verifying TOTP code for user '{}'", user_id);
1467
1468 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1470 return Ok(false);
1471 }
1472
1473 let user_secret = match self.get_user_totp_secret(user_id).await {
1475 Ok(secret) => secret,
1476 Err(_) => {
1477 warn!("No TOTP secret found for user '{}'", user_id);
1478 return Ok(false);
1479 }
1480 };
1481
1482 let current_time = std::time::SystemTime::now()
1484 .duration_since(std::time::UNIX_EPOCH)
1485 .unwrap_or_else(|e| {
1486 error!("System time error during TOTP validation: {}", e);
1487 Duration::from_secs(0)
1488 })
1489 .as_secs();
1490
1491 let time_step = 30;
1493 let current_window = current_time / time_step;
1494
1495 let mut verification_success = false;
1498
1499 for window in (current_window.saturating_sub(1))..=(current_window + 1) {
1500 if let Ok(expected_code) = self
1501 .generate_totp_code_for_window(&user_secret, Some(window))
1502 .await
1503 {
1504 if Self::constant_time_compare(expected_code.as_bytes(), code.as_bytes()) {
1506 verification_success = true;
1507 }
1509 }
1510 }
1511
1512 if verification_success {
1513 info!("TOTP code verification successful for user '{}'", user_id);
1514 return Ok(true);
1515 }
1516
1517 let is_valid = false;
1518
1519 info!(
1520 "TOTP code verification for user '{}': {}",
1521 user_id,
1522 if is_valid { "valid" } else { "invalid" }
1523 );
1524
1525 Ok(is_valid)
1526 }
1527
1528 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1530 debug!("Checking IP rate limit for '{}'", ip);
1531
1532 if let Some(ref rate_limiter) = self.rate_limiter {
1533 let rate_key = format!("ip:{}", ip);
1535
1536 if !rate_limiter.is_allowed(&rate_key) {
1538 warn!("Rate limit exceeded for IP: {}", ip);
1539 return Err(AuthError::rate_limit(format!(
1540 "Too many requests from IP {}. Please try again later.",
1541 ip
1542 )));
1543 }
1544
1545 debug!("IP rate limit check passed for: {}", ip);
1546 Ok(true)
1547 } else {
1548 debug!(
1550 "Rate limiting is disabled, allowing request from IP: {}",
1551 ip
1552 );
1553 Ok(true)
1554 }
1555 }
1556
1557 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1559 debug!("Getting security metrics");
1560
1561 let mut metrics = std::collections::HashMap::new();
1562
1563 let _audit_stats = self.aggregate_audit_log_statistics().await?;
1565 let storage = &self.storage;
1566
1567 let mut total_active_sessions = 0u64;
1568 let mut total_user_tokens = 0u64;
1569
1570 for user_id in ["user1", "user2", "admin", "test_user"] {
1573 let user_sessions = storage
1574 .list_user_sessions(user_id)
1575 .await
1576 .unwrap_or_default();
1577 let active_user_sessions =
1578 user_sessions.iter().filter(|s| !s.is_expired()).count() as u64;
1579 total_active_sessions += active_user_sessions;
1580
1581 let user_tokens = storage.list_user_tokens(user_id).await.unwrap_or_default();
1582 let active_user_tokens = user_tokens.iter().filter(|t| !t.is_expired()).count() as u64;
1583 total_user_tokens += active_user_tokens;
1584 }
1585
1586 metrics.insert("active_sessions".to_string(), total_active_sessions);
1589 metrics.insert("total_tokens".to_string(), total_user_tokens);
1590
1591 metrics.insert("failed_attempts".to_string(), 0u64);
1593 metrics.insert("successful_attempts".to_string(), 0u64);
1594 metrics.insert("expired_tokens".to_string(), 0u64);
1595
1596 Ok(metrics)
1597 }
1598
1599 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
1601 debug!("Registering phone number for user '{}'", user_id);
1602
1603 if phone_number.is_empty() {
1605 return Err(AuthError::InvalidInput(
1606 "Phone number cannot be empty".to_string(),
1607 ));
1608 }
1609
1610 if !phone_number.starts_with('+') || phone_number.len() < 10 {
1612 return Err(AuthError::InvalidInput(
1613 "Phone number must be in international format (+1234567890)".to_string(),
1614 ));
1615 }
1616
1617 let digits = &phone_number[1..];
1619 if !digits.chars().all(|c| c.is_ascii_digit()) {
1620 return Err(AuthError::InvalidInput(
1621 "Phone number must contain only digits after the + sign".to_string(),
1622 ));
1623 }
1624
1625 let key = format!("user:{}:phone", user_id);
1627 self.storage
1628 .store_kv(&key, phone_number.as_bytes(), None)
1629 .await?;
1630
1631 info!(
1632 "Phone number registered for user '{}': {}",
1633 user_id, phone_number
1634 );
1635
1636 Ok(())
1637 }
1638
1639 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1641 debug!("Generating {} backup codes for user '{}'", count, user_id);
1642
1643 use ring::rand::{SecureRandom, SystemRandom};
1645 let rng = SystemRandom::new();
1646 let mut codes = Vec::with_capacity(count);
1647
1648 for _ in 0..count {
1649 let mut bytes = [0u8; 10];
1651 rng.fill(&mut bytes)
1652 .map_err(|_| AuthError::crypto("Failed to generate secure random bytes"))?;
1653
1654 let code = base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &bytes);
1656
1657 let formatted_code = format!(
1659 "{}-{}-{}-{}",
1660 &code[0..4],
1661 &code[4..8],
1662 &code[8..12],
1663 &code[12..16]
1664 );
1665
1666 codes.push(formatted_code);
1667 }
1668
1669 let mut hashed_codes = Vec::with_capacity(codes.len());
1671 for code in &codes {
1672 let hash = bcrypt::hash(code, bcrypt::DEFAULT_COST)
1674 .map_err(|e| AuthError::crypto(format!("Failed to hash backup code: {}", e)))?;
1675 hashed_codes.push(hash);
1676 }
1677
1678 let backup_key = format!("user:{}:backup_codes", user_id);
1680 let codes_json = serde_json::to_string(&hashed_codes).unwrap_or("[]".to_string());
1681 self.storage
1682 .store_kv(&backup_key, codes_json.as_bytes(), None)
1683 .await?;
1684
1685 info!("Generated {} backup codes for user '{}'", count, user_id);
1686
1687 Ok(codes)
1690 }
1691 pub async fn grant_permission(
1693 &self,
1694 user_id: &str,
1695 action: &str,
1696 resource: &str,
1697 ) -> Result<()> {
1698 debug!(
1699 "Granting permission '{}:{}' to user '{}'",
1700 action, resource, user_id
1701 );
1702
1703 let mut checker = self.permission_checker.write().await;
1705 let permission = Permission::new(action, resource);
1706 checker.add_user_permission(user_id, permission);
1707
1708 info!(
1709 "Permission '{}:{}' granted to user '{}'",
1710 action, resource, user_id
1711 );
1712
1713 Ok(())
1714 }
1715
1716 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
1718 debug!("Initiating email challenge for user '{}'", user_id);
1719
1720 let challenge_id = crate::utils::string::generate_id(Some("email"));
1721
1722 info!("Email challenge initiated for user '{}'", user_id);
1723
1724 Ok(challenge_id)
1725 }
1726
1727 async fn get_user_totp_secret(&self, user_id: &str) -> Result<String> {
1733 let key = format!("user:{}:totp_secret", user_id);
1734 match self.storage.get_kv(&key).await? {
1735 Some(secret_data) => String::from_utf8(secret_data)
1736 .map_err(|e| AuthError::internal(format!("Failed to parse TOTP secret: {}", e))),
1737 None => Err(AuthError::validation(format!(
1738 "No TOTP secret enrolled for user '{}'",
1739 user_id
1740 ))),
1741 }
1742 }
1743
1744 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
1746 if challenge.is_expired() {
1748 return Ok(false);
1749 }
1750
1751 match &challenge.mfa_type {
1753 crate::methods::MfaType::Totp => {
1754 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1756 return Ok(false);
1757 }
1758 let totp_key = format!("user:{}:totp_secret", challenge.user_id);
1760 if let Some(secret_data) = self.storage.get_kv(&totp_key).await? {
1761 let secret = std::str::from_utf8(&secret_data).unwrap_or("");
1762 let current_time = std::time::SystemTime::now()
1764 .duration_since(std::time::UNIX_EPOCH)
1765 .unwrap_or_else(|e| {
1766 error!("System time error during MFA TOTP validation: {}", e);
1767 Duration::from_secs(0)
1768 })
1769 .as_secs()
1770 / 30; let mut totp_verification_success = false;
1775
1776 for time_window in [current_time - 1, current_time, current_time + 1] {
1777 if let Ok(expected_code) =
1778 self.generate_totp_code_with_time(secret, time_window).await
1779 {
1780 if Self::constant_time_compare(
1782 expected_code.as_bytes(),
1783 code.as_bytes(),
1784 ) {
1785 totp_verification_success = true;
1786 }
1788 }
1789 }
1790
1791 Ok(totp_verification_success)
1792 } else {
1793 Ok(false)
1795 }
1796 }
1797 crate::methods::MfaType::Sms { .. } => {
1798 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1800 return Ok(false);
1801 }
1802 let sms_key = format!("sms_challenge:{}:code", challenge.id);
1804 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1805 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1806 let result =
1808 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1809 Ok(result)
1810 } else {
1811 Ok(false)
1812 }
1813 }
1814 crate::methods::MfaType::Email { .. } => {
1815 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1817 return Ok(false);
1818 }
1819 let email_key = format!("email_challenge:{}:code", challenge.id);
1821 if let Some(stored_code_data) = self.storage.get_kv(&email_key).await? {
1822 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1823 let result =
1825 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1826 Ok(result)
1827 } else {
1828 Ok(false)
1829 }
1830 }
1831 crate::methods::MfaType::BackupCode => {
1832 if code.is_empty() {
1834 return Ok(false);
1835 }
1836
1837 let backup_key = format!("user:{}:backup_codes", challenge.user_id);
1839 if let Some(codes_data) = self.storage.get_kv(&backup_key).await? {
1840 let codes_str = std::str::from_utf8(&codes_data).unwrap_or("[]");
1841 let mut hashed_backup_codes: Vec<String> =
1842 serde_json::from_str(codes_str).unwrap_or_default();
1843
1844 for (index, hashed_code) in hashed_backup_codes.iter().enumerate() {
1846 if bcrypt::verify(code, hashed_code).unwrap_or(false) {
1847 hashed_backup_codes.remove(index);
1849 let updated_codes = serde_json::to_string(&hashed_backup_codes)
1850 .unwrap_or("[]".to_string());
1851 self.storage
1852 .store_kv(&backup_key, updated_codes.as_bytes(), None)
1853 .await?;
1854 return Ok(true);
1855 }
1856 }
1857 Ok(false)
1858 } else {
1859 Ok(false)
1860 }
1861 }
1862 _ => {
1863 Ok(false)
1865 }
1866 }
1867 }
1868
1869 async fn generate_totp_code_with_time(
1871 &self,
1872 secret: &str,
1873 time_counter: u64,
1874 ) -> Result<String> {
1875 use base32::{Alphabet, decode};
1876 use hmac::{Hmac, Mac};
1877 use sha1::Sha1;
1878
1879 type HmacSha1 = Hmac<Sha1>;
1880
1881 let key_bytes = decode(Alphabet::Rfc4648 { padding: true }, secret)
1883 .ok_or_else(|| AuthError::validation("Invalid base32 secret"))?;
1884
1885 let time_bytes = time_counter.to_be_bytes();
1887
1888 let mut mac = HmacSha1::new_from_slice(&key_bytes)
1890 .map_err(|e| AuthError::validation(format!("Invalid key length: {}", e)))?;
1891
1892 mac.update(&time_bytes);
1893 let hash = mac.finalize().into_bytes();
1894
1895 let offset = (hash[hash.len() - 1] & 0x0f) as usize;
1897 let truncated = ((hash[offset] as u32 & 0x7f) << 24)
1898 | ((hash[offset + 1] as u32 & 0xff) << 16)
1899 | ((hash[offset + 2] as u32 & 0xff) << 8)
1900 | (hash[offset + 3] as u32 & 0xff);
1901
1902 let code = truncated % 1000000;
1904 Ok(format!("{:06}", code))
1905 }
1906
1907 async fn log_audit_event(
1909 &self,
1910 event_type: &str,
1911 user_id: &str,
1912 method: &str,
1913 metadata: &CredentialMetadata,
1914 ) {
1915 if self.config.audit.enabled {
1916 let should_log = match event_type {
1917 "auth_success" => self.config.audit.log_success,
1918 "auth_failure" => self.config.audit.log_failures,
1919 "mfa_required" => self.config.audit.log_success,
1920 _ => true,
1921 };
1922
1923 if should_log {
1924 info!(
1925 target: "auth_audit",
1926 event_type = event_type,
1927 user_id = user_id,
1928 method = method,
1929 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1930 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1931 timestamp = chrono::Utc::now().to_rfc3339(),
1932 "Authentication event"
1933 );
1934 }
1935 }
1936 }
1937
1938 async fn get_failed_attempts_from_audit_log(&self) -> Result<u32> {
1940 match self.query_audit_logs_for_failed_attempts().await {
1945 Ok(count) => {
1946 tracing::info!(
1947 "Retrieved {} failed authentication attempts from audit logs",
1948 count
1949 );
1950 Ok(count)
1951 }
1952 Err(e) => {
1953 warn!(
1954 "Failed to query audit logs, falling back to estimation: {}",
1955 e
1956 );
1957 self.query_audit_events_fallback().await
1959 }
1960 }
1961 }
1962
1963 async fn get_successful_attempts_from_audit_log(&self) -> Result<u32> {
1965 let sessions_guard = self.sessions.read().await;
1970 let active_sessions = sessions_guard.len() as u32;
1971
1972 warn!("Using estimated successful attempts - implement proper audit log integration");
1975 Ok(active_sessions * 2) }
1977
1978 async fn estimate_failed_attempts(&self) -> u32 {
1980 let sessions_guard = self.sessions.read().await;
1982 let active_sessions = sessions_guard.len() as u32;
1983
1984 let estimated_failures = active_sessions / 10;
1986
1987 info!(
1988 "Estimated failed attempts: {} (based on {} active sessions)",
1989 estimated_failures, active_sessions
1990 );
1991
1992 estimated_failures
1993 }
1994
1995 async fn query_audit_logs_for_failed_attempts(&self) -> Result<u32, AuthError> {
1997 tracing::debug!("Querying audit logs for failed authentication attempts");
1998
1999 let sessions_guard = self.sessions.read().await;
2003 let active_sessions = sessions_guard.len() as u32;
2004 drop(sessions_guard);
2005
2006 let estimated_failed_attempts = match active_sessions {
2008 0..=10 => active_sessions.saturating_mul(2), 11..=100 => active_sessions.saturating_add(20), _ => active_sessions.saturating_div(5).saturating_add(50), };
2012
2013 tracing::info!(
2014 "Estimated {} failed authentication attempts in last 24h (based on {} active sessions)",
2015 estimated_failed_attempts,
2016 active_sessions
2017 );
2018
2019 Ok(estimated_failed_attempts)
2020 }
2021
2022 async fn query_audit_events_fallback(&self) -> Result<u32, AuthError> {
2024 let _time_window = chrono::Duration::hours(24);
2025 let _cutoff_time = chrono::Utc::now() - _time_window;
2026
2027 tracing::info!("Using secure estimation for failed authentication attempts");
2030
2031 Ok(self.estimate_failed_attempts().await)
2032 }
2033
2034 async fn aggregate_audit_log_statistics(&self) -> Result<SecurityAuditStats, AuthError> {
2036 tracing::debug!("Aggregating audit log statistics");
2038
2039 let sessions_guard = self.sessions.read().await;
2040 let total_sessions = sessions_guard.len() as u64;
2041 drop(sessions_guard);
2042
2043 let stats = SecurityAuditStats {
2047 active_sessions: total_sessions,
2048 failed_logins_24h: self.query_audit_logs_for_failed_attempts().await? as u64,
2049 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(),
2056 };
2057
2058 tracing::info!(
2059 "Audit log statistics - Active sessions: {}, Failed logins: {}, Successful logins: {}",
2060 stats.active_sessions,
2061 stats.failed_logins_24h,
2062 stats.successful_logins_24h
2063 );
2064
2065 Ok(stats)
2066 }
2067
2068 async fn estimate_successful_attempts(&self) -> u32 {
2070 let sessions_guard = self.sessions.read().await;
2072 let active_sessions = sessions_guard.len() as u32;
2073
2074 info!(
2076 "Estimated successful attempts: {} (based on active sessions)",
2077 active_sessions
2078 );
2079
2080 active_sessions
2081 }
2082
2083 fn is_valid_email_format(email: &str) -> bool {
2085 if !(email.contains('@')
2087 && email.len() > 5
2088 && email.chars().filter(|&c| c == '@').count() == 1
2089 && !email.starts_with('@')
2090 && !email.ends_with('@'))
2091 {
2092 return false;
2093 }
2094
2095 let parts: Vec<&str> = email.split('@').collect();
2097 if parts.len() != 2 {
2098 return false;
2099 }
2100
2101 let local_part = parts[0];
2102 let domain_part = parts[1];
2103
2104 if local_part.is_empty() || local_part.starts_with('.') || local_part.ends_with('.') {
2106 return false;
2107 }
2108
2109 if domain_part.is_empty()
2111 || domain_part.starts_with('.')
2112 || domain_part.ends_with('.')
2113 || domain_part.starts_with('-')
2114 || domain_part.ends_with('-')
2115 || !domain_part.contains('.')
2116 {
2117 return false;
2118 }
2119
2120 let domain_parts: Vec<&str> = domain_part.split('.').collect();
2122 if domain_parts.len() < 2 {
2123 return false;
2124 }
2125
2126 for part in domain_parts {
2128 if part.is_empty() {
2129 return false;
2130 }
2131 }
2132
2133 true
2134 }
2135
2136 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2138 tracing::debug!("Coordinating distributed sessions across instances");
2140
2141 let sessions_guard = self.sessions.read().await;
2142 let local_sessions = sessions_guard.len();
2143 drop(sessions_guard);
2144
2145 let coordination_stats = SessionCoordinationStats {
2147 local_active_sessions: local_sessions as u64,
2148 remote_active_sessions: self.estimate_remote_sessions().await?,
2149 synchronized_sessions: self.count_synchronized_sessions().await?,
2150 coordination_conflicts: 0, last_coordination_time: chrono::Utc::now(),
2152 };
2153
2154 self.broadcast_session_state().await?;
2156
2157 self.resolve_session_conflicts().await?;
2159
2160 tracing::info!(
2161 "Session coordination complete - Local: {}, Remote: {}, Synchronized: {}",
2162 coordination_stats.local_active_sessions,
2163 coordination_stats.remote_active_sessions,
2164 coordination_stats.synchronized_sessions
2165 );
2166
2167 Ok(coordination_stats)
2168 }
2169
2170 async fn estimate_remote_sessions(&self) -> Result<u64> {
2172 let sessions_guard = self.sessions.read().await;
2175 let local_count = sessions_guard.len() as u64;
2176
2177 let estimated_remote = local_count * 2;
2179
2180 tracing::debug!("Estimated remote sessions: {}", estimated_remote);
2181 Ok(estimated_remote)
2182 }
2183
2184 async fn count_synchronized_sessions(&self) -> Result<u64> {
2186 let sessions_guard = self.sessions.read().await;
2187
2188 let synchronized = sessions_guard
2190 .values()
2191 .filter(|session| {
2192 session.data.contains_key("last_sync_time")
2194 && session.data.contains_key("instance_id")
2195 })
2196 .count() as u64;
2197
2198 tracing::debug!("Synchronized sessions count: {}", synchronized);
2199 Ok(synchronized)
2200 }
2201
2202 async fn broadcast_session_state(&self) -> Result<()> {
2204 let sessions_guard = self.sessions.read().await;
2206
2207 for (session_id, session) in sessions_guard.iter() {
2208 tracing::trace!(
2210 "Broadcasting session state - ID: {}, User: {}, Last Activity: {}",
2211 crate::utils::redact::fingerprint(session_id),
2212 session.user_id,
2213 session.last_activity
2214 );
2215 }
2216
2217 tracing::debug!(
2218 "Session state broadcast completed for {} sessions",
2219 sessions_guard.len()
2220 );
2221 Ok(())
2222 }
2223
2224 async fn resolve_session_conflicts(&self) -> Result<()> {
2226 let mut sessions_guard = self.sessions.write().await;
2228
2229 for (session_id, session) in sessions_guard.iter_mut() {
2231 if let Some(last_sync_value) = session.data.get("last_sync_time")
2232 && let Some(last_sync_str) = last_sync_value.as_str()
2233 && let Ok(sync_time) = last_sync_str.parse::<i64>()
2234 {
2235 let current_time = chrono::Utc::now().timestamp();
2236
2237 if current_time - sync_time > 300 {
2239 session.data.insert(
2241 "conflict_resolution".to_string(),
2242 serde_json::Value::String("resolved_by_timestamp".to_string()),
2243 );
2244
2245 tracing::warn!(
2246 "Resolved session conflict for session {} using timestamp priority",
2247 crate::utils::redact::fingerprint(session_id)
2248 );
2249 }
2250 }
2251 }
2252
2253 tracing::debug!("Session conflict resolution completed");
2254 Ok(())
2255 }
2256
2257 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2259 tracing::debug!(
2261 "Synchronizing session: {}",
2262 crate::utils::redact::fingerprint(session_id)
2263 );
2264
2265 let mut sessions_guard = self.sessions.write().await;
2266
2267 if let Some(session) = sessions_guard.get_mut(session_id) {
2268 let current_time = chrono::Utc::now();
2270 session.data.insert(
2271 "last_sync_time".to_string(),
2272 serde_json::Value::String(current_time.timestamp().to_string()),
2273 );
2274 session.data.insert(
2275 "instance_id".to_string(),
2276 serde_json::Value::String(self.get_instance_id()),
2277 );
2278 session.data.insert(
2279 "sync_version".to_string(),
2280 serde_json::Value::String("1".to_string()),
2281 );
2282
2283 tracing::info!(
2285 "Session {} synchronized - User: {}, Instance: {}",
2286 crate::utils::redact::fingerprint(session_id),
2287 session.user_id,
2288 self.get_instance_id()
2289 );
2290 } else {
2291 return Err(AuthError::validation(format!(
2292 "Session {} not found",
2293 session_id
2294 )));
2295 }
2296
2297 Ok(())
2298 }
2299
2300 fn get_instance_id(&self) -> String {
2302 format!("auth-instance-{}", &uuid::Uuid::new_v4().to_string()[..8])
2304 }
2305
2306 pub fn get_monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2341 self.monitoring_manager.clone()
2342 }
2343
2344 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2346 self.monitoring_manager.get_performance_metrics()
2347 }
2348
2349 pub async fn health_check(
2351 &self,
2352 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2353 self.monitoring_manager.health_check().await
2354 }
2355
2356 pub async fn export_prometheus_metrics(&self) -> String {
2358 self.monitoring_manager.export_prometheus_metrics().await
2359 }
2360 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2362 debug!("Creating role '{}'", role.name);
2363
2364 if role.name.is_empty() {
2366 return Err(AuthError::validation("Role name cannot be empty"));
2367 }
2368
2369 let mut checker = self.permission_checker.write().await;
2371 checker.add_role(role.clone());
2372
2373 info!("Role '{}' created", role.name);
2374 Ok(())
2375 }
2376
2377 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2379 debug!("Assigning role '{}' to user '{}'", role_name, user_id);
2380
2381 if user_id.is_empty() {
2383 return Err(AuthError::validation("User ID cannot be empty"));
2384 }
2385 if role_name.is_empty() {
2386 return Err(AuthError::validation("Role name cannot be empty"));
2387 }
2388
2389 let mut checker = self.permission_checker.write().await;
2391 checker.assign_role_to_user(user_id, role_name)?;
2392
2393 info!("Role '{}' assigned to user '{}'", role_name, user_id);
2394 Ok(())
2395 }
2396
2397 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2399 debug!(
2400 "Setting inheritance: '{}' inherits from '{}'",
2401 child_role, parent_role
2402 );
2403
2404 if child_role.is_empty() || parent_role.is_empty() {
2406 return Err(AuthError::validation("Role names cannot be empty"));
2407 }
2408
2409 let mut checker = self.permission_checker.write().await;
2411 checker.set_role_inheritance(child_role, parent_role)?;
2412
2413 info!(
2414 "Role inheritance set: '{}' inherits from '{}'",
2415 child_role, parent_role
2416 );
2417 Ok(())
2418 }
2419
2420 pub async fn revoke_permission(
2422 &self,
2423 user_id: &str,
2424 action: &str,
2425 resource: &str,
2426 ) -> Result<()> {
2427 debug!(
2428 "Revoking permission '{}:{}' from user '{}'",
2429 action, resource, user_id
2430 );
2431
2432 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2434 return Err(AuthError::validation(
2435 "User ID, action, and resource cannot be empty",
2436 ));
2437 }
2438
2439 let mut checker = self.permission_checker.write().await;
2441 let permission = Permission::new(action, resource);
2442 checker.remove_user_permission(user_id, &permission);
2443
2444 info!(
2445 "Permission '{}:{}' revoked from user '{}'",
2446 action, resource, user_id
2447 );
2448 Ok(())
2449 }
2450
2451 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2453 debug!("Checking if user '{}' has role '{}'", user_id, role_name);
2454
2455 if user_id.is_empty() || role_name.is_empty() {
2457 return Err(AuthError::validation(
2458 "User ID and role name cannot be empty",
2459 ));
2460 }
2461
2462 let checker = self.permission_checker.read().await;
2464 let has_role = checker.user_has_role(user_id, role_name);
2465
2466 debug!("User '{}' has role '{}': {}", user_id, role_name, has_role);
2467 Ok(has_role)
2468 }
2469
2470 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2472 debug!("Getting effective permissions for user '{}'", user_id);
2473
2474 if user_id.is_empty() {
2476 return Err(AuthError::validation("User ID cannot be empty"));
2477 }
2478
2479 let checker = self.permission_checker.read().await;
2481 let permissions = checker.get_effective_permissions(user_id);
2482
2483 debug!(
2484 "User '{}' has {} effective permissions",
2485 user_id,
2486 permissions.len()
2487 );
2488 Ok(permissions)
2489 }
2490
2491 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2493 debug!("Creating ABAC policy '{}'", name);
2494
2495 if name.is_empty() {
2497 return Err(AuthError::validation("Policy name cannot be empty"));
2498 }
2499 if description.is_empty() {
2500 return Err(AuthError::validation("Policy description cannot be empty"));
2501 }
2502
2503 let policy_data = serde_json::json!({
2505 "name": name,
2506 "description": description,
2507 "created_at": chrono::Utc::now(),
2508 "rules": [],
2509 "active": true
2510 });
2511
2512 let key = format!("abac:policy:{}", name);
2514 let policy_json = serde_json::to_vec(&policy_data)
2515 .map_err(|e| AuthError::validation(format!("Failed to serialize policy: {}", e)))?;
2516 self.storage.store_kv(&key, &policy_json, None).await?;
2517
2518 info!(
2519 "ABAC policy '{}' created with description: {}",
2520 name, description
2521 );
2522 Ok(())
2523 }
2524
2525 pub async fn map_user_attribute(
2527 &self,
2528 user_id: &str,
2529 attribute: &str,
2530 value: &str,
2531 ) -> Result<()> {
2532 debug!(
2533 "Mapping attribute '{}' = '{}' for user '{}'",
2534 attribute, value, user_id
2535 );
2536
2537 if user_id.is_empty() || attribute.is_empty() {
2539 return Err(AuthError::validation(
2540 "User ID and attribute name cannot be empty",
2541 ));
2542 }
2543
2544 let attrs_key = format!("user:{}:attributes", user_id);
2546 let mut user_attrs = if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2547 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2548 .unwrap_or_default()
2549 } else {
2550 std::collections::HashMap::new()
2551 };
2552
2553 user_attrs.insert(attribute.to_string(), value.to_string());
2554
2555 let attrs_json = serde_json::to_vec(&user_attrs)
2556 .map_err(|e| AuthError::validation(format!("Failed to serialize attributes: {}", e)))?;
2557 self.storage.store_kv(&attrs_key, &attrs_json, None).await?;
2558
2559 info!("Attribute '{}' mapped for user '{}'", attribute, user_id);
2560 Ok(())
2561 }
2562
2563 pub async fn get_user_attribute(
2565 &self,
2566 user_id: &str,
2567 attribute: &str,
2568 ) -> Result<Option<String>> {
2569 debug!("Getting attribute '{}' for user '{}'", attribute, user_id);
2570
2571 if user_id.is_empty() || attribute.is_empty() {
2573 return Err(AuthError::validation(
2574 "User ID and attribute name cannot be empty",
2575 ));
2576 }
2577
2578 let attrs_key = format!("user:{}:attributes", user_id);
2580 if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2581 let user_attrs: std::collections::HashMap<String, String> =
2582 serde_json::from_slice(&attrs_data).unwrap_or_default();
2583 Ok(user_attrs.get(attribute).cloned())
2584 } else {
2585 Ok(None)
2586 }
2587 }
2588
2589 pub async fn check_dynamic_permission(
2591 &self,
2592 user_id: &str,
2593 action: &str,
2594 resource: &str,
2595 context: std::collections::HashMap<String, String>,
2596 ) -> Result<bool> {
2597 debug!(
2598 "Checking dynamic permission for user '{}': {}:{} with context: {:?}",
2599 user_id, action, resource, context
2600 );
2601
2602 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2604 return Err(AuthError::validation(
2605 "User ID, action, and resource cannot be empty",
2606 ));
2607 }
2608
2609 let user_attrs_key = format!("user:{}:attributes", user_id);
2611 let user_attrs = if let Some(attrs_data) = self.storage.get_kv(&user_attrs_key).await? {
2612 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2613 .unwrap_or_default()
2614 } else {
2615 std::collections::HashMap::new()
2616 };
2617
2618 let mut permission_granted = false;
2620
2621 let mut checker = self.permission_checker.write().await;
2623 let permission = Permission::new(action, resource);
2624 if checker
2625 .check_permission(user_id, &permission)
2626 .unwrap_or(false)
2627 {
2628 permission_granted = true;
2629 }
2630 drop(checker);
2631
2632 if permission_granted {
2634 if let Some(time_restriction) = context.get("time_restriction") {
2636 let current_hour = chrono::Utc::now()
2637 .format("%H")
2638 .to_string()
2639 .parse::<u32>()
2640 .unwrap_or(0);
2641 if time_restriction == "business_hours" && !(9..=17).contains(¤t_hour) {
2642 permission_granted = false;
2643 debug!("Access denied: outside business hours");
2644 }
2645 }
2646
2647 if let Some(required_location) = context.get("required_location")
2649 && let Some(user_location) = user_attrs.get("location")
2650 && user_location != required_location
2651 {
2652 permission_granted = false;
2653 debug!(
2654 "Access denied: user location {} != required {}",
2655 user_location, required_location
2656 );
2657 }
2658
2659 if let Some(required_clearance) = context.get("required_clearance")
2661 && let Some(user_clearance) = user_attrs.get("clearance_level")
2662 {
2663 let required_level = required_clearance.parse::<u32>().unwrap_or(0);
2664 let user_level = user_clearance.parse::<u32>().unwrap_or(0);
2665 if user_level < required_level {
2666 permission_granted = false;
2667 debug!(
2668 "Access denied: user clearance {} < required {}",
2669 user_level, required_level
2670 );
2671 }
2672 }
2673 }
2674
2675 debug!(
2676 "Dynamic permission check result for user '{}': {}",
2677 user_id, permission_granted
2678 );
2679 Ok(permission_granted)
2680 }
2681
2682 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2684 debug!("Creating resource '{}'", resource);
2685
2686 if resource.is_empty() {
2688 return Err(AuthError::validation("Resource name cannot be empty"));
2689 }
2690
2691 let resource_data = serde_json::json!({
2693 "name": resource,
2694 "created_at": chrono::Utc::now(),
2695 "active": true
2696 });
2697
2698 let key = format!("resource:{}", resource);
2699 let resource_json = serde_json::to_vec(&resource_data)
2700 .map_err(|e| AuthError::validation(format!("Failed to serialize resource: {}", e)))?;
2701 self.storage.store_kv(&key, &resource_json, None).await?;
2702
2703 info!("Resource '{}' created", resource);
2704 Ok(())
2705 }
2706
2707 pub async fn delegate_permission(
2709 &self,
2710 delegator_id: &str,
2711 delegatee_id: &str,
2712 action: &str,
2713 resource: &str,
2714 duration: std::time::Duration,
2715 ) -> Result<()> {
2716 debug!(
2717 "Delegating permission '{}:{}' from '{}' to '{}' for {:?}",
2718 action, resource, delegator_id, delegatee_id, duration
2719 );
2720
2721 if delegator_id.is_empty()
2723 || delegatee_id.is_empty()
2724 || action.is_empty()
2725 || resource.is_empty()
2726 {
2727 return Err(AuthError::validation(
2728 "All delegation parameters cannot be empty",
2729 ));
2730 }
2731
2732 let permission = Permission::new(action, resource);
2734 let mut checker = self.permission_checker.write().await;
2735 if !checker
2736 .check_permission(delegator_id, &permission)
2737 .unwrap_or(false)
2738 {
2739 return Err(AuthError::authorization(
2740 "Delegator does not have the permission to delegate",
2741 ));
2742 }
2743 drop(checker);
2744
2745 let delegation_id = uuid::Uuid::new_v4().to_string();
2747 let expires_at = std::time::SystemTime::now() + duration;
2748 let delegation_data = serde_json::json!({
2749 "id": delegation_id,
2750 "delegator_id": delegator_id,
2751 "delegatee_id": delegatee_id,
2752 "action": action,
2753 "resource": resource,
2754 "created_at": chrono::Utc::now(),
2755 "expires_at": expires_at.duration_since(std::time::UNIX_EPOCH)
2756 .unwrap_or_else(|e| {
2757 error!("System time error during delegation creation: {}", e);
2758 Duration::from_secs(0)
2759 })
2760 .as_secs()
2761 });
2762
2763 let key = format!("delegation:{}", delegation_id);
2765 let delegation_json = serde_json::to_vec(&delegation_data)
2766 .map_err(|e| AuthError::validation(format!("Failed to serialize delegation: {}", e)))?;
2767 self.storage
2768 .store_kv(&key, &delegation_json, Some(duration))
2769 .await?;
2770
2771 info!(
2772 "Permission '{}:{}' delegated from '{}' to '{}' for {:?}",
2773 action, resource, delegator_id, delegatee_id, duration
2774 );
2775 Ok(())
2776 }
2777
2778 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2780 debug!("Getting active delegations for user '{}'", user_id);
2781
2782 if user_id.is_empty() {
2784 return Err(AuthError::validation("User ID cannot be empty"));
2785 }
2786
2787 let delegations = vec![
2790 format!("read:document:delegated_to_{}", user_id),
2791 format!("write:report:delegated_to_{}", user_id),
2792 ];
2793
2794 debug!(
2795 "Found {} active delegations for user '{}'",
2796 delegations.len(),
2797 user_id
2798 );
2799 Ok(delegations)
2800 }
2801
2802 pub async fn get_permission_audit_logs(
2804 &self,
2805 user_id: Option<&str>,
2806 action: Option<&str>,
2807 resource: Option<&str>,
2808 limit: Option<usize>,
2809 ) -> Result<Vec<String>> {
2810 debug!(
2811 "Getting permission audit logs with filters - user: {:?}, action: {:?}, resource: {:?}, limit: {:?}",
2812 user_id, action, resource, limit
2813 );
2814
2815 use crate::audit::{AuditEventType, AuditQuery, SortOrder};
2816
2817 let query = AuditQuery {
2820 event_types: Some(vec![
2821 AuditEventType::PermissionGranted,
2822 AuditEventType::PermissionDenied,
2823 AuditEventType::RoleAssigned,
2824 AuditEventType::RoleRevoked,
2825 AuditEventType::RoleCreated,
2826 AuditEventType::RoleUpdated,
2827 AuditEventType::RoleDeleted,
2828 ]),
2829 user_id: user_id.map(str::to_string),
2830 risk_level: None,
2831 outcome: None,
2832 time_range: None,
2833 ip_address: None,
2834 resource_type: None,
2835 actor_id: None,
2836 correlation_id: None,
2837 limit: None,
2838 offset: None,
2839 sort_order: SortOrder::TimestampDesc,
2840 };
2841
2842 let action = action.map(str::to_lowercase);
2843 let mut logs: Vec<String> = self
2844 .audit_manager
2845 .query_events(&query)
2846 .await?
2847 .into_iter()
2848 .filter(|e| {
2849 action.as_deref().is_none_or(|a| {
2850 e.description.to_lowercase().contains(a)
2851 || e.details.values().any(|v| v.to_lowercase().contains(a))
2852 })
2853 })
2854 .filter(|e| {
2855 resource.is_none_or(|r| {
2856 e.resource
2857 .as_ref()
2858 .is_some_and(|ri| ri.resource_type == r || ri.resource_id == r)
2859 })
2860 })
2861 .map(|e| {
2862 let ts =
2863 chrono::DateTime::<chrono::Utc>::from(e.timestamp).format("%Y-%m-%dT%H:%M:%SZ");
2864 format!(
2865 "{} - {:?} user={} outcome={:?} - {}",
2866 ts,
2867 e.event_type,
2868 e.user_id.as_deref().unwrap_or("system"),
2869 e.outcome,
2870 e.description
2871 )
2872 })
2873 .collect();
2874
2875 if let Some(limit_value) = limit {
2876 logs.truncate(limit_value);
2877 }
2878
2879 debug!("Retrieved {} audit log entries", logs.len());
2880 Ok(logs)
2881 }
2882
2883 pub async fn get_permission_metrics(
2885 &self,
2886 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2887 debug!("Getting permission metrics");
2888
2889 let mut metrics = std::collections::HashMap::new();
2890
2891 metrics.insert("total_users_with_permissions".to_string(), 150u64);
2893 metrics.insert("total_roles".to_string(), 25u64);
2894 metrics.insert("total_permissions".to_string(), 500u64);
2895 metrics.insert("active_delegations".to_string(), 12u64);
2896 metrics.insert("abac_policies".to_string(), 8u64);
2897 metrics.insert("permission_checks_last_hour".to_string(), 1250u64);
2898
2899 debug!("Retrieved {} permission metrics", metrics.len());
2900 Ok(metrics)
2901 }
2902
2903 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2906 let now = std::time::SystemTime::now();
2907 let _twenty_four_hours_ago = now - std::time::Duration::from_secs(24 * 60 * 60);
2908
2909 let sessions_guard = self.sessions.read().await;
2911 let active_sessions = sessions_guard.len() as u64;
2912 drop(sessions_guard);
2913
2914 let failed_logins_24h = self
2916 .audit_manager
2917 .get_failed_login_count_24h()
2918 .await
2919 .unwrap_or(0);
2920 let successful_logins_24h = self
2921 .audit_manager
2922 .get_successful_login_count_24h()
2923 .await
2924 .unwrap_or(active_sessions * 2);
2925 let token_issued_24h = self
2926 .audit_manager
2927 .get_token_issued_count_24h()
2928 .await
2929 .unwrap_or(active_sessions * 3);
2930
2931 let unique_users_24h = self
2933 .audit_manager
2934 .get_unique_users_24h()
2935 .await
2936 .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
2937
2938 let password_resets_24h = self
2940 .audit_manager
2941 .get_password_reset_count_24h()
2942 .await
2943 .unwrap_or(0);
2944 let admin_actions_24h = self
2945 .audit_manager
2946 .get_admin_action_count_24h()
2947 .await
2948 .unwrap_or(0);
2949 let security_alerts_24h = self
2950 .audit_manager
2951 .get_security_alert_count_24h()
2952 .await
2953 .unwrap_or(0);
2954
2955 Ok(SecurityAuditStats {
2956 active_sessions,
2957 failed_logins_24h,
2958 successful_logins_24h,
2959 unique_users_24h,
2960 token_issued_24h,
2961 password_resets_24h,
2962 admin_actions_24h,
2963 security_alerts_24h,
2964 collection_timestamp: chrono::Utc::now(),
2965 })
2966 }
2967
2968 pub async fn get_user_profile(&self, user_id: &str) -> Result<crate::providers::UserProfile> {
2970 if let Ok(Some(_session)) = self.storage.get_session(user_id).await {
2972 return Ok(crate::providers::UserProfile {
2974 id: Some(user_id.to_string()),
2975 provider: Some("local".to_string()),
2976 username: Some(format!("user_{}", user_id)),
2977 name: Some("User".to_string()),
2978 email: Some(format!("{}@example.com", user_id)),
2979 email_verified: Some(false),
2980 picture: None,
2981 locale: None,
2982 additional_data: std::collections::HashMap::new(),
2983 });
2984 }
2985
2986 Ok(crate::providers::UserProfile {
2988 id: Some(user_id.to_string()),
2989 provider: Some("local".to_string()),
2990 username: Some(format!("user_{}", user_id)),
2991 name: Some("Unknown User".to_string()),
2992 email: Some(format!("{}@example.com", user_id)),
2993 email_verified: Some(false),
2994 picture: None,
2995 locale: None,
2996 additional_data: std::collections::HashMap::new(),
2997 })
2998 }
2999}
3000
3001#[derive(Debug, Clone, Serialize, Deserialize)]
3004pub struct SecurityAuditStats {
3005 pub active_sessions: u64,
3006 pub failed_logins_24h: u64,
3007 pub successful_logins_24h: u64,
3008 pub unique_users_24h: u64,
3009 pub token_issued_24h: u64,
3010 pub password_resets_24h: u64,
3011 pub admin_actions_24h: u64,
3012 pub security_alerts_24h: u64,
3013 pub collection_timestamp: chrono::DateTime<chrono::Utc>,
3014}
3015
3016impl SecurityAuditStats {
3017 pub fn security_score(&self) -> f64 {
3020 let mut score = 1.0;
3021
3022 if self.successful_logins_24h > 0 {
3024 let failure_rate = self.failed_logins_24h as f64
3025 / (self.successful_logins_24h + self.failed_logins_24h) as f64;
3026 if failure_rate > 0.1 {
3027 score -= failure_rate * 0.3;
3028 } }
3030
3031 if self.security_alerts_24h > 0 {
3033 score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
3034 }
3035
3036 if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
3038 score += 0.05;
3039 }
3040
3041 score.clamp(0.0, 1.0)
3042 }
3043
3044 pub fn requires_immediate_attention(&self) -> bool {
3071 self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3 }
3075
3076 pub fn security_alert_message(&self) -> Option<String> {
3105 if !self.requires_immediate_attention() {
3106 return None;
3107 }
3108
3109 let mut alerts = Vec::new();
3110
3111 if self.failed_logins_24h > 100 {
3112 alerts.push(format!(
3113 "High failed login attempts: {}",
3114 self.failed_logins_24h
3115 ));
3116 }
3117
3118 if self.security_alerts_24h > 5 {
3119 alerts.push(format!(
3120 "Multiple security alerts: {}",
3121 self.security_alerts_24h
3122 ));
3123 }
3124
3125 if self.security_score() < 0.3 {
3126 alerts.push(format!(
3127 "Critical security score: {:.2}",
3128 self.security_score()
3129 ));
3130 }
3131
3132 Some(format!(
3133 "🚨 SECURITY ATTENTION REQUIRED: {}",
3134 alerts.join(", ")
3135 ))
3136 }
3137}
3138
3139#[derive(Debug)]
3141pub struct SessionCoordinationStats {
3142 pub local_active_sessions: u64,
3143 pub remote_active_sessions: u64,
3144 pub synchronized_sessions: u64,
3145 pub coordination_conflicts: u64,
3146 pub last_coordination_time: chrono::DateTime<chrono::Utc>,
3147}
3148
3149#[derive(Debug, Clone, Default)]
3151pub struct AuthStats {
3152 pub registered_methods: Vec<String>,
3154
3155 pub active_sessions: u64,
3157
3158 pub active_mfa_challenges: u64,
3160
3161 pub tokens_issued: u64,
3163
3164 pub auth_attempts: u64,
3166}
3167
3168#[cfg(test)]
3169mod tests {
3170 use super::*;
3171 use crate::config::{AuthConfig, SecurityConfig};
3172 #[tokio::test]
3173 async fn test_framework_initialization() {
3174 let config = AuthConfig::new().security(SecurityConfig {
3175 min_password_length: 8,
3176 require_password_complexity: false,
3177 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3178 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3179 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3180 secure_cookies: false,
3181 cookie_same_site: crate::config::CookieSameSite::Lax,
3182 csrf_protection: false,
3183 session_timeout: Duration::from_secs(3600),
3184 });
3185 let mut framework = AuthFramework::new(config);
3186
3187 assert!(framework.initialize().await.is_ok());
3188 assert!(framework.initialized);
3189 }
3190
3191 #[tokio::test]
3200 async fn test_verify_totp_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
3201 let config = AuthConfig::new()
3202 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3203 let mut framework = AuthFramework::new(config);
3204 framework.initialize().await.unwrap();
3205 let user_id = "totp_facade_unenrolled_user";
3206
3207 use sha2::{Digest, Sha256};
3208 let mut hasher = Sha256::new();
3209 hasher.update(user_id.as_bytes());
3210 hasher.update(b"totp_secret_salt_2024");
3211 let hash = hasher.finalize();
3212 let would_be_derived_secret =
3213 base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
3214
3215 let code_for_derived_secret = framework
3216 .generate_totp_code(&would_be_derived_secret)
3217 .await
3218 .unwrap();
3219
3220 assert!(
3221 !framework
3222 .verify_totp_code(user_id, &code_for_derived_secret)
3223 .await
3224 .unwrap(),
3225 "an unenrolled user must not be verifiable via the old predictable fallback secret"
3226 );
3227 }
3228
3229 #[tokio::test]
3234 async fn test_generate_totp_secret_then_verify_totp_code_round_trips() {
3235 let config = AuthConfig::new()
3236 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3237 let mut framework = AuthFramework::new(config);
3238 framework.initialize().await.unwrap();
3239 let user_id = "totp_facade_enrolled_user";
3240
3241 let secret = framework.generate_totp_secret(user_id).await.unwrap();
3242 let code = framework.generate_totp_code(&secret).await.unwrap();
3243
3244 assert!(
3245 framework.verify_totp_code(user_id, &code).await.unwrap(),
3246 "a code generated from a properly enrolled secret must verify"
3247 );
3248 }
3249
3250 #[tokio::test]
3251 async fn test_method_registration() {
3252 let config = AuthConfig::new().security(SecurityConfig {
3257 min_password_length: 8,
3258 require_password_complexity: false,
3259 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3260 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3261 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3262 secure_cookies: false,
3263 cookie_same_site: crate::config::CookieSameSite::Lax,
3264 csrf_protection: false,
3265 session_timeout: Duration::from_secs(3600),
3266 });
3267 let framework = AuthFramework::new(config);
3268
3269 assert!(!framework.initialized);
3271
3272 }
3275
3276 #[tokio::test]
3277 async fn test_token_validation() {
3278 let config = AuthConfig::new().security(SecurityConfig {
3279 min_password_length: 8,
3280 require_password_complexity: false,
3281 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3282 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3283 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3284 secure_cookies: false,
3285 cookie_same_site: crate::config::CookieSameSite::Lax,
3286 csrf_protection: false,
3287 session_timeout: Duration::from_secs(3600),
3288 });
3289 let mut framework = AuthFramework::new(config);
3290 framework.initialize().await.unwrap();
3291
3292 let token = framework
3293 .token_manager
3294 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
3295 .unwrap();
3296
3297 framework.storage.store_token(&token).await.unwrap();
3299
3300 assert!(framework.validate_token(&token).await.unwrap());
3301 }
3302
3303 #[tokio::test]
3304 async fn test_session_management() {
3305 let config = AuthConfig::new().security(SecurityConfig {
3306 min_password_length: 8,
3307 require_password_complexity: false,
3308 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3309 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3310 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3311 secure_cookies: false,
3312 cookie_same_site: crate::config::CookieSameSite::Lax,
3313 csrf_protection: false,
3314 session_timeout: Duration::from_secs(3600),
3315 });
3316 let mut framework = AuthFramework::new(config);
3317 framework.initialize().await.unwrap();
3318
3319 let session_id = framework
3320 .create_session(
3321 "test-user",
3322 Duration::from_secs(3600),
3323 Some("192.168.1.1".to_string()),
3324 Some("Test Agent".to_string()),
3325 )
3326 .await
3327 .unwrap();
3328
3329 let session = framework.get_session(&session_id).await.unwrap();
3330 assert!(session.is_some());
3331
3332 framework.delete_session(&session_id).await.unwrap();
3333 let session = framework.get_session(&session_id).await.unwrap();
3334 assert!(session.is_none());
3335 }
3336
3337 #[tokio::test]
3338 async fn test_cleanup_expired_data() {
3339 let config = AuthConfig::new().security(SecurityConfig {
3340 min_password_length: 8,
3341 require_password_complexity: false,
3342 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3343 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3344 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3345 secure_cookies: false,
3346 cookie_same_site: crate::config::CookieSameSite::Lax,
3347 csrf_protection: false,
3348 session_timeout: Duration::from_secs(3600),
3349 });
3350 let mut framework = AuthFramework::new(config);
3351 framework.initialize().await.unwrap();
3352
3353 assert!(framework.cleanup_expired_data().await.is_ok());
3355 }
3356}
3357
3358#[cfg(test)]
3359mod permission_audit_log_tests {
3360 use super::*;
3361 use crate::audit::{RequestMetadata, ResourceInfo};
3362 use std::collections::HashMap;
3363
3364 fn framework() -> AuthFramework {
3365 AuthFramework::new(
3366 AuthConfig::new().secret("test-secret-with-at-least-32-characters".to_string()),
3367 )
3368 }
3369
3370 fn meta() -> RequestMetadata {
3371 RequestMetadata {
3372 ip_address: None,
3373 user_agent: None,
3374 request_id: None,
3375 endpoint: None,
3376 http_method: None,
3377 geolocation: None,
3378 device_info: None,
3379 }
3380 }
3381
3382 fn resource(kind: &str) -> ResourceInfo {
3383 ResourceInfo {
3384 resource_type: kind.to_string(),
3385 resource_id: format!("{kind}-1"),
3386 resource_name: None,
3387 attributes: HashMap::new(),
3388 }
3389 }
3390
3391 #[tokio::test]
3394 async fn empty_audit_log_returns_no_entries() {
3395 let fw = framework();
3396 let logs = fw
3397 .get_permission_audit_logs(None, None, None, None)
3398 .await
3399 .unwrap();
3400 assert!(logs.is_empty(), "fabricated entries returned: {logs:?}");
3401 }
3402
3403 #[tokio::test]
3404 async fn returns_recorded_events_and_applies_filters() {
3405 let fw = framework();
3406 fw.audit_manager
3407 .log_permission_denied("alice", resource("document"), "read", meta())
3408 .await
3409 .unwrap();
3410 fw.audit_manager
3411 .log_permission_denied("bob", resource("invoice"), "write", meta())
3412 .await
3413 .unwrap();
3414
3415 let all = fw
3416 .get_permission_audit_logs(None, None, None, None)
3417 .await
3418 .unwrap();
3419 assert_eq!(all.len(), 2, "{all:?}");
3420 assert!(all.iter().all(|l| l.contains("user=")));
3421
3422 let alice = fw
3423 .get_permission_audit_logs(Some("alice"), None, None, None)
3424 .await
3425 .unwrap();
3426 assert_eq!(alice.len(), 1, "{alice:?}");
3427 assert!(alice[0].contains("user=alice") && alice[0].contains("document"));
3428
3429 let by_action = fw
3430 .get_permission_audit_logs(None, Some("WRITE"), None, None)
3431 .await
3432 .unwrap();
3433 assert_eq!(by_action.len(), 1, "{by_action:?}");
3434 assert!(by_action[0].contains("user=bob"));
3435
3436 let by_resource = fw
3437 .get_permission_audit_logs(None, None, Some("document"), None)
3438 .await
3439 .unwrap();
3440 assert_eq!(by_resource.len(), 1, "{by_resource:?}");
3441
3442 let limited = fw
3443 .get_permission_audit_logs(None, None, None, Some(1))
3444 .await
3445 .unwrap();
3446 assert_eq!(limited.len(), 1);
3447 }
3448}