1use crate::error::{AllSourceError, Result};
9use aes_gcm::{
10 Aes256Gcm, Nonce,
11 aead::{Aead, KeyInit, OsRng},
12};
13use base64::{Engine as _, engine::general_purpose};
14use dashmap::DashMap;
15use parking_lot::RwLock;
16use serde::{Deserialize, Serialize};
17use std::sync::Arc;
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct EncryptionConfig {
22 pub enabled: bool,
24
25 pub key_rotation_days: u32,
27
28 pub algorithm: EncryptionAlgorithm,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
33pub enum EncryptionAlgorithm {
34 Aes256Gcm,
35 ChaCha20Poly1305,
36}
37
38impl Default for EncryptionConfig {
39 fn default() -> Self {
40 Self {
41 enabled: true,
42 key_rotation_days: 90,
43 algorithm: EncryptionAlgorithm::Aes256Gcm,
44 }
45 }
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct EncryptedData {
51 pub ciphertext: String,
53
54 pub nonce: String,
56
57 pub key_id: String,
59
60 pub algorithm: EncryptionAlgorithm,
62
63 pub version: u32,
65}
66
67#[derive(Debug, Clone)]
69struct DataEncryptionKey {
70 key_id: String,
71 key_bytes: Vec<u8>,
72 version: u32,
73 created_at: chrono::DateTime<chrono::Utc>,
74 active: bool,
75}
76
77pub struct FieldEncryption {
79 config: Arc<RwLock<EncryptionConfig>>,
80
81 deks: Arc<DashMap<String, DataEncryptionKey>>,
83
84 active_key_id: Arc<RwLock<Option<String>>>,
86}
87
88impl FieldEncryption {
89 pub fn new(config: EncryptionConfig) -> Result<Self> {
91 let manager = Self {
92 config: Arc::new(RwLock::new(config)),
93 deks: Arc::new(DashMap::new()),
94 active_key_id: Arc::new(RwLock::new(None)),
95 };
96
97 manager.rotate_keys()?;
99
100 Ok(manager)
101 }
102
103 pub fn encrypt_string(&self, plaintext: &str, field_name: &str) -> Result<EncryptedData> {
105 if !self.config.read().enabled {
106 return Err(AllSourceError::ValidationError(
107 "Encryption is disabled".to_string(),
108 ));
109 }
110
111 let active_key_id = self.active_key_id.read();
112 let key_id = active_key_id
113 .as_ref()
114 .ok_or_else(|| AllSourceError::ValidationError("No active encryption key".to_string()))?
115 .clone();
116
117 let dek_ref = self.deks.get(&key_id).ok_or_else(|| {
118 AllSourceError::ValidationError("Encryption key not found".to_string())
119 })?;
120 let dek = dek_ref.value();
121
122 let cipher = Aes256Gcm::new_from_slice(&dek.key_bytes)
124 .map_err(|e| AllSourceError::ValidationError(format!("Invalid key: {e}")))?;
125
126 let nonce_bytes = aes_gcm::aead::rand_core::RngCore::next_u64(&mut OsRng).to_le_bytes();
128 let mut nonce_array = [0u8; 12];
129 nonce_array[..8].copy_from_slice(&nonce_bytes);
130 let nonce = Nonce::from_slice(&nonce_array);
131
132 let ciphertext = cipher
134 .encrypt(nonce, plaintext.as_bytes())
135 .map_err(|e| AllSourceError::ValidationError(format!("Encryption failed: {e}")))?;
136
137 Ok(EncryptedData {
138 ciphertext: general_purpose::STANDARD.encode(&ciphertext),
139 nonce: general_purpose::STANDARD.encode(nonce.as_slice()),
140 key_id: key_id.clone(),
141 algorithm: self.config.read().algorithm.clone(),
142 version: dek.version,
143 })
144 }
145
146 pub fn decrypt_string(&self, encrypted: &EncryptedData) -> Result<String> {
148 if !self.config.read().enabled {
149 return Err(AllSourceError::ValidationError(
150 "Encryption is disabled".to_string(),
151 ));
152 }
153
154 let dek_ref = self.deks.get(&encrypted.key_id).ok_or_else(|| {
155 AllSourceError::ValidationError(format!(
156 "Encryption key {} not found",
157 encrypted.key_id
158 ))
159 })?;
160 let dek = dek_ref.value();
161
162 let ciphertext = general_purpose::STANDARD
164 .decode(&encrypted.ciphertext)
165 .map_err(|e| {
166 AllSourceError::ValidationError(format!("Invalid ciphertext encoding: {e}"))
167 })?;
168
169 let nonce_bytes = general_purpose::STANDARD
170 .decode(&encrypted.nonce)
171 .map_err(|e| AllSourceError::ValidationError(format!("Invalid nonce encoding: {e}")))?;
172
173 let nonce = Nonce::from_slice(&nonce_bytes);
174
175 let cipher = Aes256Gcm::new_from_slice(&dek.key_bytes)
177 .map_err(|e| AllSourceError::ValidationError(format!("Invalid key: {e}")))?;
178
179 let plaintext_bytes = cipher
180 .decrypt(nonce, ciphertext.as_ref())
181 .map_err(|e| AllSourceError::ValidationError(format!("Decryption failed: {e}")))?;
182
183 String::from_utf8(plaintext_bytes)
184 .map_err(|e| AllSourceError::ValidationError(format!("Invalid UTF-8: {e}")))
185 }
186
187 pub fn rotate_keys(&self) -> Result<()> {
189 let mut active_key_id = self.active_key_id.write();
190
191 let key_id = uuid::Uuid::new_v4().to_string();
193 let mut key_bytes = vec![0u8; 32]; aes_gcm::aead::rand_core::RngCore::fill_bytes(&mut OsRng, &mut key_bytes);
195
196 let version = self.deks.len() as u32 + 1;
197
198 let new_key = DataEncryptionKey {
199 key_id: key_id.clone(),
200 key_bytes,
201 version,
202 created_at: chrono::Utc::now(),
203 active: true,
204 };
205
206 for mut entry in self.deks.iter_mut() {
208 entry.value_mut().active = false;
209 }
210
211 self.deks.insert(key_id.clone(), new_key);
213 *active_key_id = Some(key_id);
214
215 Ok(())
216 }
217
218 pub fn get_stats(&self) -> EncryptionStats {
220 let active_key_id = self.active_key_id.read();
221
222 EncryptionStats {
223 enabled: self.config.read().enabled,
224 total_keys: self.deks.len(),
225 active_key_version: active_key_id
226 .as_ref()
227 .and_then(|id| self.deks.get(id))
228 .map_or(0, |entry| entry.value().version),
229 algorithm: self.config.read().algorithm.clone(),
230 }
231 }
232}
233
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct EncryptionStats {
236 pub enabled: bool,
237 pub total_keys: usize,
238 pub active_key_version: u32,
239 pub algorithm: EncryptionAlgorithm,
240}
241
242pub trait Encryptable {
244 fn encrypt(&self, encryption: &FieldEncryption, field_name: &str) -> Result<EncryptedData>;
245 fn decrypt(encrypted: &EncryptedData, encryption: &FieldEncryption) -> Result<Self>
246 where
247 Self: Sized;
248}
249
250impl Encryptable for String {
251 fn encrypt(&self, encryption: &FieldEncryption, field_name: &str) -> Result<EncryptedData> {
252 encryption.encrypt_string(self, field_name)
253 }
254
255 fn decrypt(encrypted: &EncryptedData, encryption: &FieldEncryption) -> Result<Self> {
256 encryption.decrypt_string(encrypted)
257 }
258}
259
260pub fn encrypt_json_value(
262 value: &serde_json::Value,
263 encryption: &FieldEncryption,
264 field_name: &str,
265) -> Result<EncryptedData> {
266 let json_string = serde_json::to_string(value)
267 .map_err(|e| AllSourceError::ValidationError(format!("JSON serialization failed: {e}")))?;
268
269 encryption.encrypt_string(&json_string, field_name)
270}
271
272pub fn decrypt_json_value(
274 encrypted: &EncryptedData,
275 encryption: &FieldEncryption,
276) -> Result<serde_json::Value> {
277 let json_string = encryption.decrypt_string(encrypted)?;
278
279 serde_json::from_str(&json_string)
280 .map_err(|e| AllSourceError::ValidationError(format!("JSON deserialization failed: {e}")))
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286
287 #[test]
288 fn test_encryption_creation() {
289 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
290 let stats = encryption.get_stats();
291
292 assert!(stats.enabled);
293 assert_eq!(stats.total_keys, 1);
294 assert_eq!(stats.active_key_version, 1);
295 }
296
297 #[test]
298 fn test_encrypt_decrypt_string() {
299 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
300 let plaintext = "sensitive data";
301
302 let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
303 assert_ne!(encrypted.ciphertext, plaintext);
304
305 let decrypted = encryption.decrypt_string(&encrypted).unwrap();
306 assert_eq!(decrypted, plaintext);
307 }
308
309 #[test]
310 fn test_encrypt_decrypt_json() {
311 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
312 let value = serde_json::json!({
313 "username": "john_doe",
314 "ssn": "123-45-6789",
315 "credit_card": "4111-1111-1111-1111"
316 });
317
318 let encrypted = encrypt_json_value(&value, &encryption, "sensitive_data").unwrap();
319 let decrypted = decrypt_json_value(&encrypted, &encryption).unwrap();
320
321 assert_eq!(decrypted, value);
322 }
323
324 #[test]
325 fn test_key_rotation() {
326 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
327 let plaintext = "sensitive data";
328
329 let encrypted1 = encryption.encrypt_string(plaintext, "test").unwrap();
331 let key_id1 = encrypted1.key_id.clone();
332
333 encryption.rotate_keys().unwrap();
335
336 let encrypted2 = encryption.encrypt_string(plaintext, "test").unwrap();
338 let key_id2 = encrypted2.key_id.clone();
339
340 assert_ne!(key_id1, key_id2);
342 assert_eq!(encrypted2.version, 2);
343
344 let decrypted1 = encryption.decrypt_string(&encrypted1).unwrap();
346 assert_eq!(decrypted1, plaintext);
347
348 let decrypted2 = encryption.decrypt_string(&encrypted2).unwrap();
350 assert_eq!(decrypted2, plaintext);
351 }
352
353 #[test]
354 fn test_multiple_key_rotations() {
355 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
356 let plaintext = "test data";
357
358 let mut encrypted_data = Vec::new();
359
360 for _ in 0..5 {
362 let encrypted = encryption.encrypt_string(plaintext, "test").unwrap();
363 encrypted_data.push(encrypted);
364 encryption.rotate_keys().unwrap();
365 }
366
367 for encrypted in &encrypted_data {
369 let decrypted = encryption.decrypt_string(encrypted).unwrap();
370 assert_eq!(decrypted, plaintext);
371 }
372
373 let stats = encryption.get_stats();
374 assert_eq!(stats.total_keys, 6); assert_eq!(stats.active_key_version, 6);
376 }
377
378 #[test]
379 fn test_disabled_encryption() {
380 let config = EncryptionConfig {
381 enabled: false,
382 ..Default::default()
383 };
384
385 let encryption = FieldEncryption::new(config).unwrap();
386 let plaintext = "test";
387
388 let result = encryption.encrypt_string(plaintext, "test");
389 assert!(result.is_err());
390 }
391
392 #[test]
393 fn test_encryption_config_default() {
394 let config = EncryptionConfig::default();
395 assert!(config.enabled);
396 assert_eq!(config.key_rotation_days, 90);
397 assert_eq!(config.algorithm, EncryptionAlgorithm::Aes256Gcm);
398 }
399
400 #[test]
401 fn test_encryption_algorithm_equality() {
402 assert_eq!(
403 EncryptionAlgorithm::Aes256Gcm,
404 EncryptionAlgorithm::Aes256Gcm
405 );
406 assert_ne!(
407 EncryptionAlgorithm::Aes256Gcm,
408 EncryptionAlgorithm::ChaCha20Poly1305
409 );
410 }
411
412 #[test]
413 fn test_encryption_config_serde() {
414 let config = EncryptionConfig::default();
415 let json = serde_json::to_string(&config).unwrap();
416 let parsed: EncryptionConfig = serde_json::from_str(&json).unwrap();
417 assert_eq!(parsed.enabled, config.enabled);
418 assert_eq!(parsed.algorithm, config.algorithm);
419 }
420
421 #[test]
422 fn test_encrypted_data_serde() {
423 let encrypted = EncryptedData {
424 ciphertext: "encrypted_data".to_string(),
425 nonce: "nonce_value".to_string(),
426 key_id: "key-123".to_string(),
427 algorithm: EncryptionAlgorithm::Aes256Gcm,
428 version: 1,
429 };
430
431 let json = serde_json::to_string(&encrypted).unwrap();
432 let parsed: EncryptedData = serde_json::from_str(&json).unwrap();
433 assert_eq!(parsed.ciphertext, encrypted.ciphertext);
434 assert_eq!(parsed.key_id, encrypted.key_id);
435 assert_eq!(parsed.version, encrypted.version);
436 }
437
438 #[test]
439 fn test_encrypt_empty_string() {
440 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
441 let plaintext = "";
442
443 let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
444 let decrypted = encryption.decrypt_string(&encrypted).unwrap();
445 assert_eq!(decrypted, plaintext);
446 }
447
448 #[test]
449 fn test_encrypt_long_string() {
450 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
451 let plaintext = "a".repeat(10000);
452
453 let encrypted = encryption.encrypt_string(&plaintext, "test_field").unwrap();
454 let decrypted = encryption.decrypt_string(&encrypted).unwrap();
455 assert_eq!(decrypted, plaintext);
456 }
457
458 #[test]
459 fn test_encrypt_unicode_string() {
460 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
461 let plaintext = "日本語テスト 🎉 émojis";
462
463 let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
464 let decrypted = encryption.decrypt_string(&encrypted).unwrap();
465 assert_eq!(decrypted, plaintext);
466 }
467
468 #[test]
469 fn test_encryption_stats() {
470 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
471
472 let stats = encryption.get_stats();
473 assert!(stats.enabled);
474 assert_eq!(stats.total_keys, 1);
475 assert_eq!(stats.active_key_version, 1);
476 assert_eq!(stats.algorithm, EncryptionAlgorithm::Aes256Gcm);
477 }
478
479 #[test]
480 fn test_decrypt_with_invalid_key() {
481 let encryption1 = FieldEncryption::new(EncryptionConfig::default()).unwrap();
482 let encryption2 = FieldEncryption::new(EncryptionConfig::default()).unwrap();
483
484 let plaintext = "test data";
485 let encrypted = encryption1.encrypt_string(plaintext, "test").unwrap();
486
487 let result = encryption2.decrypt_string(&encrypted);
489 assert!(result.is_err());
490 }
491
492 #[test]
493 fn test_encryption_different_fields() {
494 let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
495
496 let data1 = "data for field 1";
497 let data2 = "data for field 2";
498
499 let encrypted1 = encryption.encrypt_string(data1, "field1").unwrap();
500 let encrypted2 = encryption.encrypt_string(data2, "field2").unwrap();
501
502 let encrypted1_again = encryption.encrypt_string(data1, "field1").unwrap();
504 assert_ne!(encrypted1.ciphertext, encrypted1_again.ciphertext);
505
506 assert_eq!(encryption.decrypt_string(&encrypted1).unwrap(), data1);
508 assert_eq!(encryption.decrypt_string(&encrypted2).unwrap(), data2);
509 }
510}