Skip to main content

oxirs_chat/security/
mod.rs

1//! Security Module for OxiRS AI Components
2//!
3//! Provides comprehensive security features including:
4//! - Secure credential management with encryption
5//! - Input validation and sanitization
6//! - Rate limiting and throttling
7//! - Audit logging for security events
8//! - Memory-safe operations
9//! - DDoS protection
10
11pub mod audit_log;
12pub mod credentials;
13pub mod encryption;
14pub mod input_validation;
15pub mod memory_protection;
16pub mod rate_limiting;
17
18pub use audit_log::{AuditLogger, SecurityEvent};
19pub use credentials::{CredentialManager, SecureCredential};
20pub use encryption::{EncryptionConfig, Encryptor};
21pub use input_validation::{InputValidator, ValidationResult};
22pub use memory_protection::{MemoryGuard, SecureMemory};
23pub use rate_limiting::{RateLimitConfig, RateLimiter};
24
25use anyhow::Result;
26use serde::{Deserialize, Serialize};
27
28/// Security configuration for AI modules
29#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct SecurityConfig {
31    /// Enable credential encryption
32    pub encrypt_credentials: bool,
33
34    /// Enable input validation
35    pub validate_inputs: bool,
36
37    /// Enable rate limiting
38    pub enable_rate_limiting: bool,
39
40    /// Enable audit logging
41    pub enable_audit_log: bool,
42
43    /// Maximum input size (bytes)
44    pub max_input_size: usize,
45
46    /// Maximum tokens per request
47    pub max_tokens_per_request: usize,
48
49    /// Rate limit: requests per minute
50    pub requests_per_minute: usize,
51
52    /// Rate limit: tokens per minute
53    pub tokens_per_minute: usize,
54
55    /// Enable memory protection
56    pub enable_memory_protection: bool,
57
58    /// Memory limit for embeddings (MB)
59    pub embedding_memory_limit_mb: usize,
60
61    /// Enable DDoS protection
62    pub enable_ddos_protection: bool,
63
64    /// IP whitelist (empty = allow all)
65    pub ip_whitelist: Vec<String>,
66
67    /// IP blacklist
68    pub ip_blacklist: Vec<String>,
69}
70
71impl Default for SecurityConfig {
72    fn default() -> Self {
73        Self {
74            encrypt_credentials: true,
75            validate_inputs: true,
76            enable_rate_limiting: true,
77            enable_audit_log: true,
78            max_input_size: 1024 * 1024, // 1MB
79            max_tokens_per_request: 4096,
80            requests_per_minute: 60,
81            tokens_per_minute: 100_000,
82            enable_memory_protection: true,
83            embedding_memory_limit_mb: 1024, // 1GB
84            enable_ddos_protection: true,
85            ip_whitelist: vec![],
86            ip_blacklist: vec![],
87        }
88    }
89}
90
91/// Security manager coordinating all security features
92pub struct SecurityManager {
93    config: SecurityConfig,
94    credential_manager: CredentialManager,
95    input_validator: InputValidator,
96    rate_limiter: RateLimiter,
97    audit_logger: AuditLogger,
98    memory_guard: MemoryGuard,
99}
100
101impl SecurityManager {
102    pub fn new(config: SecurityConfig) -> Result<Self> {
103        let credential_manager = CredentialManager::new(config.encrypt_credentials)?;
104        let input_validator =
105            InputValidator::new(config.max_input_size, config.max_tokens_per_request);
106        let rate_limiter = RateLimiter::new(RateLimitConfig {
107            requests_per_minute: config.requests_per_minute,
108            tokens_per_minute: config.tokens_per_minute,
109            enable_burst: true,
110            burst_size: config.requests_per_minute / 10,
111        });
112        let audit_logger = AuditLogger::new()?;
113        let memory_guard = MemoryGuard::new(config.embedding_memory_limit_mb * 1024 * 1024);
114
115        Ok(Self {
116            config,
117            credential_manager,
118            input_validator,
119            rate_limiter,
120            audit_logger,
121            memory_guard,
122        })
123    }
124
125    /// Validate and sanitize user input
126    pub fn validate_input(&self, input: &str, user_id: &str) -> Result<ValidationResult> {
127        if !self.config.validate_inputs {
128            return Ok(ValidationResult::valid(input.to_string()));
129        }
130
131        // Log validation attempt
132        self.audit_logger
133            .log_event(SecurityEvent::InputValidation {
134                user_id: user_id.to_string(),
135                input_length: input.len(),
136                timestamp: chrono::Utc::now(),
137            })?;
138
139        self.input_validator.validate(input)
140    }
141
142    /// Check rate limit for user
143    pub fn check_rate_limit(&self, user_id: &str, tokens: usize) -> Result<bool> {
144        if !self.config.enable_rate_limiting {
145            return Ok(true);
146        }
147
148        let allowed = self.rate_limiter.check_limit(user_id, tokens)?;
149
150        if !allowed {
151            self.audit_logger
152                .log_event(SecurityEvent::RateLimitExceeded {
153                    user_id: user_id.to_string(),
154                    timestamp: chrono::Utc::now(),
155                })?;
156        }
157
158        Ok(allowed)
159    }
160
161    /// Store credential securely
162    pub fn store_credential(&mut self, provider: &str, api_key: &str) -> Result<()> {
163        self.audit_logger
164            .log_event(SecurityEvent::CredentialStored {
165                provider: provider.to_string(),
166                timestamp: chrono::Utc::now(),
167            })?;
168
169        self.credential_manager.store(provider, api_key)
170    }
171
172    /// Retrieve credential securely
173    pub fn retrieve_credential(&self, provider: &str) -> Result<Option<SecureCredential>> {
174        self.credential_manager.retrieve(provider)
175    }
176
177    /// Check memory usage
178    pub fn check_memory_usage(&self, additional_bytes: usize) -> Result<bool> {
179        if !self.config.enable_memory_protection {
180            return Ok(true);
181        }
182
183        Ok(self.memory_guard.can_allocate(additional_bytes))
184    }
185
186    /// Check IP address
187    pub fn check_ip(&self, ip: &str) -> Result<bool> {
188        if !self.config.enable_ddos_protection {
189            return Ok(true);
190        }
191
192        // Check blacklist first
193        if self.config.ip_blacklist.contains(&ip.to_string()) {
194            self.audit_logger.log_event(SecurityEvent::IpBlocked {
195                ip: ip.to_string(),
196                reason: "blacklisted".to_string(),
197                timestamp: chrono::Utc::now(),
198            })?;
199            return Ok(false);
200        }
201
202        // If whitelist is configured, check it
203        if !self.config.ip_whitelist.is_empty() {
204            let allowed = self.config.ip_whitelist.contains(&ip.to_string());
205            if !allowed {
206                self.audit_logger.log_event(SecurityEvent::IpBlocked {
207                    ip: ip.to_string(),
208                    reason: "not whitelisted".to_string(),
209                    timestamp: chrono::Utc::now(),
210                })?;
211            }
212            return Ok(allowed);
213        }
214
215        Ok(true)
216    }
217
218    /// Get audit log for security analysis
219    pub fn get_audit_events(
220        &self,
221        start_time: chrono::DateTime<chrono::Utc>,
222    ) -> Result<Vec<SecurityEvent>> {
223        self.audit_logger.get_events_since(start_time)
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn test_security_manager_creation() {
233        let config = SecurityConfig::default();
234        let manager = SecurityManager::new(config);
235        assert!(manager.is_ok());
236    }
237
238    #[test]
239    fn test_input_validation() {
240        let config = SecurityConfig::default();
241        let manager = SecurityManager::new(config).expect("should succeed");
242
243        let result = manager.validate_input("SELECT * FROM users", "test_user");
244        assert!(result.is_ok());
245    }
246
247    #[test]
248    fn test_rate_limiting() {
249        let config = SecurityConfig::default();
250        let manager = SecurityManager::new(config).expect("should succeed");
251
252        // First request should be allowed
253        let result = manager.check_rate_limit("test_user", 100);
254        assert!(result.is_ok());
255        assert!(result.expect("should succeed"));
256    }
257
258    #[test]
259    fn test_memory_check() {
260        let config = SecurityConfig::default();
261        let manager = SecurityManager::new(config).expect("should succeed");
262
263        // Small allocation should be allowed
264        let result = manager.check_memory_usage(1024);
265        assert!(result.is_ok());
266        assert!(result.expect("should succeed"));
267    }
268
269    #[test]
270    fn test_ip_whitelist() {
271        let config = SecurityConfig {
272            ip_whitelist: vec!["127.0.0.1".to_string()],
273            ..SecurityConfig::default()
274        };
275        let manager = SecurityManager::new(config).expect("should succeed");
276
277        // Whitelisted IP should be allowed
278        assert!(manager.check_ip("127.0.0.1").expect("should succeed"));
279
280        // Non-whitelisted IP should be blocked
281        assert!(!manager.check_ip("192.168.1.1").expect("should succeed"));
282    }
283
284    #[test]
285    fn test_ip_blacklist() {
286        let config = SecurityConfig {
287            ip_blacklist: vec!["10.0.0.1".to_string()],
288            ..SecurityConfig::default()
289        };
290        let manager = SecurityManager::new(config).expect("should succeed");
291
292        // Blacklisted IP should be blocked
293        assert!(!manager.check_ip("10.0.0.1").expect("should succeed"));
294
295        // Non-blacklisted IP should be allowed
296        assert!(manager.check_ip("127.0.0.1").expect("should succeed"));
297    }
298}