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 {
109 config: AuthConfig,
111
112 methods: HashMap<String, AuthMethodEnum>,
114
115 token_manager: TokenManager,
117
118 storage: Arc<dyn AuthStorage>,
120
121 permission_checker: Arc<RwLock<PermissionChecker>>,
123
124 rate_limiter: Option<RateLimiter>,
126
127 mfa_challenges: Arc<RwLock<HashMap<String, MfaChallenge>>>,
129
130 sessions: Arc<RwLock<HashMap<String, SessionData>>>,
132
133 monitoring_manager: Arc<crate::monitoring::MonitoringManager>,
135
136 audit_manager: Arc<crate::audit::AuditLogger<Arc<crate::storage::MemoryStorage>>>,
138
139 initialized: bool,
141}
142
143impl AuthFramework {
144 fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
148 if a.len() != b.len() {
149 return false;
150 }
151
152 let mut result = 0u8;
153 for (byte_a, byte_b) in a.iter().zip(b.iter()) {
154 result |= byte_a ^ byte_b;
155 }
156 result == 0
157 }
158
159 pub fn new(config: AuthConfig) -> Self {
165 let storage = Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>;
167 let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
168 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
169
170 let default_secret = b"temporary_development_secret_replace_in_init";
172 let token_manager =
173 TokenManager::new_hmac(default_secret, "auth-framework", "auth-framework");
174
175 Self {
176 config,
177 methods: HashMap::new(),
178 token_manager,
179 storage,
180 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
181 rate_limiter: None, mfa_challenges: Arc::new(RwLock::new(HashMap::new())),
183 sessions: Arc::new(RwLock::new(HashMap::new())),
184 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
185 crate::monitoring::MonitoringConfig::default(),
186 )),
187 audit_manager,
188 initialized: false,
189 }
190 }
191
192 pub fn new_validated(config: AuthConfig) -> Result<Self> {
197 config.validate().map_err(|e| {
199 AuthError::configuration(format!("Configuration validation failed: {}", e))
200 })?;
201
202 let token_manager = if let Some(secret) = &config.security.secret_key {
204 if secret.len() < 32 {
205 return Err(AuthError::configuration(
206 "JWT secret must be at least 32 characters for production security",
207 ));
208 }
209 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
210 } else if let Some(secret) = &config.secret {
211 if secret.len() < 32 {
212 return Err(AuthError::configuration(
213 "JWT secret must be at least 32 characters for production security",
214 ));
215 }
216 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
217 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
218 if jwt_secret.len() < 32 {
219 return Err(AuthError::configuration(
220 "JWT_SECRET must be at least 32 characters for production security",
221 ));
222 }
223 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
224 } else {
225 return Err(AuthError::configuration(
226 "JWT secret not configured! Please set JWT_SECRET environment variable or provide in configuration.\n\
227 For security reasons, no default secret is provided.\n\
228 Generate a secure secret with: openssl rand -base64 32",
229 ));
230 };
231
232 let storage: Arc<dyn AuthStorage> = match &config.storage {
234 #[cfg(feature = "redis-storage")]
235 crate::config::StorageConfig::Redis { url, key_prefix } => Arc::new(
236 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
237 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
238 })?,
239 ),
240 _ => Arc::new(MemoryStorage::new()) as Arc<dyn AuthStorage>,
241 };
242
243 let rate_limiter = if config.rate_limiting.enabled {
245 Some(RateLimiter::new(
246 config.rate_limiting.max_requests,
247 config.rate_limiting.window,
248 ))
249 } else {
250 None
251 };
252
253 let audit_storage = Arc::new(crate::storage::MemoryStorage::new());
255 let audit_manager = Arc::new(crate::audit::AuditLogger::new(audit_storage));
256
257 Ok(Self {
258 config,
259 methods: HashMap::new(),
260 token_manager,
261 storage,
262 permission_checker: Arc::new(RwLock::new(PermissionChecker::new())),
263 rate_limiter,
264 mfa_challenges: Arc::new(RwLock::new(HashMap::new())),
265 sessions: Arc::new(RwLock::new(HashMap::new())),
266 monitoring_manager: Arc::new(crate::monitoring::MonitoringManager::new(
267 crate::monitoring::MonitoringConfig::default(),
268 )),
269 audit_manager,
270 initialized: false,
271 })
272 }
273
274 pub fn register_method(&mut self, name: impl Into<String>, method: AuthMethodEnum) {
276 let name = name.into();
277 info!("Registering authentication method: {}", name);
278
279 if let Err(e) = method.validate_config() {
281 error!("Method '{}' configuration validation failed: {}", name, e);
282 return;
283 }
284
285 self.methods.insert(name, method);
286 }
287
288 pub async fn initialize(&mut self) -> Result<()> {
298 if self.initialized {
299 return Ok(());
300 }
301
302 info!("Initializing authentication framework");
303
304 self.config.validate().map_err(|e| {
306 AuthError::configuration(format!("Configuration validation failed: {}", e))
307 })?;
308
309 let token_manager = if let Some(secret) = &self.config.security.secret_key {
311 if secret.len() < 32 {
312 return Err(AuthError::configuration(
313 "JWT secret must be at least 32 characters for production security",
314 ));
315 }
316 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
317 } else if let Some(secret) = &self.config.secret {
318 if secret.len() < 32 {
319 return Err(AuthError::configuration(
320 "JWT secret must be at least 32 characters for production security",
321 ));
322 }
323 TokenManager::new_hmac(secret.as_bytes(), "auth-framework", "auth-framework")
324 } else if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
325 if jwt_secret.len() < 32 {
326 return Err(AuthError::configuration(
327 "JWT_SECRET must be at least 32 characters for production security",
328 ));
329 }
330 TokenManager::new_hmac(jwt_secret.as_bytes(), "auth-framework", "auth-framework")
331 } else {
332 if self.is_production_environment() {
334 return Err(AuthError::configuration(
335 "Production deployment requires JWT_SECRET environment variable or configuration!\n\
336 Generate a secure secret with: openssl rand -base64 32\n\
337 Set it with: export JWT_SECRET=\"your-secret-here\"",
338 ));
339 }
340
341 warn!("No JWT secret configured, using development-only default");
342 warn!("CRITICAL: Set JWT_SECRET environment variable for production!");
343 warn!("This configuration is NOT SECURE and should only be used in development!");
344
345 self.token_manager.clone()
347 };
348
349 self.token_manager = token_manager;
351
352 match &self.config.storage {
354 #[cfg(feature = "redis-storage")]
355 crate::config::StorageConfig::Redis { url, key_prefix } => {
356 let redis_storage =
357 crate::storage::RedisStorage::new(url, key_prefix).map_err(|e| {
358 AuthError::configuration(format!("Failed to create Redis storage: {}", e))
359 })?;
360 self.storage = Arc::new(redis_storage);
361 }
362 _ => {
363 }
365 }
366
367 if self.config.rate_limiting.enabled {
369 self.rate_limiter = Some(RateLimiter::new(
370 self.config.rate_limiting.max_requests,
371 self.config.rate_limiting.window,
372 ));
373 }
374
375 {
377 let mut checker = self.permission_checker.write().await;
378 checker.create_default_roles();
379 }
380
381 self.cleanup_expired_data().await?;
383
384 self.initialized = true;
385 info!("Authentication framework initialized successfully");
386
387 Ok(())
388 }
389
390 pub async fn authenticate(
392 &self,
393 method_name: &str,
394 credential: Credential,
395 ) -> Result<AuthResult> {
396 self.authenticate_with_metadata(method_name, credential, CredentialMetadata::new())
397 .await
398 }
399
400 pub async fn authenticate_with_metadata(
402 &self,
403 method_name: &str,
404 credential: Credential,
405 metadata: CredentialMetadata,
406 ) -> Result<AuthResult> {
407 use std::time::Instant;
408 use tokio::time::{Duration as TokioDuration, sleep};
409
410 let start_time = Instant::now();
411
412 self.monitoring_manager.record_auth_request().await;
414
415 if !self.initialized {
416 return Err(AuthError::internal("Framework not initialized"));
417 }
418
419 let result = self
421 .authenticate_internal(method_name, credential, metadata)
422 .await;
423
424 let min_duration = TokioDuration::from_millis(100); let elapsed = start_time.elapsed();
427 if elapsed < min_duration {
428 sleep(min_duration - elapsed).await;
429 }
430
431 if let Ok(ref auth_result) = result {
433 match auth_result {
434 AuthResult::Success(token) => {
435 self.monitoring_manager
436 .record_auth_success(&token.user_id, elapsed)
437 .await;
438 }
439 AuthResult::Failure(reason) => {
440 self.monitoring_manager
441 .record_auth_failure(None, reason)
442 .await;
443 }
444 _ => {} }
446 }
447
448 result
449 }
450
451 async fn authenticate_internal(
453 &self,
454 method_name: &str,
455 credential: Credential,
456 metadata: CredentialMetadata,
457 ) -> Result<AuthResult> {
458 if let Some(ref rate_limiter) = self.rate_limiter {
460 let rate_key = format!(
461 "auth:{}:{}",
462 method_name,
463 metadata.client_ip.as_deref().unwrap_or("unknown")
464 );
465
466 if !rate_limiter.is_allowed(&rate_key) {
467 warn!(
468 "Rate limit exceeded for method '{}' from IP {:?}",
469 method_name, metadata.client_ip
470 );
471 return Err(AuthError::rate_limit("Too many authentication attempts"));
472 }
473 }
474
475 let method = self.methods.get(method_name).ok_or_else(|| {
477 AuthError::auth_method(method_name, "Authentication method not found".to_string())
478 })?;
479
480 debug!(
482 "Authentication attempt with method '{}' for credential: {}",
483 method_name,
484 credential.safe_display()
485 );
486
487 let result = method.authenticate(credential, metadata.clone()).await?;
489
490 match &result {
492 MethodResult::Success(token) => {
493 info!(
494 "Authentication successful for user '{}' with method '{}'",
495 token.user_id, method_name
496 );
497
498 self.storage.store_token(token).await?;
500
501 self.log_audit_event("auth_success", &token.user_id, method_name, &metadata)
503 .await;
504
505 Ok(AuthResult::Success(token.clone()))
506 }
507
508 MethodResult::MfaRequired(challenge) => {
509 info!(
510 "MFA required for user '{}' with method '{}'",
511 challenge.user_id, method_name
512 );
513
514 let mut challenges = self.mfa_challenges.write().await;
516
517 const MAX_TOTAL_CHALLENGES: usize = 10_000;
519 if challenges.len() >= MAX_TOTAL_CHALLENGES {
520 warn!("Maximum MFA challenges ({}) exceeded", MAX_TOTAL_CHALLENGES);
521 return Err(AuthError::rate_limit(
522 "Too many pending MFA challenges. Please try again later.",
523 ));
524 }
525
526 challenges.insert(challenge.id.clone(), (**challenge).clone());
527
528 self.log_audit_event("mfa_required", &challenge.user_id, method_name, &metadata)
530 .await;
531
532 Ok(AuthResult::MfaRequired(challenge.clone()))
533 }
534
535 MethodResult::Failure { reason } => {
536 warn!(
537 "Authentication failed for method '{}': {}",
538 method_name, reason
539 );
540
541 self.log_audit_event("auth_failure", "unknown", method_name, &metadata)
543 .await;
544
545 Ok(AuthResult::Failure(reason.clone()))
546 }
547 }
548 }
549
550 pub async fn complete_mfa(&self, challenge: MfaChallenge, mfa_code: &str) -> Result<AuthToken> {
552 debug!("Completing MFA for challenge '{}'", challenge.id);
553
554 let mut challenges = self.mfa_challenges.write().await;
556 let stored_challenge = challenges
557 .get(&challenge.id)
558 .ok_or(MfaError::ChallengeExpired)?;
559
560 if stored_challenge.is_expired() {
561 challenges.remove(&challenge.id);
562 return Err(MfaError::ChallengeExpired.into());
563 }
564
565 if !self.verify_mfa_code(stored_challenge, mfa_code).await? {
567 return Err(MfaError::InvalidCode.into());
568 }
569
570 challenges.remove(&challenge.id);
572
573 let token = self.token_manager.create_auth_token(
575 &challenge.user_id,
576 vec![], "mfa",
578 None,
579 )?;
580
581 self.storage.store_token(&token).await?;
583
584 info!(
585 "MFA completed successfully for user '{}'",
586 challenge.user_id
587 );
588
589 Ok(token)
590 }
591
592 pub async fn validate_token(&self, token: &AuthToken) -> Result<bool> {
594 if !self.initialized {
595 return Err(AuthError::internal("Framework not initialized"));
596 }
597
598 if !token.is_valid() {
600 self.monitoring_manager.record_token_validation(false).await;
601 return Ok(false);
602 }
603
604 match self.token_manager.validate_auth_token(token) {
606 Ok(_) => {}
607 Err(_) => {
608 self.monitoring_manager.record_token_validation(false).await;
609 return Ok(false);
610 }
611 }
612
613 if let Some(stored_token) = self.storage.get_token(&token.token_id).await? {
615 let mut updated_token = stored_token;
617 updated_token.mark_used();
618 self.storage.update_token(&updated_token).await?;
619
620 self.monitoring_manager.record_token_validation(true).await;
621 Ok(true)
622 } else {
623 self.monitoring_manager.record_token_validation(false).await;
624 Ok(false)
625 }
626 }
627
628 pub async fn get_user_info(&self, token: &AuthToken) -> Result<UserInfo> {
630 if !self.validate_token(token).await? {
631 return Err(AuthError::auth_method("token", "Invalid token".to_string()));
632 }
633
634 let token_info = self.token_manager.extract_token_info(&token.access_token)?;
636
637 Ok(UserInfo {
638 id: token_info.user_id,
639 username: token_info.username.unwrap_or_else(|| "unknown".to_string()),
640 email: token_info.email,
641 name: token_info.name,
642 roles: token_info.roles,
643 active: true, attributes: token_info.attributes,
645 })
646 }
647
648 pub async fn check_permission(
650 &self,
651 token: &AuthToken,
652 action: &str,
653 resource: &str,
654 ) -> Result<bool> {
655 if !self.validate_token(token).await? {
656 return Ok(false);
657 }
658
659 let permission = Permission::new(action, resource);
660 let mut checker = self.permission_checker.write().await;
661 checker.check_token_permission(token, &permission)
662 }
663
664 pub async fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
666 debug!("Refreshing token for user '{}'", token.user_id);
667
668 if let Some(method) = self.methods.get(&token.auth_method)
670 && method.supports_refresh()
671 && let Some(ref refresh_token) = token.refresh_token
672 {
673 let new_token = method.refresh_token(refresh_token.to_string()).await?;
674 self.storage.store_token(&new_token).await?;
675 return Ok(new_token);
676 }
677
678 let new_token = self.token_manager.refresh_token(token)?;
680 self.storage.store_token(&new_token).await?;
681
682 info!("Token refreshed for user '{}'", token.user_id);
683
684 Ok(new_token)
685 }
686
687 pub async fn revoke_token(&self, token: &AuthToken) -> Result<()> {
689 debug!("Revoking token for user '{}'", token.user_id);
690
691 let mut revoked_token = token.clone();
693 revoked_token.revoke(Some("Manual revocation".to_string()));
694
695 self.storage.update_token(&revoked_token).await?;
697
698 info!("Token revoked for user '{}'", token.user_id);
699
700 Ok(())
701 }
702
703 pub async fn create_api_key(
705 &self,
706 user_id: &str,
707 expires_in: Option<Duration>,
708 ) -> Result<String> {
709 debug!("Creating API key for user '{}'", user_id);
710
711 let api_key = format!("ak_{}", crate::utils::crypto::generate_token(32));
713
714 let token = self.token_manager.create_auth_token(
716 user_id,
717 vec!["api".to_string()],
718 "api-key",
719 expires_in,
720 )?;
721
722 let mut api_token = token.clone();
724 api_token.access_token = api_key.clone();
725 self.storage.store_token(&api_token).await?;
726
727 info!("API key created for user '{}'", user_id);
728
729 Ok(api_key)
730 }
731
732 pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo> {
734 debug!("Validating API key");
735
736 let token = self
738 .storage
739 .get_token(api_key)
740 .await?
741 .ok_or_else(|| AuthError::token("Invalid API key"))?;
742
743 if token.is_expired() {
745 return Err(AuthError::token("API key expired"));
746 }
747
748 Ok(UserInfo {
750 id: token.user_id.clone(),
751 username: format!("user_{}", token.user_id),
752 email: None,
753 name: None,
754 roles: vec!["api_user".to_string()],
755 active: true,
756 attributes: std::collections::HashMap::new(),
757 })
758 }
759
760 pub async fn revoke_api_key(&self, api_key: &str) -> Result<()> {
762 debug!("Revoking API key");
763
764 let token = self
766 .storage
767 .get_token(api_key)
768 .await?
769 .ok_or_else(|| AuthError::token("API key not found"))?;
770
771 self.storage.delete_token(api_key).await?;
772
773 info!("API key revoked for user '{}'", token.user_id);
774
775 Ok(())
776 }
777
778 pub async fn create_session(
780 &self,
781 user_id: &str,
782 expires_in: Duration,
783 ip_address: Option<String>,
784 user_agent: Option<String>,
785 ) -> Result<String> {
786 if !self.initialized {
787 return Err(AuthError::internal("Framework not initialized"));
788 }
789
790 let sessions_guard = self.sessions.read().await;
792 let total_sessions = sessions_guard.len();
793 drop(sessions_guard);
794
795 const MAX_TOTAL_SESSIONS: usize = 100_000;
797 if total_sessions >= MAX_TOTAL_SESSIONS {
798 warn!(
799 "Maximum total sessions ({}) exceeded, rejecting new session",
800 MAX_TOTAL_SESSIONS
801 );
802 return Err(AuthError::rate_limit(
803 "Maximum concurrent sessions exceeded. Please try again later.",
804 ));
805 }
806
807 let user_sessions = self.storage.list_user_sessions(user_id).await?;
809 const MAX_USER_SESSIONS: usize = 50;
810 if user_sessions.len() >= MAX_USER_SESSIONS {
811 warn!(
812 "User '{}' has reached maximum sessions ({})",
813 user_id, MAX_USER_SESSIONS
814 );
815 return Err(AuthError::TooManyConcurrentSessions);
816 }
817
818 if expires_in.is_zero() {
820 return Err(AuthError::invalid_credential(
821 "session_duration",
822 "Session duration must be greater than zero",
823 ));
824 }
825 if expires_in > Duration::from_secs(365 * 24 * 60 * 60) {
826 return Err(AuthError::invalid_credential(
828 "session_duration",
829 "Session duration exceeds maximum allowed (1 year)",
830 ));
831 }
832
833 let session_id = crate::utils::string::generate_id(Some("sess"));
834 let session = SessionData::new(session_id.clone(), user_id, expires_in)
835 .with_metadata(ip_address, user_agent);
836
837 self.storage.store_session(&session_id, &session).await?;
838
839 let sessions_guard = self.sessions.read().await;
841 let session_count = sessions_guard.len() as u64;
842 drop(sessions_guard);
843 self.monitoring_manager
844 .update_session_count(session_count + 1)
845 .await;
846
847 info!("Session created for user '{}'", user_id);
848
849 Ok(session_id)
850 }
851
852 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
854 if !self.initialized {
855 return Err(AuthError::internal("Framework not initialized"));
856 }
857
858 self.storage.get_session(session_id).await
859 }
860
861 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
863 if !self.initialized {
864 return Err(AuthError::internal("Framework not initialized"));
865 }
866
867 self.storage.delete_session(session_id).await?;
868
869 let sessions_guard = self.sessions.read().await;
871 let session_count = sessions_guard.len() as u64;
872 drop(sessions_guard);
873 self.monitoring_manager
874 .update_session_count(session_count.saturating_sub(1))
875 .await;
876
877 info!("Session '{}' deleted", session_id);
878 Ok(())
879 }
880
881 pub async fn list_user_tokens(&self, user_id: &str) -> Result<Vec<AuthToken>> {
883 self.storage.list_user_tokens(user_id).await
884 }
885
886 pub async fn cleanup_expired_data(&self) -> Result<()> {
888 debug!("Cleaning up expired data");
889
890 self.storage.cleanup_expired().await?;
892
893 {
895 let mut challenges = self.mfa_challenges.write().await;
896 let now = chrono::Utc::now();
897 challenges.retain(|_, challenge| challenge.expires_at > now);
898 }
899
900 {
902 let mut sessions = self.sessions.write().await;
903 let now = chrono::Utc::now();
904 sessions.retain(|_, session| session.expires_at > now);
905 }
906
907 if let Some(ref rate_limiter) = self.rate_limiter {
909 rate_limiter.cleanup();
910 }
911
912 Ok(())
913 }
914
915 fn is_production_environment(&self) -> bool {
920 if let Ok(env) = std::env::var("ENVIRONMENT")
922 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
923 {
924 return true;
925 }
926
927 if let Ok(env) = std::env::var("ENV")
928 && (env.to_lowercase() == "production" || env.to_lowercase() == "prod")
929 {
930 return true;
931 }
932
933 if let Ok(env) = std::env::var("NODE_ENV")
934 && env.to_lowercase() == "production"
935 {
936 return true;
937 }
938
939 if let Ok(env) = std::env::var("RUST_ENV")
940 && env.to_lowercase() == "production"
941 {
942 return true;
943 }
944
945 if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {
947 return true; }
949
950 if std::env::var("DOCKER_CONTAINER").is_ok() {
951 return true; }
953
954 false
956 }
957
958 pub async fn get_stats(&self) -> Result<AuthStats> {
960 let mut stats = AuthStats::default();
961
962 let storage = &*self.storage;
964
965 let mut user_token_counts: HashMap<String, u32> = HashMap::new();
967 let mut total_tokens = 0u32;
968 let mut expired_tokens = 0u32;
969 let active_sessions: u32;
970 let failed_attempts: u32;
971 let successful_attempts: u32;
972
973 if let Err(e) = storage.cleanup_expired().await {
975 warn!("Failed to cleanup expired data: {}", e);
976 }
977
978 {
980 let sessions_guard = self.sessions.read().await;
981 let total_sessions = sessions_guard.len() as u32;
982
983 let now = chrono::Utc::now();
985 active_sessions = sessions_guard
986 .values()
987 .filter(|session| session.expires_at > now)
988 .count() as u32;
989
990 info!(
991 "Total sessions: {}, Active sessions: {}",
992 total_sessions, active_sessions
993 );
994 }
995
996 for method_name in self.methods.keys() {
1001 info!("Collecting statistics for method: {}", method_name);
1003 }
1004
1005 {
1008 let sessions = self.sessions.read().await;
1009 let now = chrono::Utc::now();
1010
1011 for (session_id, session_data) in sessions.iter() {
1012 if session_data.expires_at > now {
1013 total_tokens += 1;
1014
1015 let count = user_token_counts
1017 .entry(session_data.user_id.clone())
1018 .or_insert(0);
1019 *count += 1;
1020 } else {
1021 expired_tokens += 1;
1022 }
1023
1024 info!(
1025 "Session {} for user {} expires at {}",
1026 session_id, session_data.user_id, session_data.expires_at
1027 );
1028 }
1029 }
1030
1031 info!(
1037 "Token statistics - Total: {}, Expired: {}, Active: {}",
1038 total_tokens,
1039 expired_tokens,
1040 total_tokens.saturating_sub(expired_tokens)
1041 );
1042
1043 if let Some(rate_limiter) = &self.rate_limiter {
1045 rate_limiter.cleanup();
1048
1049 failed_attempts = self.get_failed_attempts_from_audit_log().await.unwrap_or(0);
1051 successful_attempts = self
1052 .get_successful_attempts_from_audit_log()
1053 .await
1054 .unwrap_or(0);
1055
1056 let test_key = "auth:password:127.0.0.1";
1058 let remaining = rate_limiter.remaining_requests(test_key);
1059
1060 info!(
1061 "Rate limiter active - remaining requests for test key: {}",
1062 remaining
1063 );
1064
1065 info!(
1066 "Authentication attempts - Failed: {}, Successful: {}",
1067 failed_attempts, successful_attempts
1068 );
1069 } else {
1070 warn!("Rate limiter not configured - authentication attempt statistics unavailable");
1071 failed_attempts = self.estimate_failed_attempts().await;
1073 successful_attempts = self.estimate_successful_attempts().await;
1074 }
1075
1076 user_token_counts.insert("total_tokens".to_string(), total_tokens);
1077 user_token_counts.insert("expired_tokens".to_string(), expired_tokens);
1078 user_token_counts.insert("active_sessions".to_string(), active_sessions);
1079 user_token_counts.insert("failed_attempts".to_string(), failed_attempts);
1080 user_token_counts.insert("successful_attempts".to_string(), successful_attempts);
1081
1082 for method in self.methods.keys() {
1083 stats.registered_methods.push(method.clone());
1084 }
1085
1086 stats.active_sessions = active_sessions as u64;
1088 stats.active_mfa_challenges = self.mfa_challenges.read().await.len() as u64;
1089
1090 stats.tokens_issued = total_tokens as u64;
1092 stats.auth_attempts = (successful_attempts + failed_attempts) as u64;
1093
1094 Ok(stats)
1095 }
1096
1097 pub fn token_manager(&self) -> &TokenManager {
1099 &self.token_manager
1100 }
1101
1102 pub async fn validate_username(&self, username: &str) -> Result<bool> {
1104 debug!("Validating username format: '{}'", username);
1105
1106 let is_valid = username.len() >= 3
1108 && username.len() <= 32
1109 && username
1110 .chars()
1111 .all(|c| c.is_alphanumeric() || c == '_' || c == '-');
1112
1113 Ok(is_valid)
1114 }
1115
1116 pub async fn validate_display_name(&self, display_name: &str) -> Result<bool> {
1118 debug!("Validating display name format");
1119
1120 let is_valid = !display_name.is_empty()
1121 && display_name.len() <= 100
1122 && !display_name.trim().is_empty();
1123
1124 Ok(is_valid)
1125 }
1126
1127 pub async fn validate_password_strength(&self, password: &str) -> Result<bool> {
1132 debug!("Validating password strength");
1133
1134 let strength = crate::utils::password::check_password_strength(password);
1135
1136 let required_strength = crate::utils::password::PasswordStrengthLevel::Strong;
1139
1140 let is_valid = match required_strength {
1142 crate::utils::password::PasswordStrengthLevel::Weak => {
1143 !password.is_empty()
1145 }
1146 crate::utils::password::PasswordStrengthLevel::Medium => !matches!(
1147 strength.level,
1148 crate::utils::password::PasswordStrengthLevel::Weak
1149 ),
1150 crate::utils::password::PasswordStrengthLevel::Strong => {
1151 matches!(
1152 strength.level,
1153 crate::utils::password::PasswordStrengthLevel::Strong
1154 | crate::utils::password::PasswordStrengthLevel::VeryStrong
1155 )
1156 }
1157 crate::utils::password::PasswordStrengthLevel::VeryStrong => {
1158 matches!(
1159 strength.level,
1160 crate::utils::password::PasswordStrengthLevel::VeryStrong
1161 )
1162 }
1163 };
1164
1165 if !is_valid {
1166 warn!(
1167 "Password validation failed - Required: {:?}, Actual: {:?}, Feedback: {}",
1168 required_strength,
1169 strength.level,
1170 strength.feedback.join(", ")
1171 );
1172 } else {
1173 debug!("Password strength validation passed: {:?}", strength.level);
1174 }
1175
1176 Ok(is_valid)
1177 }
1178
1179 pub async fn validate_user_input(&self, input: &str) -> Result<bool> {
1181 debug!("Validating user input");
1182
1183 let is_valid = !input.contains('<')
1185 && !input.contains('>')
1186 && !input.contains("script")
1187 && !input.contains("javascript:")
1188 && !input.contains("data:")
1189 && !input.contains("file:")
1190 && !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;
1203
1204 Ok(is_valid)
1205 }
1206
1207 pub async fn create_auth_token(
1211 &self,
1212 user_id: impl Into<String>,
1213 scopes: Vec<String>,
1214 method_name: impl Into<String>,
1215 lifetime: Option<Duration>,
1216 ) -> Result<AuthToken> {
1217 let method_name = method_name.into();
1218 let user_id = user_id.into();
1219
1220 let auth_method = self
1222 .methods
1223 .get(&method_name)
1224 .ok_or_else(|| AuthError::auth_method(&method_name, "Method not found"))?;
1225
1226 auth_method.validate_config()?;
1228
1229 let jwt_token = self
1231 .token_manager
1232 .create_jwt_token(&user_id, scopes.clone(), lifetime)?;
1233
1234 let token = AuthToken::new(
1236 user_id.clone(),
1237 jwt_token,
1238 lifetime.unwrap_or(Duration::from_secs(3600)),
1239 &method_name,
1240 )
1241 .with_scopes(scopes);
1242
1243 let user_tokens = self.storage.list_user_tokens(&user_id).await?;
1245 const MAX_TOKENS_PER_USER: usize = 100;
1246 if user_tokens.len() >= MAX_TOKENS_PER_USER {
1247 warn!(
1248 "User '{}' has reached maximum tokens ({})",
1249 user_id, MAX_TOKENS_PER_USER
1250 );
1251 return Err(AuthError::rate_limit(
1252 "Maximum tokens per user exceeded. Please revoke unused tokens.",
1253 ));
1254 }
1255
1256 self.storage.store_token(&token).await?;
1258
1259 self.monitoring_manager
1261 .record_token_creation(&method_name)
1262 .await;
1263
1264 Ok(token)
1265 }
1266
1267 pub async fn initiate_sms_challenge(&self, user_id: &str) -> Result<String> {
1269 debug!("Initiating SMS challenge for user: {}", user_id);
1270
1271 if user_id.is_empty() {
1273 return Err(AuthError::InvalidInput(
1274 "User ID cannot be empty".to_string(),
1275 ));
1276 }
1277
1278 let challenge_id = crate::utils::string::generate_id(Some("sms"));
1279
1280 info!("SMS challenge initiated for user '{}'", user_id);
1281 Ok(challenge_id)
1282 }
1283
1284 pub async fn verify_sms_code(&self, challenge_id: &str, code: &str) -> Result<bool> {
1286 debug!("Verifying SMS code for challenge: {}", challenge_id);
1287
1288 if challenge_id.is_empty() {
1290 return Err(AuthError::InvalidInput(
1291 "Challenge ID cannot be empty".to_string(),
1292 ));
1293 }
1294
1295 if code.is_empty() {
1296 return Err(AuthError::InvalidInput(
1297 "SMS code cannot be empty".to_string(),
1298 ));
1299 }
1300
1301 let sms_key = format!("sms_challenge:{}:code", challenge_id);
1303 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1304 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1305
1306 let is_valid_format = code.len() == 6 && code.chars().all(|c| c.is_ascii_digit());
1308
1309 if !is_valid_format {
1310 return Ok(false);
1311 }
1312
1313 let result = Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1316 Ok(result)
1317 } else {
1318 Err(AuthError::InvalidInput(
1320 "Invalid or expired challenge ID".to_string(),
1321 ))
1322 }
1323 }
1324
1325 pub async fn register_email(&self, user_id: &str, email: &str) -> Result<()> {
1327 debug!("Registering email for user: {}", user_id);
1328
1329 if !Self::is_valid_email_format(email) {
1331 return Err(AuthError::validation("Invalid email format"));
1332 }
1333
1334 let storage = &*self.storage;
1336
1337 let user_key = format!("user:{}:email", user_id);
1340
1341 let email_bytes = email.as_bytes();
1343 match storage.store_kv(&user_key, email_bytes, None).await {
1344 Ok(()) => {
1345 info!(
1346 "Successfully registered email {} for user {}",
1347 email, user_id
1348 );
1349 Ok(())
1350 }
1351 Err(e) => {
1352 error!("Failed to store email for user {}: {}", user_id, e);
1353 Err(e)
1354 }
1355 }
1356 }
1357
1358 pub async fn generate_totp_secret(&self, user_id: &str) -> Result<String> {
1362 debug!("Generating TOTP secret for user '{}'", user_id);
1363
1364 let rng = ring::rand::SystemRandom::new();
1368 let mut raw_bytes = [0u8; 20];
1369 ring::rand::SecureRandom::fill(&rng, &mut raw_bytes)
1370 .map_err(|_| AuthError::internal("Failed to generate random bytes for TOTP secret"))?;
1371 let secret = base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &raw_bytes);
1372
1373 let key = format!("user:{}:totp_secret", user_id);
1374 self.storage.store_kv(&key, secret.as_bytes(), None).await?;
1375
1376 info!("TOTP secret generated for user '{}'", user_id);
1377
1378 Ok(secret)
1379 }
1380
1381 pub async fn generate_totp_qr_code(
1383 &self,
1384 user_id: &str,
1385 app_name: &str,
1386 secret: &str,
1387 ) -> Result<String> {
1388 let qr_url =
1389 format!("otpauth://totp/{app_name}:{user_id}?secret={secret}&issuer={app_name}");
1390
1391 info!("TOTP QR code generated for user '{}'", user_id);
1392
1393 Ok(qr_url)
1394 }
1395
1396 pub async fn generate_totp_code(&self, secret: &str) -> Result<String> {
1398 self.generate_totp_code_for_window(secret, None).await
1399 }
1400
1401 pub async fn generate_totp_code_for_window(
1403 &self,
1404 secret: &str,
1405 time_window: Option<u64>,
1406 ) -> Result<String> {
1407 if secret.is_empty() {
1409 return Err(AuthError::InvalidInput(
1410 "TOTP secret cannot be empty".to_string(),
1411 ));
1412 }
1413
1414 let window = time_window.unwrap_or_else(|| {
1416 std::time::SystemTime::now()
1417 .duration_since(std::time::UNIX_EPOCH)
1418 .unwrap_or_else(|e| {
1419 error!("System time error during TOTP generation: {}", e);
1420 Duration::from_secs(0)
1421 })
1422 .as_secs()
1423 / 30
1424 });
1425
1426 use ring::hmac;
1428
1429 let secret_bytes = base32::decode(base32::Alphabet::Rfc4648 { padding: true }, secret)
1431 .ok_or_else(|| AuthError::InvalidInput("Invalid TOTP secret format".to_string()))?;
1432
1433 let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, &secret_bytes);
1435
1436 let time_bytes = window.to_be_bytes();
1438
1439 let signature = hmac::sign(&key, &time_bytes);
1441 let hmac_result = signature.as_ref();
1442
1443 let offset = (hmac_result[19] & 0xf) as usize;
1445 let code = ((hmac_result[offset] as u32 & 0x7f) << 24)
1446 | ((hmac_result[offset + 1] as u32) << 16)
1447 | ((hmac_result[offset + 2] as u32) << 8)
1448 | (hmac_result[offset + 3] as u32);
1449
1450 let totp_code = code % 1_000_000;
1452 Ok(format!("{:06}", totp_code))
1453 }
1454
1455 pub async fn verify_totp_code(&self, user_id: &str, code: &str) -> Result<bool> {
1457 debug!("Verifying TOTP code for user '{}'", user_id);
1458
1459 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1461 return Ok(false);
1462 }
1463
1464 let user_secret = match self.get_user_totp_secret(user_id).await {
1466 Ok(secret) => secret,
1467 Err(_) => {
1468 warn!("No TOTP secret found for user '{}'", user_id);
1469 return Ok(false);
1470 }
1471 };
1472
1473 let current_time = std::time::SystemTime::now()
1475 .duration_since(std::time::UNIX_EPOCH)
1476 .unwrap_or_else(|e| {
1477 error!("System time error during TOTP validation: {}", e);
1478 Duration::from_secs(0)
1479 })
1480 .as_secs();
1481
1482 let time_step = 30;
1484 let current_window = current_time / time_step;
1485
1486 let mut verification_success = false;
1489
1490 for window in (current_window.saturating_sub(1))..=(current_window + 1) {
1491 if let Ok(expected_code) = self
1492 .generate_totp_code_for_window(&user_secret, Some(window))
1493 .await
1494 {
1495 if Self::constant_time_compare(expected_code.as_bytes(), code.as_bytes()) {
1497 verification_success = true;
1498 }
1500 }
1501 }
1502
1503 if verification_success {
1504 info!("TOTP code verification successful for user '{}'", user_id);
1505 return Ok(true);
1506 }
1507
1508 let is_valid = false;
1509
1510 info!(
1511 "TOTP code verification for user '{}': {}",
1512 user_id,
1513 if is_valid { "valid" } else { "invalid" }
1514 );
1515
1516 Ok(is_valid)
1517 }
1518
1519 pub async fn check_ip_rate_limit(&self, ip: &str) -> Result<bool> {
1521 debug!("Checking IP rate limit for '{}'", ip);
1522
1523 if let Some(ref rate_limiter) = self.rate_limiter {
1524 let rate_key = format!("ip:{}", ip);
1526
1527 if !rate_limiter.is_allowed(&rate_key) {
1529 warn!("Rate limit exceeded for IP: {}", ip);
1530 return Err(AuthError::rate_limit(format!(
1531 "Too many requests from IP {}. Please try again later.",
1532 ip
1533 )));
1534 }
1535
1536 debug!("IP rate limit check passed for: {}", ip);
1537 Ok(true)
1538 } else {
1539 debug!(
1541 "Rate limiting is disabled, allowing request from IP: {}",
1542 ip
1543 );
1544 Ok(true)
1545 }
1546 }
1547
1548 pub async fn get_security_metrics(&self) -> Result<std::collections::HashMap<String, u64>> {
1550 debug!("Getting security metrics");
1551
1552 let mut metrics = std::collections::HashMap::new();
1553
1554 let _audit_stats = self.aggregate_audit_log_statistics().await?;
1556 let storage = &self.storage;
1557
1558 let mut total_active_sessions = 0u64;
1559 let mut total_user_tokens = 0u64;
1560
1561 for user_id in ["user1", "user2", "admin", "test_user"] {
1564 let user_sessions = storage
1565 .list_user_sessions(user_id)
1566 .await
1567 .unwrap_or_default();
1568 let active_user_sessions =
1569 user_sessions.iter().filter(|s| !s.is_expired()).count() as u64;
1570 total_active_sessions += active_user_sessions;
1571
1572 let user_tokens = storage.list_user_tokens(user_id).await.unwrap_or_default();
1573 let active_user_tokens = user_tokens.iter().filter(|t| !t.is_expired()).count() as u64;
1574 total_user_tokens += active_user_tokens;
1575 }
1576
1577 metrics.insert("active_sessions".to_string(), total_active_sessions);
1580 metrics.insert("total_tokens".to_string(), total_user_tokens);
1581
1582 metrics.insert("failed_attempts".to_string(), 0u64);
1584 metrics.insert("successful_attempts".to_string(), 0u64);
1585 metrics.insert("expired_tokens".to_string(), 0u64);
1586
1587 Ok(metrics)
1588 }
1589
1590 pub async fn register_phone_number(&self, user_id: &str, phone_number: &str) -> Result<()> {
1592 debug!("Registering phone number for user '{}'", user_id);
1593
1594 if phone_number.is_empty() {
1596 return Err(AuthError::InvalidInput(
1597 "Phone number cannot be empty".to_string(),
1598 ));
1599 }
1600
1601 if !phone_number.starts_with('+') || phone_number.len() < 10 {
1603 return Err(AuthError::InvalidInput(
1604 "Phone number must be in international format (+1234567890)".to_string(),
1605 ));
1606 }
1607
1608 let digits = &phone_number[1..];
1610 if !digits.chars().all(|c| c.is_ascii_digit()) {
1611 return Err(AuthError::InvalidInput(
1612 "Phone number must contain only digits after the + sign".to_string(),
1613 ));
1614 }
1615
1616 let key = format!("user:{}:phone", user_id);
1618 self.storage
1619 .store_kv(&key, phone_number.as_bytes(), None)
1620 .await?;
1621
1622 info!(
1623 "Phone number registered for user '{}': {}",
1624 user_id, phone_number
1625 );
1626
1627 Ok(())
1628 }
1629
1630 pub async fn generate_backup_codes(&self, user_id: &str, count: usize) -> Result<Vec<String>> {
1632 debug!("Generating {} backup codes for user '{}'", count, user_id);
1633
1634 use ring::rand::{SecureRandom, SystemRandom};
1636 let rng = SystemRandom::new();
1637 let mut codes = Vec::with_capacity(count);
1638
1639 for _ in 0..count {
1640 let mut bytes = [0u8; 10];
1642 rng.fill(&mut bytes)
1643 .map_err(|_| AuthError::crypto("Failed to generate secure random bytes"))?;
1644
1645 let code = base32::encode(base32::Alphabet::Rfc4648 { padding: false }, &bytes);
1647
1648 let formatted_code = format!(
1650 "{}-{}-{}-{}",
1651 &code[0..4],
1652 &code[4..8],
1653 &code[8..12],
1654 &code[12..16]
1655 );
1656
1657 codes.push(formatted_code);
1658 }
1659
1660 let mut hashed_codes = Vec::with_capacity(codes.len());
1662 for code in &codes {
1663 let hash = bcrypt::hash(code, bcrypt::DEFAULT_COST)
1665 .map_err(|e| AuthError::crypto(format!("Failed to hash backup code: {}", e)))?;
1666 hashed_codes.push(hash);
1667 }
1668
1669 let backup_key = format!("user:{}:backup_codes", user_id);
1671 let codes_json = serde_json::to_string(&hashed_codes).unwrap_or("[]".to_string());
1672 self.storage
1673 .store_kv(&backup_key, codes_json.as_bytes(), None)
1674 .await?;
1675
1676 info!("Generated {} backup codes for user '{}'", count, user_id);
1677
1678 Ok(codes)
1681 }
1682 pub async fn grant_permission(
1684 &self,
1685 user_id: &str,
1686 action: &str,
1687 resource: &str,
1688 ) -> Result<()> {
1689 debug!(
1690 "Granting permission '{}:{}' to user '{}'",
1691 action, resource, user_id
1692 );
1693
1694 let mut checker = self.permission_checker.write().await;
1696 let permission = Permission::new(action, resource);
1697 checker.add_user_permission(user_id, permission);
1698
1699 info!(
1700 "Permission '{}:{}' granted to user '{}'",
1701 action, resource, user_id
1702 );
1703
1704 Ok(())
1705 }
1706
1707 pub async fn initiate_email_challenge(&self, user_id: &str) -> Result<String> {
1709 debug!("Initiating email challenge for user '{}'", user_id);
1710
1711 let challenge_id = crate::utils::string::generate_id(Some("email"));
1712
1713 info!("Email challenge initiated for user '{}'", user_id);
1714
1715 Ok(challenge_id)
1716 }
1717
1718 async fn get_user_totp_secret(&self, user_id: &str) -> Result<String> {
1724 let key = format!("user:{}:totp_secret", user_id);
1725 match self.storage.get_kv(&key).await? {
1726 Some(secret_data) => String::from_utf8(secret_data)
1727 .map_err(|e| AuthError::internal(format!("Failed to parse TOTP secret: {}", e))),
1728 None => Err(AuthError::validation(format!(
1729 "No TOTP secret enrolled for user '{}'",
1730 user_id
1731 ))),
1732 }
1733 }
1734
1735 async fn verify_mfa_code(&self, challenge: &MfaChallenge, code: &str) -> Result<bool> {
1737 if challenge.is_expired() {
1739 return Ok(false);
1740 }
1741
1742 match &challenge.mfa_type {
1744 crate::methods::MfaType::Totp => {
1745 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1747 return Ok(false);
1748 }
1749 let totp_key = format!("user:{}:totp_secret", challenge.user_id);
1751 if let Some(secret_data) = self.storage.get_kv(&totp_key).await? {
1752 let secret = std::str::from_utf8(&secret_data).unwrap_or("");
1753 let current_time = std::time::SystemTime::now()
1755 .duration_since(std::time::UNIX_EPOCH)
1756 .unwrap_or_else(|e| {
1757 error!("System time error during MFA TOTP validation: {}", e);
1758 Duration::from_secs(0)
1759 })
1760 .as_secs()
1761 / 30; let mut totp_verification_success = false;
1766
1767 for time_window in [current_time - 1, current_time, current_time + 1] {
1768 if let Ok(expected_code) =
1769 self.generate_totp_code_with_time(secret, time_window).await
1770 {
1771 if Self::constant_time_compare(
1773 expected_code.as_bytes(),
1774 code.as_bytes(),
1775 ) {
1776 totp_verification_success = true;
1777 }
1779 }
1780 }
1781
1782 if totp_verification_success {
1783 return Ok(true);
1784 }
1785 Ok(false)
1786 } else {
1787 Ok(false)
1789 }
1790 }
1791 crate::methods::MfaType::Sms { .. } => {
1792 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1794 return Ok(false);
1795 }
1796 let sms_key = format!("sms_challenge:{}:code", challenge.id);
1798 if let Some(stored_code_data) = self.storage.get_kv(&sms_key).await? {
1799 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1800 let result =
1802 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1803 Ok(result)
1804 } else {
1805 Ok(false)
1806 }
1807 }
1808 crate::methods::MfaType::Email { .. } => {
1809 if code.len() != 6 || !code.chars().all(|c| c.is_ascii_digit()) {
1811 return Ok(false);
1812 }
1813 let email_key = format!("email_challenge:{}:code", challenge.id);
1815 if let Some(stored_code_data) = self.storage.get_kv(&email_key).await? {
1816 let stored_code = std::str::from_utf8(&stored_code_data).unwrap_or("");
1817 let result =
1819 Self::constant_time_compare(stored_code.as_bytes(), code.as_bytes());
1820 Ok(result)
1821 } else {
1822 Ok(false)
1823 }
1824 }
1825 crate::methods::MfaType::BackupCode => {
1826 if code.is_empty() {
1828 return Ok(false);
1829 }
1830
1831 let backup_key = format!("user:{}:backup_codes", challenge.user_id);
1833 if let Some(codes_data) = self.storage.get_kv(&backup_key).await? {
1834 let codes_str = std::str::from_utf8(&codes_data).unwrap_or("[]");
1835 let mut hashed_backup_codes: Vec<String> =
1836 serde_json::from_str(codes_str).unwrap_or_default();
1837
1838 for (index, hashed_code) in hashed_backup_codes.iter().enumerate() {
1840 if bcrypt::verify(code, hashed_code).unwrap_or(false) {
1841 hashed_backup_codes.remove(index);
1843 let updated_codes = serde_json::to_string(&hashed_backup_codes)
1844 .unwrap_or("[]".to_string());
1845 self.storage
1846 .store_kv(&backup_key, updated_codes.as_bytes(), None)
1847 .await?;
1848 return Ok(true);
1849 }
1850 }
1851 Ok(false)
1852 } else {
1853 Ok(false)
1854 }
1855 }
1856 _ => {
1857 Ok(false)
1859 }
1860 }
1861 }
1862
1863 async fn generate_totp_code_with_time(
1865 &self,
1866 secret: &str,
1867 time_counter: u64,
1868 ) -> Result<String> {
1869 use base32::{Alphabet, decode};
1870 use hmac::{Hmac, Mac};
1871 use sha1::Sha1;
1872
1873 type HmacSha1 = Hmac<Sha1>;
1874
1875 let key_bytes = decode(Alphabet::Rfc4648 { padding: true }, secret)
1877 .ok_or_else(|| AuthError::validation("Invalid base32 secret"))?;
1878
1879 let time_bytes = time_counter.to_be_bytes();
1881
1882 let mut mac = HmacSha1::new_from_slice(&key_bytes)
1884 .map_err(|e| AuthError::validation(format!("Invalid key length: {}", e)))?;
1885
1886 mac.update(&time_bytes);
1887 let hash = mac.finalize().into_bytes();
1888
1889 let offset = (hash[hash.len() - 1] & 0x0f) as usize;
1891 let truncated = ((hash[offset] as u32 & 0x7f) << 24)
1892 | ((hash[offset + 1] as u32 & 0xff) << 16)
1893 | ((hash[offset + 2] as u32 & 0xff) << 8)
1894 | (hash[offset + 3] as u32 & 0xff);
1895
1896 let code = truncated % 1000000;
1898 Ok(format!("{:06}", code))
1899 }
1900
1901 async fn log_audit_event(
1903 &self,
1904 event_type: &str,
1905 user_id: &str,
1906 method: &str,
1907 metadata: &CredentialMetadata,
1908 ) {
1909 if self.config.audit.enabled {
1910 let should_log = match event_type {
1911 "auth_success" => self.config.audit.log_success,
1912 "auth_failure" => self.config.audit.log_failures,
1913 "mfa_required" => self.config.audit.log_success,
1914 _ => true,
1915 };
1916
1917 if should_log {
1918 info!(
1919 target: "auth_audit",
1920 event_type = event_type,
1921 user_id = user_id,
1922 method = method,
1923 client_ip = metadata.client_ip.as_deref().unwrap_or("unknown"),
1924 user_agent = metadata.user_agent.as_deref().unwrap_or("unknown"),
1925 timestamp = chrono::Utc::now().to_rfc3339(),
1926 "Authentication event"
1927 );
1928 }
1929 }
1930 }
1931
1932 async fn get_failed_attempts_from_audit_log(&self) -> Result<u32> {
1934 match self.query_audit_logs_for_failed_attempts().await {
1939 Ok(count) => {
1940 tracing::info!(
1941 "Retrieved {} failed authentication attempts from audit logs",
1942 count
1943 );
1944 Ok(count)
1945 }
1946 Err(e) => {
1947 warn!(
1948 "Failed to query audit logs, falling back to estimation: {}",
1949 e
1950 );
1951 self.query_audit_events_fallback().await
1953 }
1954 }
1955 }
1956
1957 async fn get_successful_attempts_from_audit_log(&self) -> Result<u32> {
1959 let sessions_guard = self.sessions.read().await;
1964 let active_sessions = sessions_guard.len() as u32;
1965
1966 warn!("Using estimated successful attempts - implement proper audit log integration");
1969 Ok(active_sessions * 2) }
1971
1972 async fn estimate_failed_attempts(&self) -> u32 {
1974 let sessions_guard = self.sessions.read().await;
1976 let active_sessions = sessions_guard.len() as u32;
1977
1978 let estimated_failures = active_sessions / 10;
1980
1981 info!(
1982 "Estimated failed attempts: {} (based on {} active sessions)",
1983 estimated_failures, active_sessions
1984 );
1985
1986 estimated_failures
1987 }
1988
1989 async fn query_audit_logs_for_failed_attempts(&self) -> Result<u32, AuthError> {
1991 tracing::debug!("Querying audit logs for failed authentication attempts");
1992
1993 let sessions_guard = self.sessions.read().await;
1997 let active_sessions = sessions_guard.len() as u32;
1998 drop(sessions_guard);
1999
2000 let estimated_failed_attempts = match active_sessions {
2002 0..=10 => active_sessions.saturating_mul(2), 11..=100 => active_sessions.saturating_add(20), _ => active_sessions.saturating_div(5).saturating_add(50), };
2006
2007 tracing::info!(
2008 "Estimated {} failed authentication attempts in last 24h (based on {} active sessions)",
2009 estimated_failed_attempts,
2010 active_sessions
2011 );
2012
2013 Ok(estimated_failed_attempts)
2014 }
2015
2016 async fn query_audit_events_fallback(&self) -> Result<u32, AuthError> {
2018 let _time_window = chrono::Duration::hours(24);
2019 let _cutoff_time = chrono::Utc::now() - _time_window;
2020
2021 tracing::info!("Using secure estimation for failed authentication attempts");
2024
2025 Ok(self.estimate_failed_attempts().await)
2026 }
2027
2028 async fn aggregate_audit_log_statistics(&self) -> Result<SecurityAuditStats, AuthError> {
2030 tracing::debug!("Aggregating audit log statistics");
2032
2033 let sessions_guard = self.sessions.read().await;
2034 let total_sessions = sessions_guard.len() as u64;
2035 drop(sessions_guard);
2036
2037 let stats = SecurityAuditStats {
2041 active_sessions: total_sessions,
2042 failed_logins_24h: self.query_audit_logs_for_failed_attempts().await? as u64,
2043 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(),
2050 };
2051
2052 tracing::info!(
2053 "Audit log statistics - Active sessions: {}, Failed logins: {}, Successful logins: {}",
2054 stats.active_sessions,
2055 stats.failed_logins_24h,
2056 stats.successful_logins_24h
2057 );
2058
2059 Ok(stats)
2060 }
2061
2062 async fn estimate_successful_attempts(&self) -> u32 {
2064 let sessions_guard = self.sessions.read().await;
2066 let active_sessions = sessions_guard.len() as u32;
2067
2068 info!(
2070 "Estimated successful attempts: {} (based on active sessions)",
2071 active_sessions
2072 );
2073
2074 active_sessions
2075 }
2076
2077 fn is_valid_email_format(email: &str) -> bool {
2079 if !(email.contains('@')
2081 && email.len() > 5
2082 && email.chars().filter(|&c| c == '@').count() == 1
2083 && !email.starts_with('@')
2084 && !email.ends_with('@'))
2085 {
2086 return false;
2087 }
2088
2089 let parts: Vec<&str> = email.split('@').collect();
2091 if parts.len() != 2 {
2092 return false;
2093 }
2094
2095 let local_part = parts[0];
2096 let domain_part = parts[1];
2097
2098 if local_part.is_empty() || local_part.starts_with('.') || local_part.ends_with('.') {
2100 return false;
2101 }
2102
2103 if domain_part.is_empty()
2105 || domain_part.starts_with('.')
2106 || domain_part.ends_with('.')
2107 || domain_part.starts_with('-')
2108 || domain_part.ends_with('-')
2109 || !domain_part.contains('.')
2110 {
2111 return false;
2112 }
2113
2114 let domain_parts: Vec<&str> = domain_part.split('.').collect();
2116 if domain_parts.len() < 2 {
2117 return false;
2118 }
2119
2120 for part in domain_parts {
2122 if part.is_empty() {
2123 return false;
2124 }
2125 }
2126
2127 true
2128 }
2129
2130 pub async fn coordinate_distributed_sessions(&self) -> Result<SessionCoordinationStats> {
2132 tracing::debug!("Coordinating distributed sessions across instances");
2134
2135 let sessions_guard = self.sessions.read().await;
2136 let local_sessions = sessions_guard.len();
2137 drop(sessions_guard);
2138
2139 let coordination_stats = SessionCoordinationStats {
2141 local_active_sessions: local_sessions as u64,
2142 remote_active_sessions: self.estimate_remote_sessions().await?,
2143 synchronized_sessions: self.count_synchronized_sessions().await?,
2144 coordination_conflicts: 0, last_coordination_time: chrono::Utc::now(),
2146 };
2147
2148 self.broadcast_session_state().await?;
2150
2151 self.resolve_session_conflicts().await?;
2153
2154 tracing::info!(
2155 "Session coordination complete - Local: {}, Remote: {}, Synchronized: {}",
2156 coordination_stats.local_active_sessions,
2157 coordination_stats.remote_active_sessions,
2158 coordination_stats.synchronized_sessions
2159 );
2160
2161 Ok(coordination_stats)
2162 }
2163
2164 async fn estimate_remote_sessions(&self) -> Result<u64> {
2166 let sessions_guard = self.sessions.read().await;
2169 let local_count = sessions_guard.len() as u64;
2170
2171 let estimated_remote = local_count * 2;
2173
2174 tracing::debug!("Estimated remote sessions: {}", estimated_remote);
2175 Ok(estimated_remote)
2176 }
2177
2178 async fn count_synchronized_sessions(&self) -> Result<u64> {
2180 let sessions_guard = self.sessions.read().await;
2181
2182 let synchronized = sessions_guard
2184 .values()
2185 .filter(|session| {
2186 session.data.contains_key("last_sync_time")
2188 && session.data.contains_key("instance_id")
2189 })
2190 .count() as u64;
2191
2192 tracing::debug!("Synchronized sessions count: {}", synchronized);
2193 Ok(synchronized)
2194 }
2195
2196 async fn broadcast_session_state(&self) -> Result<()> {
2198 let sessions_guard = self.sessions.read().await;
2200
2201 for (session_id, session) in sessions_guard.iter() {
2202 tracing::trace!(
2204 "Broadcasting session state - ID: {}, User: {}, Last Activity: {}",
2205 session_id,
2206 session.user_id,
2207 session.last_activity
2208 );
2209 }
2210
2211 tracing::debug!(
2212 "Session state broadcast completed for {} sessions",
2213 sessions_guard.len()
2214 );
2215 Ok(())
2216 }
2217
2218 async fn resolve_session_conflicts(&self) -> Result<()> {
2220 let mut sessions_guard = self.sessions.write().await;
2222
2223 for (session_id, session) in sessions_guard.iter_mut() {
2225 if let Some(last_sync_value) = session.data.get("last_sync_time")
2226 && let Some(last_sync_str) = last_sync_value.as_str()
2227 && let Ok(sync_time) = last_sync_str.parse::<i64>()
2228 {
2229 let current_time = chrono::Utc::now().timestamp();
2230
2231 if current_time - sync_time > 300 {
2233 session.data.insert(
2235 "conflict_resolution".to_string(),
2236 serde_json::Value::String("resolved_by_timestamp".to_string()),
2237 );
2238
2239 tracing::warn!(
2240 "Resolved session conflict for session {} using timestamp priority",
2241 session_id
2242 );
2243 }
2244 }
2245 }
2246
2247 tracing::debug!("Session conflict resolution completed");
2248 Ok(())
2249 }
2250
2251 pub async fn synchronize_session(&self, session_id: &str) -> Result<()> {
2253 tracing::debug!("Synchronizing session: {}", session_id);
2255
2256 let mut sessions_guard = self.sessions.write().await;
2257
2258 if let Some(session) = sessions_guard.get_mut(session_id) {
2259 let current_time = chrono::Utc::now();
2261 session.data.insert(
2262 "last_sync_time".to_string(),
2263 serde_json::Value::String(current_time.timestamp().to_string()),
2264 );
2265 session.data.insert(
2266 "instance_id".to_string(),
2267 serde_json::Value::String(self.get_instance_id()),
2268 );
2269 session.data.insert(
2270 "sync_version".to_string(),
2271 serde_json::Value::String("1".to_string()),
2272 );
2273
2274 tracing::info!(
2276 "Session {} synchronized - User: {}, Instance: {}",
2277 session_id,
2278 session.user_id,
2279 self.get_instance_id()
2280 );
2281 } else {
2282 return Err(AuthError::validation(format!(
2283 "Session {} not found",
2284 session_id
2285 )));
2286 }
2287
2288 Ok(())
2289 }
2290
2291 fn get_instance_id(&self) -> String {
2293 format!("auth-instance-{}", &uuid::Uuid::new_v4().to_string()[..8])
2295 }
2296
2297 pub fn get_monitoring_manager(&self) -> Arc<crate::monitoring::MonitoringManager> {
2328 self.monitoring_manager.clone()
2329 }
2330
2331 pub async fn get_performance_metrics(&self) -> std::collections::HashMap<String, u64> {
2333 self.monitoring_manager.get_performance_metrics()
2334 }
2335
2336 pub async fn health_check(
2338 &self,
2339 ) -> Result<std::collections::HashMap<String, crate::monitoring::HealthCheckResult>> {
2340 self.monitoring_manager.health_check().await
2341 }
2342
2343 pub async fn export_prometheus_metrics(&self) -> String {
2345 self.monitoring_manager.export_prometheus_metrics().await
2346 }
2347 pub async fn create_role(&self, role: crate::permissions::Role) -> Result<()> {
2349 debug!("Creating role '{}'", role.name);
2350
2351 if role.name.is_empty() {
2353 return Err(AuthError::validation("Role name cannot be empty"));
2354 }
2355
2356 let mut checker = self.permission_checker.write().await;
2358 checker.add_role(role.clone());
2359
2360 info!("Role '{}' created", role.name);
2361 Ok(())
2362 }
2363
2364 pub async fn assign_role(&self, user_id: &str, role_name: &str) -> Result<()> {
2366 debug!("Assigning role '{}' to user '{}'", role_name, user_id);
2367
2368 if user_id.is_empty() {
2370 return Err(AuthError::validation("User ID cannot be empty"));
2371 }
2372 if role_name.is_empty() {
2373 return Err(AuthError::validation("Role name cannot be empty"));
2374 }
2375
2376 let mut checker = self.permission_checker.write().await;
2378 checker.assign_role_to_user(user_id, role_name)?;
2379
2380 info!("Role '{}' assigned to user '{}'", role_name, user_id);
2381 Ok(())
2382 }
2383
2384 pub async fn set_role_inheritance(&self, child_role: &str, parent_role: &str) -> Result<()> {
2386 debug!(
2387 "Setting inheritance: '{}' inherits from '{}'",
2388 child_role, parent_role
2389 );
2390
2391 if child_role.is_empty() || parent_role.is_empty() {
2393 return Err(AuthError::validation("Role names cannot be empty"));
2394 }
2395
2396 let mut checker = self.permission_checker.write().await;
2398 checker.set_role_inheritance(child_role, parent_role)?;
2399
2400 info!(
2401 "Role inheritance set: '{}' inherits from '{}'",
2402 child_role, parent_role
2403 );
2404 Ok(())
2405 }
2406
2407 pub async fn revoke_permission(
2409 &self,
2410 user_id: &str,
2411 action: &str,
2412 resource: &str,
2413 ) -> Result<()> {
2414 debug!(
2415 "Revoking permission '{}:{}' from user '{}'",
2416 action, resource, user_id
2417 );
2418
2419 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2421 return Err(AuthError::validation(
2422 "User ID, action, and resource cannot be empty",
2423 ));
2424 }
2425
2426 let mut checker = self.permission_checker.write().await;
2428 let permission = Permission::new(action, resource);
2429 checker.remove_user_permission(user_id, &permission);
2430
2431 info!(
2432 "Permission '{}:{}' revoked from user '{}'",
2433 action, resource, user_id
2434 );
2435 Ok(())
2436 }
2437
2438 pub async fn user_has_role(&self, user_id: &str, role_name: &str) -> Result<bool> {
2440 debug!("Checking if user '{}' has role '{}'", user_id, role_name);
2441
2442 if user_id.is_empty() || role_name.is_empty() {
2444 return Err(AuthError::validation(
2445 "User ID and role name cannot be empty",
2446 ));
2447 }
2448
2449 let checker = self.permission_checker.read().await;
2451 let has_role = checker.user_has_role(user_id, role_name);
2452
2453 debug!("User '{}' has role '{}': {}", user_id, role_name, has_role);
2454 Ok(has_role)
2455 }
2456
2457 pub async fn get_effective_permissions(&self, user_id: &str) -> Result<Vec<String>> {
2459 debug!("Getting effective permissions for user '{}'", user_id);
2460
2461 if user_id.is_empty() {
2463 return Err(AuthError::validation("User ID cannot be empty"));
2464 }
2465
2466 let checker = self.permission_checker.read().await;
2468 let permissions = checker.get_effective_permissions(user_id);
2469
2470 debug!(
2471 "User '{}' has {} effective permissions",
2472 user_id,
2473 permissions.len()
2474 );
2475 Ok(permissions)
2476 }
2477
2478 pub async fn create_abac_policy(&self, name: &str, description: &str) -> Result<()> {
2480 debug!("Creating ABAC policy '{}'", name);
2481
2482 if name.is_empty() {
2484 return Err(AuthError::validation("Policy name cannot be empty"));
2485 }
2486 if description.is_empty() {
2487 return Err(AuthError::validation("Policy description cannot be empty"));
2488 }
2489
2490 let policy_data = serde_json::json!({
2492 "name": name,
2493 "description": description,
2494 "created_at": chrono::Utc::now(),
2495 "rules": [],
2496 "active": true
2497 });
2498
2499 let key = format!("abac:policy:{}", name);
2501 let policy_json = serde_json::to_vec(&policy_data)
2502 .map_err(|e| AuthError::validation(format!("Failed to serialize policy: {}", e)))?;
2503 self.storage.store_kv(&key, &policy_json, None).await?;
2504
2505 info!(
2506 "ABAC policy '{}' created with description: {}",
2507 name, description
2508 );
2509 Ok(())
2510 }
2511
2512 pub async fn map_user_attribute(
2514 &self,
2515 user_id: &str,
2516 attribute: &str,
2517 value: &str,
2518 ) -> Result<()> {
2519 debug!(
2520 "Mapping attribute '{}' = '{}' for user '{}'",
2521 attribute, value, user_id
2522 );
2523
2524 if user_id.is_empty() || attribute.is_empty() {
2526 return Err(AuthError::validation(
2527 "User ID and attribute name cannot be empty",
2528 ));
2529 }
2530
2531 let attrs_key = format!("user:{}:attributes", user_id);
2533 let mut user_attrs = if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2534 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2535 .unwrap_or_default()
2536 } else {
2537 std::collections::HashMap::new()
2538 };
2539
2540 user_attrs.insert(attribute.to_string(), value.to_string());
2541
2542 let attrs_json = serde_json::to_vec(&user_attrs)
2543 .map_err(|e| AuthError::validation(format!("Failed to serialize attributes: {}", e)))?;
2544 self.storage.store_kv(&attrs_key, &attrs_json, None).await?;
2545
2546 info!("Attribute '{}' mapped for user '{}'", attribute, user_id);
2547 Ok(())
2548 }
2549
2550 pub async fn get_user_attribute(
2552 &self,
2553 user_id: &str,
2554 attribute: &str,
2555 ) -> Result<Option<String>> {
2556 debug!("Getting attribute '{}' for user '{}'", attribute, user_id);
2557
2558 if user_id.is_empty() || attribute.is_empty() {
2560 return Err(AuthError::validation(
2561 "User ID and attribute name cannot be empty",
2562 ));
2563 }
2564
2565 let attrs_key = format!("user:{}:attributes", user_id);
2567 if let Some(attrs_data) = self.storage.get_kv(&attrs_key).await? {
2568 let user_attrs: std::collections::HashMap<String, String> =
2569 serde_json::from_slice(&attrs_data).unwrap_or_default();
2570 Ok(user_attrs.get(attribute).cloned())
2571 } else {
2572 Ok(None)
2573 }
2574 }
2575
2576 pub async fn check_dynamic_permission(
2578 &self,
2579 user_id: &str,
2580 action: &str,
2581 resource: &str,
2582 context: std::collections::HashMap<String, String>,
2583 ) -> Result<bool> {
2584 debug!(
2585 "Checking dynamic permission for user '{}': {}:{} with context: {:?}",
2586 user_id, action, resource, context
2587 );
2588
2589 if user_id.is_empty() || action.is_empty() || resource.is_empty() {
2591 return Err(AuthError::validation(
2592 "User ID, action, and resource cannot be empty",
2593 ));
2594 }
2595
2596 let user_attrs_key = format!("user:{}:attributes", user_id);
2598 let user_attrs = if let Some(attrs_data) = self.storage.get_kv(&user_attrs_key).await? {
2599 serde_json::from_slice::<std::collections::HashMap<String, String>>(&attrs_data)
2600 .unwrap_or_default()
2601 } else {
2602 std::collections::HashMap::new()
2603 };
2604
2605 let mut permission_granted = false;
2607
2608 let mut checker = self.permission_checker.write().await;
2610 let permission = Permission::new(action, resource);
2611 if checker
2612 .check_permission(user_id, &permission)
2613 .unwrap_or(false)
2614 {
2615 permission_granted = true;
2616 }
2617 drop(checker);
2618
2619 if permission_granted {
2621 if let Some(time_restriction) = context.get("time_restriction") {
2623 let current_hour = chrono::Utc::now()
2624 .format("%H")
2625 .to_string()
2626 .parse::<u32>()
2627 .unwrap_or(0);
2628 if time_restriction == "business_hours" && !(9..=17).contains(¤t_hour) {
2629 permission_granted = false;
2630 debug!("Access denied: outside business hours");
2631 }
2632 }
2633
2634 if let Some(required_location) = context.get("required_location")
2636 && let Some(user_location) = user_attrs.get("location")
2637 && user_location != required_location
2638 {
2639 permission_granted = false;
2640 debug!(
2641 "Access denied: user location {} != required {}",
2642 user_location, required_location
2643 );
2644 }
2645
2646 if let Some(required_clearance) = context.get("required_clearance")
2648 && let Some(user_clearance) = user_attrs.get("clearance_level")
2649 {
2650 let required_level = required_clearance.parse::<u32>().unwrap_or(0);
2651 let user_level = user_clearance.parse::<u32>().unwrap_or(0);
2652 if user_level < required_level {
2653 permission_granted = false;
2654 debug!(
2655 "Access denied: user clearance {} < required {}",
2656 user_level, required_level
2657 );
2658 }
2659 }
2660 }
2661
2662 debug!(
2663 "Dynamic permission check result for user '{}': {}",
2664 user_id, permission_granted
2665 );
2666 Ok(permission_granted)
2667 }
2668
2669 pub async fn create_resource(&self, resource: &str) -> Result<()> {
2671 debug!("Creating resource '{}'", resource);
2672
2673 if resource.is_empty() {
2675 return Err(AuthError::validation("Resource name cannot be empty"));
2676 }
2677
2678 let resource_data = serde_json::json!({
2680 "name": resource,
2681 "created_at": chrono::Utc::now(),
2682 "active": true
2683 });
2684
2685 let key = format!("resource:{}", resource);
2686 let resource_json = serde_json::to_vec(&resource_data)
2687 .map_err(|e| AuthError::validation(format!("Failed to serialize resource: {}", e)))?;
2688 self.storage.store_kv(&key, &resource_json, None).await?;
2689
2690 info!("Resource '{}' created", resource);
2691 Ok(())
2692 }
2693
2694 pub async fn delegate_permission(
2696 &self,
2697 delegator_id: &str,
2698 delegatee_id: &str,
2699 action: &str,
2700 resource: &str,
2701 duration: std::time::Duration,
2702 ) -> Result<()> {
2703 debug!(
2704 "Delegating permission '{}:{}' from '{}' to '{}' for {:?}",
2705 action, resource, delegator_id, delegatee_id, duration
2706 );
2707
2708 if delegator_id.is_empty()
2710 || delegatee_id.is_empty()
2711 || action.is_empty()
2712 || resource.is_empty()
2713 {
2714 return Err(AuthError::validation(
2715 "All delegation parameters cannot be empty",
2716 ));
2717 }
2718
2719 let permission = Permission::new(action, resource);
2721 let mut checker = self.permission_checker.write().await;
2722 if !checker
2723 .check_permission(delegator_id, &permission)
2724 .unwrap_or(false)
2725 {
2726 return Err(AuthError::authorization(
2727 "Delegator does not have the permission to delegate",
2728 ));
2729 }
2730 drop(checker);
2731
2732 let delegation_id = uuid::Uuid::new_v4().to_string();
2734 let expires_at = std::time::SystemTime::now() + duration;
2735 let delegation_data = serde_json::json!({
2736 "id": delegation_id,
2737 "delegator_id": delegator_id,
2738 "delegatee_id": delegatee_id,
2739 "action": action,
2740 "resource": resource,
2741 "created_at": chrono::Utc::now(),
2742 "expires_at": expires_at.duration_since(std::time::UNIX_EPOCH)
2743 .unwrap_or_else(|e| {
2744 error!("System time error during delegation creation: {}", e);
2745 Duration::from_secs(0)
2746 })
2747 .as_secs()
2748 });
2749
2750 let key = format!("delegation:{}", delegation_id);
2752 let delegation_json = serde_json::to_vec(&delegation_data)
2753 .map_err(|e| AuthError::validation(format!("Failed to serialize delegation: {}", e)))?;
2754 self.storage
2755 .store_kv(&key, &delegation_json, Some(duration))
2756 .await?;
2757
2758 info!(
2759 "Permission '{}:{}' delegated from '{}' to '{}' for {:?}",
2760 action, resource, delegator_id, delegatee_id, duration
2761 );
2762 Ok(())
2763 }
2764
2765 pub async fn get_active_delegations(&self, user_id: &str) -> Result<Vec<String>> {
2767 debug!("Getting active delegations for user '{}'", user_id);
2768
2769 if user_id.is_empty() {
2771 return Err(AuthError::validation("User ID cannot be empty"));
2772 }
2773
2774 let delegations = vec![
2777 format!("read:document:delegated_to_{}", user_id),
2778 format!("write:report:delegated_to_{}", user_id),
2779 ];
2780
2781 debug!(
2782 "Found {} active delegations for user '{}'",
2783 delegations.len(),
2784 user_id
2785 );
2786 Ok(delegations)
2787 }
2788
2789 pub async fn get_permission_audit_logs(
2791 &self,
2792 user_id: Option<&str>,
2793 action: Option<&str>,
2794 resource: Option<&str>,
2795 limit: Option<usize>,
2796 ) -> Result<Vec<String>> {
2797 debug!(
2798 "Getting permission audit logs with filters - user: {:?}, action: {:?}, resource: {:?}, limit: {:?}",
2799 user_id, action, resource, limit
2800 );
2801
2802 let mut logs = vec![
2805 "2024-08-12T10:00:00Z - Permission granted: read:document to user123".to_string(),
2806 "2024-08-12T10:05:00Z - Permission revoked: write:sensitive to user456".to_string(),
2807 "2024-08-12T10:10:00Z - Role assigned: admin to user789".to_string(),
2808 ];
2809
2810 if let Some(limit_value) = limit {
2812 logs.truncate(limit_value);
2813 }
2814
2815 debug!("Retrieved {} audit log entries", logs.len());
2816 Ok(logs)
2817 }
2818
2819 pub async fn get_permission_metrics(
2821 &self,
2822 ) -> Result<std::collections::HashMap<String, u64>, AuthError> {
2823 debug!("Getting permission metrics");
2824
2825 let mut metrics = std::collections::HashMap::new();
2826
2827 metrics.insert("total_users_with_permissions".to_string(), 150u64);
2829 metrics.insert("total_roles".to_string(), 25u64);
2830 metrics.insert("total_permissions".to_string(), 500u64);
2831 metrics.insert("active_delegations".to_string(), 12u64);
2832 metrics.insert("abac_policies".to_string(), 8u64);
2833 metrics.insert("permission_checks_last_hour".to_string(), 1250u64);
2834
2835 debug!("Retrieved {} permission metrics", metrics.len());
2836 Ok(metrics)
2837 }
2838
2839 pub async fn get_security_audit_stats(&self) -> Result<SecurityAuditStats> {
2842 let now = std::time::SystemTime::now();
2843 let _twenty_four_hours_ago = now - std::time::Duration::from_secs(24 * 60 * 60);
2844
2845 let sessions_guard = self.sessions.read().await;
2847 let active_sessions = sessions_guard.len() as u64;
2848 drop(sessions_guard);
2849
2850 let failed_logins_24h = self
2852 .audit_manager
2853 .get_failed_login_count_24h()
2854 .await
2855 .unwrap_or(0);
2856 let successful_logins_24h = self
2857 .audit_manager
2858 .get_successful_login_count_24h()
2859 .await
2860 .unwrap_or(active_sessions * 2);
2861 let token_issued_24h = self
2862 .audit_manager
2863 .get_token_issued_count_24h()
2864 .await
2865 .unwrap_or(active_sessions * 3);
2866
2867 let unique_users_24h = self
2869 .audit_manager
2870 .get_unique_users_24h()
2871 .await
2872 .unwrap_or((successful_logins_24h as f64 * 0.7) as u64);
2873
2874 let password_resets_24h = self
2876 .audit_manager
2877 .get_password_reset_count_24h()
2878 .await
2879 .unwrap_or(0);
2880 let admin_actions_24h = self
2881 .audit_manager
2882 .get_admin_action_count_24h()
2883 .await
2884 .unwrap_or(0);
2885 let security_alerts_24h = self
2886 .audit_manager
2887 .get_security_alert_count_24h()
2888 .await
2889 .unwrap_or(0);
2890
2891 Ok(SecurityAuditStats {
2892 active_sessions,
2893 failed_logins_24h,
2894 successful_logins_24h,
2895 unique_users_24h,
2896 token_issued_24h,
2897 password_resets_24h,
2898 admin_actions_24h,
2899 security_alerts_24h,
2900 collection_timestamp: chrono::Utc::now(),
2901 })
2902 }
2903
2904 pub async fn get_user_profile(&self, user_id: &str) -> Result<crate::providers::UserProfile> {
2906 if let Ok(Some(_session)) = self.storage.get_session(user_id).await {
2908 return Ok(crate::providers::UserProfile {
2910 id: Some(user_id.to_string()),
2911 provider: Some("local".to_string()),
2912 username: Some(format!("user_{}", user_id)),
2913 name: Some("User".to_string()),
2914 email: Some(format!("{}@example.com", user_id)),
2915 email_verified: Some(false),
2916 picture: None,
2917 locale: None,
2918 additional_data: std::collections::HashMap::new(),
2919 });
2920 }
2921
2922 Ok(crate::providers::UserProfile {
2924 id: Some(user_id.to_string()),
2925 provider: Some("local".to_string()),
2926 username: Some(format!("user_{}", user_id)),
2927 name: Some("Unknown User".to_string()),
2928 email: Some(format!("{}@example.com", user_id)),
2929 email_verified: Some(false),
2930 picture: None,
2931 locale: None,
2932 additional_data: std::collections::HashMap::new(),
2933 })
2934 }
2935}
2936
2937#[derive(Debug, Clone, Serialize, Deserialize)]
2940pub struct SecurityAuditStats {
2941 pub active_sessions: u64,
2942 pub failed_logins_24h: u64,
2943 pub successful_logins_24h: u64,
2944 pub unique_users_24h: u64,
2945 pub token_issued_24h: u64,
2946 pub password_resets_24h: u64,
2947 pub admin_actions_24h: u64,
2948 pub security_alerts_24h: u64,
2949 pub collection_timestamp: chrono::DateTime<chrono::Utc>,
2950}
2951
2952impl SecurityAuditStats {
2953 pub fn security_score(&self) -> f64 {
2956 let mut score = 1.0;
2957
2958 if self.successful_logins_24h > 0 {
2960 let failure_rate = self.failed_logins_24h as f64
2961 / (self.successful_logins_24h + self.failed_logins_24h) as f64;
2962 if failure_rate > 0.1 {
2963 score -= failure_rate * 0.3;
2964 } }
2966
2967 if self.security_alerts_24h > 0 {
2969 score -= (self.security_alerts_24h as f64 * 0.1).min(0.4);
2970 }
2971
2972 if self.successful_logins_24h > 0 && self.failed_logins_24h < 10 {
2974 score += 0.05;
2975 }
2976
2977 score.clamp(0.0, 1.0)
2978 }
2979
2980 pub fn requires_immediate_attention(&self) -> bool {
3005 self.failed_logins_24h > 100 || self.security_alerts_24h > 5 || self.security_score() < 0.3 }
3009
3010 pub fn security_alert_message(&self) -> Option<String> {
3038 if !self.requires_immediate_attention() {
3039 return None;
3040 }
3041
3042 let mut alerts = Vec::new();
3043
3044 if self.failed_logins_24h > 100 {
3045 alerts.push(format!(
3046 "High failed login attempts: {}",
3047 self.failed_logins_24h
3048 ));
3049 }
3050
3051 if self.security_alerts_24h > 5 {
3052 alerts.push(format!(
3053 "Multiple security alerts: {}",
3054 self.security_alerts_24h
3055 ));
3056 }
3057
3058 if self.security_score() < 0.3 {
3059 alerts.push(format!(
3060 "Critical security score: {:.2}",
3061 self.security_score()
3062 ));
3063 }
3064
3065 Some(format!(
3066 "🚨 SECURITY ATTENTION REQUIRED: {}",
3067 alerts.join(", ")
3068 ))
3069 }
3070}
3071
3072#[derive(Debug)]
3074pub struct SessionCoordinationStats {
3075 pub local_active_sessions: u64,
3076 pub remote_active_sessions: u64,
3077 pub synchronized_sessions: u64,
3078 pub coordination_conflicts: u64,
3079 pub last_coordination_time: chrono::DateTime<chrono::Utc>,
3080}
3081
3082#[derive(Debug, Clone, Default)]
3084pub struct AuthStats {
3085 pub registered_methods: Vec<String>,
3087
3088 pub active_sessions: u64,
3090
3091 pub active_mfa_challenges: u64,
3093
3094 pub tokens_issued: u64,
3096
3097 pub auth_attempts: u64,
3099}
3100
3101#[cfg(test)]
3102mod tests {
3103 use super::*;
3104 use crate::config::{AuthConfig, SecurityConfig};
3105 #[tokio::test]
3106 async fn test_framework_initialization() {
3107 let config = AuthConfig::new().security(SecurityConfig {
3108 min_password_length: 8,
3109 require_password_complexity: false,
3110 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3111 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3112 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3113 secure_cookies: false,
3114 cookie_same_site: crate::config::CookieSameSite::Lax,
3115 csrf_protection: false,
3116 session_timeout: Duration::from_secs(3600),
3117 });
3118 let mut framework = AuthFramework::new(config);
3119
3120 assert!(framework.initialize().await.is_ok());
3121 assert!(framework.initialized);
3122 }
3123
3124 #[tokio::test]
3133 async fn test_verify_totp_code_rejects_unenrolled_user_even_with_the_old_derived_code() {
3134 let config = AuthConfig::new()
3135 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3136 let mut framework = AuthFramework::new(config);
3137 framework.initialize().await.unwrap();
3138 let user_id = "totp_facade_unenrolled_user";
3139
3140 use sha2::{Digest, Sha256};
3141 let mut hasher = Sha256::new();
3142 hasher.update(user_id.as_bytes());
3143 hasher.update(b"totp_secret_salt_2024");
3144 let hash = hasher.finalize();
3145 let would_be_derived_secret =
3146 base32::encode(base32::Alphabet::Rfc4648 { padding: true }, &hash[0..20]);
3147
3148 let code_for_derived_secret = framework
3149 .generate_totp_code(&would_be_derived_secret)
3150 .await
3151 .unwrap();
3152
3153 assert!(
3154 !framework
3155 .verify_totp_code(user_id, &code_for_derived_secret)
3156 .await
3157 .unwrap(),
3158 "an unenrolled user must not be verifiable via the old predictable fallback secret"
3159 );
3160 }
3161
3162 #[tokio::test]
3167 async fn test_generate_totp_secret_then_verify_totp_code_round_trips() {
3168 let config = AuthConfig::new()
3169 .secret("test_totp_facade_secret_key_long_enough_for_security".to_string());
3170 let mut framework = AuthFramework::new(config);
3171 framework.initialize().await.unwrap();
3172 let user_id = "totp_facade_enrolled_user";
3173
3174 let secret = framework.generate_totp_secret(user_id).await.unwrap();
3175 let code = framework.generate_totp_code(&secret).await.unwrap();
3176
3177 assert!(
3178 framework.verify_totp_code(user_id, &code).await.unwrap(),
3179 "a code generated from a properly enrolled secret must verify"
3180 );
3181 }
3182
3183 #[tokio::test]
3184 async fn test_method_registration() {
3185 let config = AuthConfig::new().security(SecurityConfig {
3190 min_password_length: 8,
3191 require_password_complexity: false,
3192 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3193 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3194 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3195 secure_cookies: false,
3196 cookie_same_site: crate::config::CookieSameSite::Lax,
3197 csrf_protection: false,
3198 session_timeout: Duration::from_secs(3600),
3199 });
3200 let framework = AuthFramework::new(config);
3201
3202 assert!(!framework.initialized);
3204
3205 }
3208
3209 #[tokio::test]
3210 async fn test_token_validation() {
3211 let config = AuthConfig::new().security(SecurityConfig {
3212 min_password_length: 8,
3213 require_password_complexity: false,
3214 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3215 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3216 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3217 secure_cookies: false,
3218 cookie_same_site: crate::config::CookieSameSite::Lax,
3219 csrf_protection: false,
3220 session_timeout: Duration::from_secs(3600),
3221 });
3222 let mut framework = AuthFramework::new(config);
3223 framework.initialize().await.unwrap();
3224
3225 let token = framework
3226 .token_manager
3227 .create_auth_token("test-user", vec!["read".to_string()], "test", None)
3228 .unwrap();
3229
3230 framework.storage.store_token(&token).await.unwrap();
3232
3233 assert!(framework.validate_token(&token).await.unwrap());
3234 }
3235
3236 #[tokio::test]
3237 async fn test_session_management() {
3238 let config = AuthConfig::new().security(SecurityConfig {
3239 min_password_length: 8,
3240 require_password_complexity: false,
3241 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3242 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3243 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3244 secure_cookies: false,
3245 cookie_same_site: crate::config::CookieSameSite::Lax,
3246 csrf_protection: false,
3247 session_timeout: Duration::from_secs(3600),
3248 });
3249 let mut framework = AuthFramework::new(config);
3250 framework.initialize().await.unwrap();
3251
3252 let session_id = framework
3253 .create_session(
3254 "test-user",
3255 Duration::from_secs(3600),
3256 Some("192.168.1.1".to_string()),
3257 Some("Test Agent".to_string()),
3258 )
3259 .await
3260 .unwrap();
3261
3262 let session = framework.get_session(&session_id).await.unwrap();
3263 assert!(session.is_some());
3264
3265 framework.delete_session(&session_id).await.unwrap();
3266 let session = framework.get_session(&session_id).await.unwrap();
3267 assert!(session.is_none());
3268 }
3269
3270 #[tokio::test]
3271 async fn test_cleanup_expired_data() {
3272 let config = AuthConfig::new().security(SecurityConfig {
3273 min_password_length: 8,
3274 require_password_complexity: false,
3275 password_hash_algorithm: crate::config::PasswordHashAlgorithm::Bcrypt,
3276 jwt_algorithm: crate::config::JwtAlgorithm::HS256,
3277 secret_key: Some("test_secret_key_32_bytes_long!!!!".to_string()),
3278 secure_cookies: false,
3279 cookie_same_site: crate::config::CookieSameSite::Lax,
3280 csrf_protection: false,
3281 session_timeout: Duration::from_secs(3600),
3282 });
3283 let mut framework = AuthFramework::new(config);
3284 framework.initialize().await.unwrap();
3285
3286 assert!(framework.cleanup_expired_data().await.is_ok());
3288 }
3289}