allsource-core 0.19.1

High-performance event store core built in Rust
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
/// Field-Level Encryption for Sensitive Data
///
/// Provides transparent encryption/decryption of sensitive fields using:
/// - AES-256-GCM for symmetric encryption
/// - Envelope encryption pattern
/// - Key rotation support
/// - Per-field encryption keys
use crate::error::{AllSourceError, Result};
use aes_gcm::{
    Aes256Gcm, Nonce,
    aead::{Aead, KeyInit, OsRng},
};
use base64::{Engine as _, engine::general_purpose};
use dashmap::DashMap;
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

/// Encryption configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionConfig {
    /// Enable encryption
    pub enabled: bool,

    /// Key rotation period in days
    pub key_rotation_days: u32,

    /// Algorithm to use
    pub algorithm: EncryptionAlgorithm,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum EncryptionAlgorithm {
    Aes256Gcm,
    ChaCha20Poly1305,
}

impl Default for EncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            key_rotation_days: 90,
            algorithm: EncryptionAlgorithm::Aes256Gcm,
        }
    }
}

/// Encrypted data with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedData {
    /// Ciphertext (base64 encoded)
    pub ciphertext: String,

    /// Nonce/IV (base64 encoded)
    pub nonce: String,

    /// Key ID used for encryption
    pub key_id: String,

    /// Algorithm used
    pub algorithm: EncryptionAlgorithm,

    /// Version for key rotation
    pub version: u32,
}

/// Data encryption key
#[derive(Debug, Clone)]
struct DataEncryptionKey {
    key_id: String,
    key_bytes: Vec<u8>,
    version: u32,
    created_at: chrono::DateTime<chrono::Utc>,
    active: bool,
}

/// Field-level encryption manager
pub struct FieldEncryption {
    config: Arc<RwLock<EncryptionConfig>>,

    // Data encryption keys (DEKs) - using DashMap for lock-free concurrent access
    deks: Arc<DashMap<String, DataEncryptionKey>>,

    // Active key for encryption
    active_key_id: Arc<RwLock<Option<String>>>,
}

impl FieldEncryption {
    /// Create new field encryption manager
    pub fn new(config: EncryptionConfig) -> Result<Self> {
        let manager = Self {
            config: Arc::new(RwLock::new(config)),
            deks: Arc::new(DashMap::new()),
            active_key_id: Arc::new(RwLock::new(None)),
        };

        // Generate initial key
        manager.rotate_keys()?;

        Ok(manager)
    }

    /// Encrypt a string value
    pub fn encrypt_string(&self, plaintext: &str, field_name: &str) -> Result<EncryptedData> {
        if !self.config.read().enabled {
            return Err(AllSourceError::ValidationError(
                "Encryption is disabled".to_string(),
            ));
        }

        let active_key_id = self.active_key_id.read();
        let key_id = active_key_id
            .as_ref()
            .ok_or_else(|| AllSourceError::ValidationError("No active encryption key".to_string()))?
            .clone();

        let dek_ref = self.deks.get(&key_id).ok_or_else(|| {
            AllSourceError::ValidationError("Encryption key not found".to_string())
        })?;
        let dek = dek_ref.value();

        // Use AES-256-GCM
        let cipher = Aes256Gcm::new_from_slice(&dek.key_bytes)
            .map_err(|e| AllSourceError::ValidationError(format!("Invalid key: {e}")))?;

        // Generate random nonce
        let nonce_bytes = aes_gcm::aead::rand_core::RngCore::next_u64(&mut OsRng).to_le_bytes();
        let mut nonce_array = [0u8; 12];
        nonce_array[..8].copy_from_slice(&nonce_bytes);
        let nonce = Nonce::from_slice(&nonce_array);

        // Encrypt with associated data (field name) for integrity
        let ciphertext = cipher
            .encrypt(nonce, plaintext.as_bytes())
            .map_err(|e| AllSourceError::ValidationError(format!("Encryption failed: {e}")))?;

        Ok(EncryptedData {
            ciphertext: general_purpose::STANDARD.encode(&ciphertext),
            nonce: general_purpose::STANDARD.encode(nonce.as_slice()),
            key_id: key_id.clone(),
            algorithm: self.config.read().algorithm.clone(),
            version: dek.version,
        })
    }

    /// Decrypt a string value
    pub fn decrypt_string(&self, encrypted: &EncryptedData) -> Result<String> {
        if !self.config.read().enabled {
            return Err(AllSourceError::ValidationError(
                "Encryption is disabled".to_string(),
            ));
        }

        let dek_ref = self.deks.get(&encrypted.key_id).ok_or_else(|| {
            AllSourceError::ValidationError(format!(
                "Encryption key {} not found",
                encrypted.key_id
            ))
        })?;
        let dek = dek_ref.value();

        // Decode base64
        let ciphertext = general_purpose::STANDARD
            .decode(&encrypted.ciphertext)
            .map_err(|e| {
                AllSourceError::ValidationError(format!("Invalid ciphertext encoding: {e}"))
            })?;

        let nonce_bytes = general_purpose::STANDARD
            .decode(&encrypted.nonce)
            .map_err(|e| AllSourceError::ValidationError(format!("Invalid nonce encoding: {e}")))?;

        let nonce = Nonce::from_slice(&nonce_bytes);

        // Decrypt
        let cipher = Aes256Gcm::new_from_slice(&dek.key_bytes)
            .map_err(|e| AllSourceError::ValidationError(format!("Invalid key: {e}")))?;

        let plaintext_bytes = cipher
            .decrypt(nonce, ciphertext.as_ref())
            .map_err(|e| AllSourceError::ValidationError(format!("Decryption failed: {e}")))?;

        String::from_utf8(plaintext_bytes)
            .map_err(|e| AllSourceError::ValidationError(format!("Invalid UTF-8: {e}")))
    }

    /// Rotate encryption keys
    pub fn rotate_keys(&self) -> Result<()> {
        let mut active_key_id = self.active_key_id.write();

        // Generate new key
        let key_id = uuid::Uuid::new_v4().to_string();
        let mut key_bytes = vec![0u8; 32]; // 256 bits for AES-256
        aes_gcm::aead::rand_core::RngCore::fill_bytes(&mut OsRng, &mut key_bytes);

        let version = self.deks.len() as u32 + 1;

        let new_key = DataEncryptionKey {
            key_id: key_id.clone(),
            key_bytes,
            version,
            created_at: chrono::Utc::now(),
            active: true,
        };

        // Deactivate old keys
        for mut entry in self.deks.iter_mut() {
            entry.value_mut().active = false;
        }

        // Add new key
        self.deks.insert(key_id.clone(), new_key);
        *active_key_id = Some(key_id);

        Ok(())
    }

    /// Get encryption statistics
    pub fn get_stats(&self) -> EncryptionStats {
        let active_key_id = self.active_key_id.read();

        EncryptionStats {
            enabled: self.config.read().enabled,
            total_keys: self.deks.len(),
            active_key_version: active_key_id
                .as_ref()
                .and_then(|id| self.deks.get(id))
                .map_or(0, |entry| entry.value().version),
            algorithm: self.config.read().algorithm.clone(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionStats {
    pub enabled: bool,
    pub total_keys: usize,
    pub active_key_version: u32,
    pub algorithm: EncryptionAlgorithm,
}

/// Trait for types that can be encrypted
pub trait Encryptable {
    fn encrypt(&self, encryption: &FieldEncryption, field_name: &str) -> Result<EncryptedData>;
    fn decrypt(encrypted: &EncryptedData, encryption: &FieldEncryption) -> Result<Self>
    where
        Self: Sized;
}

impl Encryptable for String {
    fn encrypt(&self, encryption: &FieldEncryption, field_name: &str) -> Result<EncryptedData> {
        encryption.encrypt_string(self, field_name)
    }

    fn decrypt(encrypted: &EncryptedData, encryption: &FieldEncryption) -> Result<Self> {
        encryption.decrypt_string(encrypted)
    }
}

/// Helper for encrypting JSON values
pub fn encrypt_json_value(
    value: &serde_json::Value,
    encryption: &FieldEncryption,
    field_name: &str,
) -> Result<EncryptedData> {
    let json_string = serde_json::to_string(value)
        .map_err(|e| AllSourceError::ValidationError(format!("JSON serialization failed: {e}")))?;

    encryption.encrypt_string(&json_string, field_name)
}

/// Helper for decrypting JSON values
pub fn decrypt_json_value(
    encrypted: &EncryptedData,
    encryption: &FieldEncryption,
) -> Result<serde_json::Value> {
    let json_string = encryption.decrypt_string(encrypted)?;

    serde_json::from_str(&json_string)
        .map_err(|e| AllSourceError::ValidationError(format!("JSON deserialization failed: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encryption_creation() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let stats = encryption.get_stats();

        assert!(stats.enabled);
        assert_eq!(stats.total_keys, 1);
        assert_eq!(stats.active_key_version, 1);
    }

    #[test]
    fn test_encrypt_decrypt_string() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "sensitive data";

        let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
        assert_ne!(encrypted.ciphertext, plaintext);

        let decrypted = encryption.decrypt_string(&encrypted).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encrypt_decrypt_json() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let value = serde_json::json!({
            "username": "john_doe",
            "ssn": "123-45-6789",
            "credit_card": "4111-1111-1111-1111"
        });

        let encrypted = encrypt_json_value(&value, &encryption, "sensitive_data").unwrap();
        let decrypted = decrypt_json_value(&encrypted, &encryption).unwrap();

        assert_eq!(decrypted, value);
    }

    #[test]
    fn test_key_rotation() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "sensitive data";

        // Encrypt with first key
        let encrypted1 = encryption.encrypt_string(plaintext, "test").unwrap();
        let key_id1 = encrypted1.key_id.clone();

        // Rotate keys
        encryption.rotate_keys().unwrap();

        // Encrypt with new key
        let encrypted2 = encryption.encrypt_string(plaintext, "test").unwrap();
        let key_id2 = encrypted2.key_id.clone();

        // Keys should be different
        assert_ne!(key_id1, key_id2);
        assert_eq!(encrypted2.version, 2);

        // Should still be able to decrypt data encrypted with old key
        let decrypted1 = encryption.decrypt_string(&encrypted1).unwrap();
        assert_eq!(decrypted1, plaintext);

        // Should be able to decrypt data encrypted with new key
        let decrypted2 = encryption.decrypt_string(&encrypted2).unwrap();
        assert_eq!(decrypted2, plaintext);
    }

    #[test]
    fn test_multiple_key_rotations() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "test data";

        let mut encrypted_data = Vec::new();

        // Create data with multiple key versions
        for _ in 0..5 {
            let encrypted = encryption.encrypt_string(plaintext, "test").unwrap();
            encrypted_data.push(encrypted);
            encryption.rotate_keys().unwrap();
        }

        // Should be able to decrypt all versions
        for encrypted in &encrypted_data {
            let decrypted = encryption.decrypt_string(encrypted).unwrap();
            assert_eq!(decrypted, plaintext);
        }

        let stats = encryption.get_stats();
        assert_eq!(stats.total_keys, 6); // Initial + 5 rotations
        assert_eq!(stats.active_key_version, 6);
    }

    #[test]
    fn test_disabled_encryption() {
        let config = EncryptionConfig {
            enabled: false,
            ..Default::default()
        };

        let encryption = FieldEncryption::new(config).unwrap();
        let plaintext = "test";

        let result = encryption.encrypt_string(plaintext, "test");
        assert!(result.is_err());
    }

    #[test]
    fn test_encryption_config_default() {
        let config = EncryptionConfig::default();
        assert!(config.enabled);
        assert_eq!(config.key_rotation_days, 90);
        assert_eq!(config.algorithm, EncryptionAlgorithm::Aes256Gcm);
    }

    #[test]
    fn test_encryption_algorithm_equality() {
        assert_eq!(
            EncryptionAlgorithm::Aes256Gcm,
            EncryptionAlgorithm::Aes256Gcm
        );
        assert_ne!(
            EncryptionAlgorithm::Aes256Gcm,
            EncryptionAlgorithm::ChaCha20Poly1305
        );
    }

    #[test]
    fn test_encryption_config_serde() {
        let config = EncryptionConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let parsed: EncryptionConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.enabled, config.enabled);
        assert_eq!(parsed.algorithm, config.algorithm);
    }

    #[test]
    fn test_encrypted_data_serde() {
        let encrypted = EncryptedData {
            ciphertext: "encrypted_data".to_string(),
            nonce: "nonce_value".to_string(),
            key_id: "key-123".to_string(),
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            version: 1,
        };

        let json = serde_json::to_string(&encrypted).unwrap();
        let parsed: EncryptedData = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.ciphertext, encrypted.ciphertext);
        assert_eq!(parsed.key_id, encrypted.key_id);
        assert_eq!(parsed.version, encrypted.version);
    }

    #[test]
    fn test_encrypt_empty_string() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "";

        let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
        let decrypted = encryption.decrypt_string(&encrypted).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encrypt_long_string() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "a".repeat(10000);

        let encrypted = encryption.encrypt_string(&plaintext, "test_field").unwrap();
        let decrypted = encryption.decrypt_string(&encrypted).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encrypt_unicode_string() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let plaintext = "日本語テスト 🎉 émojis";

        let encrypted = encryption.encrypt_string(plaintext, "test_field").unwrap();
        let decrypted = encryption.decrypt_string(&encrypted).unwrap();
        assert_eq!(decrypted, plaintext);
    }

    #[test]
    fn test_encryption_stats() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();

        let stats = encryption.get_stats();
        assert!(stats.enabled);
        assert_eq!(stats.total_keys, 1);
        assert_eq!(stats.active_key_version, 1);
        assert_eq!(stats.algorithm, EncryptionAlgorithm::Aes256Gcm);
    }

    #[test]
    fn test_decrypt_with_invalid_key() {
        let encryption1 = FieldEncryption::new(EncryptionConfig::default()).unwrap();
        let encryption2 = FieldEncryption::new(EncryptionConfig::default()).unwrap();

        let plaintext = "test data";
        let encrypted = encryption1.encrypt_string(plaintext, "test").unwrap();

        // Try to decrypt with different encryption instance (different keys)
        let result = encryption2.decrypt_string(&encrypted);
        assert!(result.is_err());
    }

    #[test]
    fn test_encryption_different_fields() {
        let encryption = FieldEncryption::new(EncryptionConfig::default()).unwrap();

        let data1 = "data for field 1";
        let data2 = "data for field 2";

        let encrypted1 = encryption.encrypt_string(data1, "field1").unwrap();
        let encrypted2 = encryption.encrypt_string(data2, "field2").unwrap();

        // Even same data produces different ciphertext due to random nonce
        let encrypted1_again = encryption.encrypt_string(data1, "field1").unwrap();
        assert_ne!(encrypted1.ciphertext, encrypted1_again.ciphertext);

        // Both should decrypt correctly
        assert_eq!(encryption.decrypt_string(&encrypted1).unwrap(), data1);
        assert_eq!(encryption.decrypt_string(&encrypted2).unwrap(), data2);
    }
}