rustchain-community 1.0.0

Open-source AI agent framework with core functionality and plugin system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::collections::HashMap;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};
use uuid::Uuid;
use tokio::sync::RwLock;

pub mod auth;
pub mod compliance;
pub mod encryption;
pub mod access_control;
pub mod audit;
pub mod threat_detection;

pub use auth::*;
pub use compliance::{ComplianceFramework, ComplianceRequirement, ComplianceSeverity, ImplementationStatus, 
                    ComplianceControl, ControlType, TestResult, ComplianceReport, ComplianceSummary, 
                    RequirementAssessment, ComplianceViolation, ComplianceRecommendation, Priority, 
                    DataRetentionPolicy, DeletionMethod, RetentionException, ComplianceService, 
                    MultiFrameworkComplianceService, RetentionReport, DataProcessingRecord};
pub use encryption::*;
pub use access_control::*;
pub use audit::*;
pub use threat_detection::*;

/// Core security context for all security operations
#[derive(Clone, Debug)]
pub struct SecurityContext {
    pub session_id: Uuid,
    pub user_id: Option<String>,
    pub tenant_id: Option<String>,
    pub permissions: Vec<String>,
    pub security_level: SecurityLevel,
    pub created_at: DateTime<Utc>,
    pub expires_at: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SecurityLevel {
    Public,
    Internal,
    Confidential,
    Restricted,
    TopSecret,
}

/// Security event types for auditing
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum SecurityEvent {
    Authentication {
        user_id: String,
        method: String,
        success: bool,
        ip_address: Option<String>,
    },
    Authorization {
        user_id: String,
        resource: String,
        action: String,
        granted: bool,
    },
    DataAccess {
        user_id: String,
        resource: String,
        operation: String,
        classification: SecurityLevel,
    },
    ThreatDetected {
        threat_type: String,
        severity: ThreatSeverity,
        source: String,
        details: HashMap<String, String>,
    },
    PolicyViolation {
        user_id: String,
        policy: String,
        violation_type: String,
        severity: ViolationSeverity,
    },
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ThreatSeverity {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum ViolationSeverity {
    Minor,
    Major,
    Critical,
}

/// Security configuration
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SecurityConfig {
    pub jwt_secret: Option<String>,
    pub session_timeout_minutes: u32,
    pub max_login_attempts: u32,
    pub encryption_algorithm: String,
    pub compliance_frameworks: Vec<String>,
    pub threat_detection_enabled: bool,
    pub audit_retention_days: u32,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            jwt_secret: None,
            session_timeout_minutes: 60,
            max_login_attempts: 3,
            encryption_algorithm: "AES-256-GCM".to_string(),
            compliance_frameworks: vec!["GDPR".to_string(), "HIPAA".to_string()],
            threat_detection_enabled: true,
            audit_retention_days: 2555, // 7 years
        }
    }
}

/// Session tracking for active security contexts
#[derive(Clone, Debug)]
pub struct SessionTracker {
    active_sessions: Arc<RwLock<HashMap<Uuid, SecurityContext>>>,
}

impl SessionTracker {
    pub fn new() -> Self {
        Self {
            active_sessions: Arc::new(RwLock::new(HashMap::new())),
        }
    }
    
    /// Add a new session to tracking
    pub async fn add_session(&self, context: SecurityContext) {
        let session_id = context.session_id;
        self.active_sessions.write().await.insert(session_id, context);
    }
    
    /// Remove a session from tracking
    pub async fn remove_session(&self, session_id: &Uuid) -> bool {
        self.active_sessions.write().await.remove(session_id).is_some()
    }
    
    /// Get session if it exists and hasn't expired
    pub async fn get_session(&self, session_id: &Uuid) -> Option<SecurityContext> {
        let sessions = self.active_sessions.read().await;
        if let Some(context) = sessions.get(session_id) {
            // Check if session has expired
            if let Some(expires_at) = context.expires_at {
                if Utc::now() > expires_at {
                    return None; // Session expired
                }
            }
            Some(context.clone())
        } else {
            None
        }
    }
    
    /// Count active sessions (non-expired)
    pub async fn count_active_sessions(&self) -> u64 {
        let now = Utc::now();
        let sessions = self.active_sessions.read().await;
        sessions
            .values()
            .filter(|context| {
                if let Some(expires_at) = context.expires_at {
                    now <= expires_at
                } else {
                    true // No expiration means it's active
                }
            })
            .count() as u64
    }
    
    /// Clean up expired sessions
    pub async fn cleanup_expired_sessions(&self) -> u64 {
        let now = Utc::now();
        let mut sessions = self.active_sessions.write().await;
        let initial_count = sessions.len();
        
        sessions.retain(|_, context| {
            if let Some(expires_at) = context.expires_at {
                now <= expires_at
            } else {
                true // No expiration means keep it
            }
        });
        
        (initial_count - sessions.len()) as u64
    }
    
    /// Get all active session IDs
    pub async fn get_active_session_ids(&self) -> Vec<Uuid> {
        let now = Utc::now();
        let sessions = self.active_sessions.read().await;
        sessions
            .iter()
            .filter(|(_, context)| {
                if let Some(expires_at) = context.expires_at {
                    now <= expires_at
                } else {
                    true
                }
            })
            .map(|(id, _)| *id)
            .collect()
    }
}

/// Main security manager
#[derive(Clone)]
pub struct SecurityManager {
    config: Arc<SecurityConfig>,
    auth_service: Arc<dyn AuthenticationService>,
    authz_service: Arc<dyn AuthorizationService>,
    encryption_service: Arc<dyn EncryptionService>,
    compliance_service: Arc<dyn ComplianceService>,
    audit_service: Arc<dyn AuditService>,
    threat_detector: Arc<dyn ThreatDetectionService>,
    session_tracker: SessionTracker,
}

impl SecurityManager {
    pub fn new(config: SecurityConfig) -> crate::core::error::Result<Self> {
        let config = Arc::new(config);
        
        let auth_service: Arc<dyn AuthenticationService> = Arc::new(JwtAuthenticationService::new(config.clone())?);
        let authz_service: Arc<dyn AuthorizationService> = Arc::new(RbacAuthorizationService::new());
        let encryption_service: Arc<dyn EncryptionService> = Arc::new(AesEncryptionService::new()?);
        let compliance_service: Arc<dyn ComplianceService> = Arc::new(MultiFrameworkComplianceService::new(config.clone()));
        let audit_service: Arc<dyn AuditService> = Arc::new(DatabaseAuditService::new()?);
        let threat_detector: Arc<dyn ThreatDetectionService> = Arc::new(RuleBasedThreatDetector::new());
        
        Ok(Self {
            config,
            auth_service,
            authz_service,
            encryption_service,
            compliance_service,
            audit_service,
            threat_detector,
            session_tracker: SessionTracker::new(),
        })
    }
    
    /// Authenticate a user and create security context
    pub async fn authenticate(&self, credentials: &Credentials) -> crate::core::error::Result<SecurityContext> {
        // Log authentication attempt
        self.audit_service.log_event(SecurityEvent::Authentication {
            user_id: credentials.user_id().to_string(),
            method: credentials.auth_method().to_string(),
            success: false, // Will be updated if successful
            ip_address: credentials.ip_address(),
        }).await?;
        
        // Check for threats
        if let Some(threat) = self.threat_detector.detect_authentication_threat(credentials).await? {
            self.audit_service.log_event(SecurityEvent::ThreatDetected {
                threat_type: "Authentication".to_string(),
                severity: threat.severity,
                source: credentials.user_id().to_string(),
                details: threat.details,
            }).await?;
            
            return Err(crate::core::error::RustChainError::Security("Authentication threat detected".to_string()));
        }
        
        // Perform authentication
        let auth_result = self.auth_service.authenticate(credentials).await?;
        
        // Create security context
        let context = SecurityContext {
            session_id: Uuid::new_v4(),
            user_id: Some(auth_result.user_id.clone()),
            tenant_id: auth_result.tenant_id,
            permissions: auth_result.permissions,
            security_level: SecurityLevel::Internal,
            created_at: Utc::now(),
            expires_at: Some(Utc::now() + chrono::Duration::minutes(self.config.session_timeout_minutes as i64)),
        };
        
        // Log successful authentication
        self.audit_service.log_event(SecurityEvent::Authentication {
            user_id: auth_result.user_id,
            method: credentials.auth_method().to_string(),
            success: true,
            ip_address: credentials.ip_address(),
        }).await?;
        
        // Add session to tracking
        self.session_tracker.add_session(context.clone()).await;
        
        Ok(context)
    }
    
    /// Authorize an action for a security context
    pub async fn authorize(&self, context: &SecurityContext, resource: &str, action: &str) -> crate::core::error::Result<bool> {
        let authorized = self.authz_service.authorize(context, resource, action).await?;
        
        // Log authorization attempt
        self.audit_service.log_event(SecurityEvent::Authorization {
            user_id: context.user_id.as_deref().unwrap_or("anonymous").to_string(),
            resource: resource.to_string(),
            action: action.to_string(),
            granted: authorized,
        }).await?;
        
        Ok(authorized)
    }
    
    /// Encrypt data with security context
    pub async fn encrypt(&self, context: &SecurityContext, data: &[u8]) -> crate::core::error::Result<Vec<u8>> {
        let encrypted = self.encryption_service.encrypt(data, context).await?;
        
        // Log data access
        self.audit_service.log_event(SecurityEvent::DataAccess {
            user_id: context.user_id.as_deref().unwrap_or("system").to_string(),
            resource: "encrypted_data".to_string(),
            operation: "encrypt".to_string(),
            classification: context.security_level.clone(),
        }).await?;
        
        Ok(encrypted)
    }
    
    /// Decrypt data with security context
    pub async fn decrypt(&self, context: &SecurityContext, data: &[u8]) -> crate::core::error::Result<Vec<u8>> {
        let decrypted = self.encryption_service.decrypt(data, context).await?;
        
        // Log data access
        self.audit_service.log_event(SecurityEvent::DataAccess {
            user_id: context.user_id.as_deref().unwrap_or("system").to_string(),
            resource: "encrypted_data".to_string(),
            operation: "decrypt".to_string(),
            classification: context.security_level.clone(),
        }).await?;
        
        Ok(decrypted)
    }
    
    /// Generate compliance report
    pub async fn generate_compliance_report(&self, framework: &str) -> crate::core::error::Result<ComplianceReport> {
        self.compliance_service.generate_report(framework).await
    }
    
    /// Get security metrics
    pub async fn get_security_metrics(&self) -> crate::core::error::Result<SecurityMetrics> {
        let auth_events = self.audit_service.count_events_by_type("authentication", chrono::Duration::hours(24)).await?;
        let threat_events = self.audit_service.count_events_by_type("threat", chrono::Duration::hours(24)).await?;
        let violations = self.audit_service.count_events_by_type("violation", chrono::Duration::hours(24)).await?;
        
        // Clean up expired sessions before counting
        self.session_tracker.cleanup_expired_sessions().await;
        let active_sessions = self.session_tracker.count_active_sessions().await;
        
        Ok(SecurityMetrics {
            authentication_events_24h: auth_events,
            threats_detected_24h: threat_events,
            policy_violations_24h: violations,
            active_sessions,
        })
    }
    
    /// Logout a user session
    pub async fn logout(&self, session_id: &Uuid) -> crate::core::error::Result<bool> {
        let removed = self.session_tracker.remove_session(session_id).await;
        
        if removed {
            // Log logout event
            self.audit_service.log_event(SecurityEvent::Authentication {
                user_id: "unknown".to_string(), // We could enhance this by getting user from session
                method: "logout".to_string(),
                success: true,
                ip_address: None,
            }).await?;
        }
        
        Ok(removed)
    }
    
    /// Get session information
    pub async fn get_session(&self, session_id: &Uuid) -> Option<SecurityContext> {
        self.session_tracker.get_session(session_id).await
    }
    
    /// Get all active session IDs (for administrative purposes)
    pub async fn get_active_session_ids(&self) -> Vec<Uuid> {
        self.session_tracker.get_active_session_ids().await
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct SecurityMetrics {
    pub authentication_events_24h: u64,
    pub threats_detected_24h: u64,
    pub policy_violations_24h: u64,
    pub active_sessions: u64,
}

/// Security error types
#[derive(Debug, thiserror::Error)]
pub enum SecurityError {
    #[error("Authentication failed: {0}")]
    AuthenticationFailed(String),
    
    #[error("Authorization denied: {0}")]
    AuthorizationDenied(String),
    
    #[error("Encryption failed: {0}")]
    EncryptionFailed(String),
    
    #[error("Compliance violation: {0}")]
    ComplianceViolation(String),
    
    #[error("Security threat detected: {0}")]
    ThreatDetected(String),
    
    #[error("Audit failed: {0}")]
    AuditFailed(String),
    
    #[error("Configuration error: {0}")]
    ConfigError(String),
}

impl From<SecurityError> for crate::core::error::RustChainError {
    fn from(err: SecurityError) -> Self {
        crate::core::error::RustChainError::Security(err.to_string())
    }
}