Skip to main content

oxirs_cluster/
security.rs

1//! Security and Authentication Module
2//!
3//! Provides comprehensive security features including authentication, authorization,
4//! encryption, and audit logging for the distributed cluster.
5
6use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::collections::{HashMap, HashSet};
10use std::sync::Arc;
11use std::time::{Duration, SystemTime};
12use tokio::sync::RwLock;
13use tracing::{info, warn};
14
15use crate::raft::OxirsNodeId;
16
17/// Authentication configuration
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct AuthConfig {
20    pub enable_tls: bool,
21    pub require_client_auth: bool,
22    pub jwt_secret: String,
23    pub token_expiry_hours: u64,
24    pub max_failed_attempts: u32,
25    pub lockout_duration_minutes: u64,
26    pub enable_audit_logging: bool,
27}
28
29impl Default for AuthConfig {
30    fn default() -> Self {
31        Self {
32            enable_tls: true,
33            require_client_auth: true,
34            jwt_secret: "default-secret-change-in-production".to_string(),
35            token_expiry_hours: 24,
36            max_failed_attempts: 5,
37            lockout_duration_minutes: 30,
38            enable_audit_logging: true,
39        }
40    }
41}
42
43/// User authentication information
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct User {
46    pub username: String,
47    pub password_hash: String,
48    pub roles: HashSet<String>,
49    pub permissions: HashSet<Permission>,
50    pub created_at: SystemTime,
51    pub last_login: Option<SystemTime>,
52    pub is_active: bool,
53}
54
55impl User {
56    /// Check if the user has a specific permission
57    pub fn has_permission(&self, permission: &Permission) -> bool {
58        self.permissions.contains(permission)
59    }
60
61    /// Create a new user
62    pub fn new(username: String, password_hash: String) -> Self {
63        Self {
64            username,
65            password_hash,
66            roles: HashSet::new(),
67            permissions: HashSet::new(),
68            created_at: SystemTime::now(),
69            last_login: None,
70            is_active: true,
71        }
72    }
73}
74
75/// System permissions
76#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
77pub enum Permission {
78    // Cluster management
79    ClusterRead,
80    ClusterWrite,
81    ClusterAdmin,
82
83    // Node management
84    NodeAdd,
85    NodeRemove,
86    NodeStatus,
87
88    // Query permissions
89    QueryRead,
90    QueryWrite,
91    QueryAdmin,
92
93    // Data permissions
94    DataRead,
95    DataWrite,
96    DataDelete,
97    DataAdmin,
98
99    // System permissions
100    SystemMonitor,
101    SystemConfig,
102    SystemAdmin,
103
104    // Audit permissions
105    AuditRead,
106    AuditWrite,
107}
108
109/// Authentication token
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct AuthToken {
112    pub token_id: String,
113    pub username: String,
114    pub roles: HashSet<String>,
115    pub permissions: HashSet<Permission>,
116    pub issued_at: SystemTime,
117    pub expires_at: SystemTime,
118    pub node_id: Option<OxirsNodeId>,
119}
120
121impl AuthToken {
122    pub fn is_expired(&self) -> bool {
123        SystemTime::now() > self.expires_at
124    }
125
126    pub fn has_permission(&self, permission: &Permission) -> bool {
127        self.permissions.contains(permission)
128    }
129
130    pub fn has_role(&self, role: &str) -> bool {
131        self.roles.contains(role)
132    }
133}
134
135/// Audit log entry
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct AuditEntry {
138    pub timestamp: SystemTime,
139    pub event_type: AuditEventType,
140    pub username: Option<String>,
141    pub node_id: OxirsNodeId,
142    pub source_ip: Option<String>,
143    pub operation: String,
144    pub resource: Option<String>,
145    pub success: bool,
146    pub error_message: Option<String>,
147    pub additional_data: HashMap<String, String>,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub enum AuditEventType {
152    Authentication,
153    Authorization,
154    DataAccess,
155    DataModification,
156    SystemOperation,
157    SecurityEvent,
158    ClusterOperation,
159}
160
161/// Failed login attempt tracking
162#[derive(Debug, Clone)]
163struct FailedAttempt {
164    #[allow(dead_code)]
165    username: String,
166    attempts: u32,
167    last_attempt: SystemTime,
168    lockout_until: Option<SystemTime>,
169}
170
171/// Security manager for the cluster
172pub struct SecurityManager {
173    config: AuthConfig,
174    users: Arc<RwLock<HashMap<String, User>>>,
175    active_tokens: Arc<RwLock<HashMap<String, AuthToken>>>,
176    failed_attempts: Arc<RwLock<HashMap<String, FailedAttempt>>>,
177    audit_log: Arc<RwLock<Vec<AuditEntry>>>,
178    node_id: OxirsNodeId,
179}
180
181impl SecurityManager {
182    /// Create a new security manager
183    pub fn new(config: AuthConfig, node_id: OxirsNodeId) -> Self {
184        Self {
185            config,
186            users: Arc::new(RwLock::new(HashMap::new())),
187            active_tokens: Arc::new(RwLock::new(HashMap::new())),
188            failed_attempts: Arc::new(RwLock::new(HashMap::new())),
189            audit_log: Arc::new(RwLock::new(Vec::new())),
190            node_id,
191        }
192    }
193
194    /// Initialize with default admin user
195    pub async fn initialize(&self) -> Result<()> {
196        let admin_user = User {
197            username: "admin".to_string(),
198            password_hash: self.hash_password("admin123")?,
199            roles: vec!["admin".to_string()].into_iter().collect(),
200            permissions: vec![
201                Permission::SystemAdmin,
202                Permission::ClusterAdmin,
203                Permission::DataAdmin,
204                Permission::DataRead,
205                Permission::DataWrite,
206                Permission::QueryAdmin,
207                Permission::AuditRead,
208                Permission::AuditWrite,
209            ]
210            .into_iter()
211            .collect(),
212            created_at: SystemTime::now(),
213            last_login: None,
214            is_active: true,
215        };
216
217        let mut users = self.users.write().await;
218        users.insert("admin".to_string(), admin_user);
219
220        info!("Security manager initialized with default admin user");
221        self.audit_system_event("Security manager initialized")
222            .await;
223
224        Ok(())
225    }
226
227    /// Create a new user
228    pub async fn create_user(
229        &self,
230        username: String,
231        password: String,
232        roles: HashSet<String>,
233        permissions: HashSet<Permission>,
234    ) -> Result<()> {
235        let mut users = self.users.write().await;
236
237        if users.contains_key(&username) {
238            return Err(anyhow::anyhow!("User already exists: {}", username));
239        }
240
241        let user = User {
242            username: username.clone(),
243            password_hash: self.hash_password(&password)?,
244            roles,
245            permissions,
246            created_at: SystemTime::now(),
247            last_login: None,
248            is_active: true,
249        };
250
251        users.insert(username.clone(), user);
252        info!("Created user: {}", username);
253        self.audit_system_event(&format!("User created: {username}"))
254            .await;
255
256        Ok(())
257    }
258
259    /// Authenticate user and return token
260    pub async fn authenticate(
261        &self,
262        username: &str,
263        password: &str,
264        source_ip: Option<String>,
265    ) -> Result<AuthToken> {
266        // Check if user is locked out
267        if self.is_user_locked_out(username).await {
268            self.audit_authentication_event(
269                Some(username.to_string()),
270                source_ip.clone(),
271                "Login attempt - user locked out",
272                false,
273                Some("User account is locked due to too many failed attempts".to_string()),
274            )
275            .await;
276            return Err(anyhow::anyhow!(
277                "Account is locked due to too many failed attempts"
278            ));
279        }
280
281        let users = self.users.read().await;
282        let user = users
283            .get(username)
284            .ok_or_else(|| anyhow::anyhow!("User not found"))?;
285
286        if !user.is_active {
287            self.audit_authentication_event(
288                Some(username.to_string()),
289                source_ip,
290                "Login attempt - inactive user",
291                false,
292                Some("User account is inactive".to_string()),
293            )
294            .await;
295            return Err(anyhow::anyhow!("User account is inactive"));
296        }
297
298        if !self.verify_password(password, &user.password_hash)? {
299            self.record_failed_attempt(username).await;
300            self.audit_authentication_event(
301                Some(username.to_string()),
302                source_ip,
303                "Login attempt - invalid password",
304                false,
305                Some("Invalid password".to_string()),
306            )
307            .await;
308            return Err(anyhow::anyhow!("Invalid credentials"));
309        }
310
311        // Clear failed attempts on successful login
312        self.clear_failed_attempts(username).await;
313
314        // Create token
315        let token = self.create_token(user).await?;
316
317        // Update last login
318        drop(users);
319        let mut users = self.users.write().await;
320        if let Some(user) = users.get_mut(username) {
321            user.last_login = Some(SystemTime::now());
322        }
323
324        self.audit_authentication_event(
325            Some(username.to_string()),
326            source_ip,
327            "Successful login",
328            true,
329            None,
330        )
331        .await;
332
333        info!("User {} authenticated successfully", username);
334        Ok(token)
335    }
336
337    /// Validate an authentication token
338    pub async fn validate_token(&self, token_id: &str) -> Result<AuthToken> {
339        let tokens = self.active_tokens.read().await;
340        let token = tokens
341            .get(token_id)
342            .ok_or_else(|| anyhow::anyhow!("Invalid token"))?;
343
344        if token.is_expired() {
345            drop(tokens);
346            self.revoke_token(token_id).await?;
347            return Err(anyhow::anyhow!("Token expired"));
348        }
349
350        Ok(token.clone())
351    }
352
353    /// Check if user has permission
354    pub async fn check_permission(&self, token_id: &str, permission: Permission) -> Result<bool> {
355        let token = self.validate_token(token_id).await?;
356        Ok(token.has_permission(&permission))
357    }
358
359    /// Revoke an authentication token
360    pub async fn revoke_token(&self, token_id: &str) -> Result<()> {
361        let mut tokens = self.active_tokens.write().await;
362        if tokens.remove(token_id).is_some() {
363            info!("Token revoked: {}", token_id);
364            self.audit_authentication_event(None, None, "Token revoked", true, None)
365                .await;
366        }
367        Ok(())
368    }
369
370    /// Get user information
371    pub async fn get_user(&self, username: &str) -> Option<User> {
372        let users = self.users.read().await;
373        users.get(username).cloned()
374    }
375
376    /// Update user permissions
377    pub async fn update_user_permissions(
378        &self,
379        username: &str,
380        permissions: HashSet<Permission>,
381    ) -> Result<()> {
382        let mut users = self.users.write().await;
383        let user = users
384            .get_mut(username)
385            .ok_or_else(|| anyhow::anyhow!("User not found"))?;
386
387        user.permissions = permissions;
388        info!("Updated permissions for user: {}", username);
389        self.audit_system_event(&format!("Updated permissions for user: {username}"))
390            .await;
391
392        Ok(())
393    }
394
395    /// Deactivate user
396    pub async fn deactivate_user(&self, username: &str) -> Result<()> {
397        let mut users = self.users.write().await;
398        let user = users
399            .get_mut(username)
400            .ok_or_else(|| anyhow::anyhow!("User not found"))?;
401
402        user.is_active = false;
403        info!("Deactivated user: {}", username);
404        self.audit_system_event(&format!("User deactivated: {username}"))
405            .await;
406
407        Ok(())
408    }
409
410    /// Get audit log entries
411    pub async fn get_audit_log(&self, limit: Option<usize>) -> Vec<AuditEntry> {
412        let audit_log = self.audit_log.read().await;
413        if let Some(limit) = limit {
414            audit_log.iter().rev().take(limit).cloned().collect()
415        } else {
416            audit_log.clone()
417        }
418    }
419
420    /// Clean up expired tokens
421    pub async fn cleanup_expired_tokens(&self) {
422        let mut tokens = self.active_tokens.write().await;
423        let before_count = tokens.len();
424
425        tokens.retain(|_, token| !token.is_expired());
426
427        let after_count = tokens.len();
428        if before_count != after_count {
429            info!("Cleaned up {} expired tokens", before_count - after_count);
430        }
431    }
432
433    /// Hash password using SHA-256 with salt
434    fn hash_password(&self, password: &str) -> Result<String> {
435        let salt = "oxirs_cluster_salt"; // In production, use random salt per user
436        let mut hasher = Sha256::new();
437        hasher.update(password.as_bytes());
438        hasher.update(salt.as_bytes());
439        let result = hasher.finalize();
440        Ok(hex::encode(result))
441    }
442
443    /// Verify password hash
444    fn verify_password(&self, password: &str, hash: &str) -> Result<bool> {
445        let computed_hash = self.hash_password(password)?;
446        Ok(computed_hash == hash)
447    }
448
449    /// Create authentication token
450    async fn create_token(&self, user: &User) -> Result<AuthToken> {
451        let token_id = uuid::Uuid::new_v4().to_string();
452        let now = SystemTime::now();
453        let expires_at = now + Duration::from_secs(self.config.token_expiry_hours * 3600);
454
455        let token = AuthToken {
456            token_id: token_id.clone(),
457            username: user.username.clone(),
458            roles: user.roles.clone(),
459            permissions: user.permissions.clone(),
460            issued_at: now,
461            expires_at,
462            node_id: Some(self.node_id),
463        };
464
465        let mut tokens = self.active_tokens.write().await;
466        tokens.insert(token_id, token.clone());
467
468        Ok(token)
469    }
470
471    /// Check if user is locked out
472    async fn is_user_locked_out(&self, username: &str) -> bool {
473        let failed_attempts = self.failed_attempts.read().await;
474        if let Some(attempt) = failed_attempts.get(username) {
475            if let Some(lockout_until) = attempt.lockout_until {
476                return SystemTime::now() < lockout_until;
477            }
478        }
479        false
480    }
481
482    /// Record failed login attempt
483    async fn record_failed_attempt(&self, username: &str) {
484        let mut failed_attempts = self.failed_attempts.write().await;
485        let now = SystemTime::now();
486
487        let attempt = failed_attempts
488            .entry(username.to_string())
489            .or_insert(FailedAttempt {
490                username: username.to_string(),
491                attempts: 0,
492                last_attempt: now,
493                lockout_until: None,
494            });
495
496        attempt.attempts += 1;
497        attempt.last_attempt = now;
498
499        if attempt.attempts >= self.config.max_failed_attempts {
500            let lockout_duration = Duration::from_secs(self.config.lockout_duration_minutes * 60);
501            attempt.lockout_until = Some(now + lockout_duration);
502            warn!(
503                "User {} locked out due to {} failed attempts",
504                username, attempt.attempts
505            );
506        }
507    }
508
509    /// Clear failed attempts for user
510    async fn clear_failed_attempts(&self, username: &str) {
511        let mut failed_attempts = self.failed_attempts.write().await;
512        failed_attempts.remove(username);
513    }
514
515    /// Audit authentication event
516    async fn audit_authentication_event(
517        &self,
518        username: Option<String>,
519        source_ip: Option<String>,
520        operation: &str,
521        success: bool,
522        error_message: Option<String>,
523    ) {
524        if !self.config.enable_audit_logging {
525            return;
526        }
527
528        let entry = AuditEntry {
529            timestamp: SystemTime::now(),
530            event_type: AuditEventType::Authentication,
531            username,
532            node_id: self.node_id,
533            source_ip,
534            operation: operation.to_string(),
535            resource: None,
536            success,
537            error_message,
538            additional_data: HashMap::new(),
539        };
540
541        let mut audit_log = self.audit_log.write().await;
542        audit_log.push(entry);
543
544        // Limit audit log size
545        if audit_log.len() > 10000 {
546            audit_log.drain(0..1000);
547        }
548    }
549
550    /// Audit system event
551    async fn audit_system_event(&self, operation: &str) {
552        if !self.config.enable_audit_logging {
553            return;
554        }
555
556        let entry = AuditEntry {
557            timestamp: SystemTime::now(),
558            event_type: AuditEventType::SystemOperation,
559            username: None,
560            node_id: self.node_id,
561            source_ip: None,
562            operation: operation.to_string(),
563            resource: None,
564            success: true,
565            error_message: None,
566            additional_data: HashMap::new(),
567        };
568
569        let mut audit_log = self.audit_log.write().await;
570        audit_log.push(entry);
571
572        // Limit audit log size
573        if audit_log.len() > 10000 {
574            audit_log.drain(0..1000);
575        }
576    }
577
578    /// Audit data access event
579    pub async fn audit_data_access(
580        &self,
581        username: Option<String>,
582        operation: &str,
583        resource: Option<String>,
584        success: bool,
585        error_message: Option<String>,
586    ) {
587        if !self.config.enable_audit_logging {
588            return;
589        }
590
591        let entry = AuditEntry {
592            timestamp: SystemTime::now(),
593            event_type: AuditEventType::DataAccess,
594            username,
595            node_id: self.node_id,
596            source_ip: None,
597            operation: operation.to_string(),
598            resource,
599            success,
600            error_message,
601            additional_data: HashMap::new(),
602        };
603
604        let mut audit_log = self.audit_log.write().await;
605        audit_log.push(entry);
606
607        // Limit audit log size
608        if audit_log.len() > 10000 {
609            audit_log.drain(0..1000);
610        }
611    }
612
613    /// Start background cleanup tasks
614    pub async fn start_background_tasks(&self) {
615        let security_manager = SecurityManager {
616            config: self.config.clone(),
617            users: Arc::clone(&self.users),
618            active_tokens: Arc::clone(&self.active_tokens),
619            failed_attempts: Arc::clone(&self.failed_attempts),
620            audit_log: Arc::clone(&self.audit_log),
621            node_id: self.node_id,
622        };
623
624        tokio::spawn(async move {
625            let mut interval = tokio::time::interval(Duration::from_secs(300)); // 5 minutes
626            loop {
627                interval.tick().await;
628                security_manager.cleanup_expired_tokens().await;
629            }
630        });
631    }
632}
633
634/// Role-based permission management
635pub struct RoleManager {
636    roles: HashMap<String, HashSet<Permission>>,
637}
638
639impl Default for RoleManager {
640    fn default() -> Self {
641        Self::new()
642    }
643}
644
645impl RoleManager {
646    pub fn new() -> Self {
647        let mut roles = HashMap::new();
648
649        // Default roles
650        roles.insert(
651            "admin".to_string(),
652            vec![
653                Permission::SystemAdmin,
654                Permission::ClusterAdmin,
655                Permission::DataAdmin,
656                Permission::QueryAdmin,
657                Permission::AuditRead,
658                Permission::AuditWrite,
659            ]
660            .into_iter()
661            .collect(),
662        );
663
664        roles.insert(
665            "operator".to_string(),
666            vec![
667                Permission::ClusterRead,
668                Permission::ClusterWrite,
669                Permission::NodeAdd,
670                Permission::NodeRemove,
671                Permission::NodeStatus,
672                Permission::SystemMonitor,
673            ]
674            .into_iter()
675            .collect(),
676        );
677
678        roles.insert(
679            "developer".to_string(),
680            vec![
681                Permission::QueryRead,
682                Permission::QueryWrite,
683                Permission::DataRead,
684                Permission::DataWrite,
685                Permission::ClusterRead,
686            ]
687            .into_iter()
688            .collect(),
689        );
690
691        roles.insert(
692            "readonly".to_string(),
693            vec![
694                Permission::QueryRead,
695                Permission::DataRead,
696                Permission::ClusterRead,
697                Permission::NodeStatus,
698            ]
699            .into_iter()
700            .collect(),
701        );
702
703        Self { roles }
704    }
705
706    pub fn get_role_permissions(&self, role: &str) -> Option<&HashSet<Permission>> {
707        self.roles.get(role)
708    }
709
710    pub fn create_role(&mut self, role: String, permissions: HashSet<Permission>) {
711        self.roles.insert(role, permissions);
712    }
713
714    pub fn get_all_roles(&self) -> Vec<String> {
715        self.roles.keys().cloned().collect()
716    }
717}
718
719#[cfg(test)]
720mod tests {
721    use super::*;
722
723    #[tokio::test]
724    async fn test_security_manager_creation() {
725        let config = AuthConfig::default();
726        let security_manager = SecurityManager::new(config, 1);
727        security_manager.initialize().await.unwrap();
728
729        let admin_user = security_manager.get_user("admin").await;
730        assert!(admin_user.is_some());
731        assert!(admin_user.unwrap().has_permission(&Permission::SystemAdmin));
732    }
733
734    #[tokio::test]
735    async fn test_user_authentication() {
736        let config = AuthConfig::default();
737        let security_manager = SecurityManager::new(config, 1);
738        security_manager.initialize().await.unwrap();
739
740        // Test successful authentication
741        let token = security_manager
742            .authenticate("admin", "admin123", None)
743            .await
744            .unwrap();
745        assert!(!token.is_expired());
746        assert!(token.has_permission(&Permission::SystemAdmin));
747
748        // Test failed authentication
749        let result = security_manager
750            .authenticate("admin", "wrong_password", None)
751            .await;
752        assert!(result.is_err());
753    }
754
755    #[tokio::test]
756    async fn test_token_validation() {
757        let config = AuthConfig::default();
758        let security_manager = SecurityManager::new(config, 1);
759        security_manager.initialize().await.unwrap();
760
761        let token = security_manager
762            .authenticate("admin", "admin123", None)
763            .await
764            .unwrap();
765        let token_id = token.token_id.clone();
766
767        // Test valid token
768        let validated = security_manager.validate_token(&token_id).await.unwrap();
769        assert_eq!(validated.username, "admin");
770
771        // Test token revocation
772        security_manager.revoke_token(&token_id).await.unwrap();
773        let result = security_manager.validate_token(&token_id).await;
774        assert!(result.is_err());
775    }
776
777    #[tokio::test]
778    async fn test_permission_checking() {
779        let config = AuthConfig::default();
780        let security_manager = SecurityManager::new(config, 1);
781        security_manager.initialize().await.unwrap();
782
783        let token = security_manager
784            .authenticate("admin", "admin123", None)
785            .await
786            .unwrap();
787        let token_id = token.token_id.clone();
788
789        // Test permission check
790        let has_admin = security_manager
791            .check_permission(&token_id, Permission::SystemAdmin)
792            .await
793            .unwrap();
794        assert!(has_admin);
795
796        let has_invalid = security_manager
797            .check_permission(&token_id, Permission::DataRead)
798            .await
799            .unwrap();
800        assert!(has_invalid); // Admin should have all permissions
801    }
802
803    #[tokio::test]
804    async fn test_failed_attempt_lockout() {
805        let config = AuthConfig {
806            max_failed_attempts: 2,
807            lockout_duration_minutes: 1,
808            ..Default::default()
809        };
810
811        let security_manager = SecurityManager::new(config, 1);
812        security_manager.initialize().await.unwrap();
813
814        // First failed attempt
815        let _ = security_manager.authenticate("admin", "wrong", None).await;
816
817        // Second failed attempt
818        let _ = security_manager.authenticate("admin", "wrong", None).await;
819
820        // Should be locked out now
821        let result = security_manager
822            .authenticate("admin", "admin123", None)
823            .await;
824        assert!(result.is_err());
825        assert!(result.unwrap_err().to_string().contains("locked"));
826    }
827
828    #[test]
829    fn test_role_manager() {
830        let role_manager = RoleManager::new();
831
832        let admin_permissions = role_manager.get_role_permissions("admin").unwrap();
833        assert!(admin_permissions.contains(&Permission::SystemAdmin));
834
835        let readonly_permissions = role_manager.get_role_permissions("readonly").unwrap();
836        assert!(readonly_permissions.contains(&Permission::DataRead));
837        assert!(!readonly_permissions.contains(&Permission::DataWrite));
838    }
839}