oxirs_chat/security/
mod.rs1pub 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#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct SecurityConfig {
31 pub encrypt_credentials: bool,
33
34 pub validate_inputs: bool,
36
37 pub enable_rate_limiting: bool,
39
40 pub enable_audit_log: bool,
42
43 pub max_input_size: usize,
45
46 pub max_tokens_per_request: usize,
48
49 pub requests_per_minute: usize,
51
52 pub tokens_per_minute: usize,
54
55 pub enable_memory_protection: bool,
57
58 pub embedding_memory_limit_mb: usize,
60
61 pub enable_ddos_protection: bool,
63
64 pub ip_whitelist: Vec<String>,
66
67 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, 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, enable_ddos_protection: true,
85 ip_whitelist: vec![],
86 ip_blacklist: vec![],
87 }
88 }
89}
90
91pub 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 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 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 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 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 pub fn retrieve_credential(&self, provider: &str) -> Result<Option<SecureCredential>> {
174 self.credential_manager.retrieve(provider)
175 }
176
177 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 pub fn check_ip(&self, ip: &str) -> Result<bool> {
188 if !self.config.enable_ddos_protection {
189 return Ok(true);
190 }
191
192 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 !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 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 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 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 assert!(manager.check_ip("127.0.0.1").expect("should succeed"));
279
280 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 assert!(!manager.check_ip("10.0.0.1").expect("should succeed"));
294
295 assert!(manager.check_ip("127.0.0.1").expect("should succeed"));
297 }
298}