paladin-ai 0.4.3

Enterprise AI orchestration framework with multi-agent coordination patterns
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
//! Security and encryption utilities for Sentinel Vision System
//!
//! This module provides encryption, secure memory handling, and data protection
//! for vision and document data in the Paladin framework.
//!
//! # Features
//!
//! - **Encryption at Rest**: ChaCha20-Poly1305 authenticated encryption
//! - **Secure Memory**: Automatic memory cleanup using `zeroize`
//! - **Data Retention**: Configurable TTL-based data cleanup
//! - **Audit Logging**: Access logging without sensitive data
//!
//! # Example
//!
//! ```
//! use paladin::infrastructure::security::encryption::{EncryptionService, SecureData};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let service = EncryptionService::new()?;
//!
//! // Encrypt image data
//! let image_data = b"fake image bytes";
//! let encrypted = service.encrypt_image_data(image_data)?;
//!
//! // Decrypt when needed
//! let decrypted = service.decrypt_image_data(&encrypted)?;
//! assert_eq!(image_data, decrypted.as_slice());
//! # Ok(())
//! # }
//! ```

use chacha20poly1305::{
    ChaCha20Poly1305, Nonce,
    aead::{Aead, KeyInit, OsRng},
};
use rand::RngCore;
use std::time::{Duration, SystemTime};
use thiserror::Error;
use zeroize::{Zeroize, ZeroizeOnDrop};

/// Errors that can occur during encryption/decryption operations
#[derive(Debug, Error)]
pub enum EncryptionError {
    /// Failed to generate encryption key
    #[error("Failed to generate encryption key: {0}")]
    KeyGenerationError(String),

    /// Failed to encrypt data
    #[error("Failed to encrypt data: {0}")]
    EncryptionFailed(String),

    /// Failed to decrypt data
    #[error("Failed to decrypt data: {0}")]
    DecryptionFailed(String),

    /// Invalid encrypted data format
    #[error("Invalid encrypted data format: {0}")]
    InvalidFormat(String),

    /// Data has exceeded retention period
    #[error("Data expired: retention period exceeded")]
    DataExpired,
}

/// Secure data wrapper that automatically zeros memory on drop
///
/// This ensures sensitive data is cleared from memory when no longer needed.
#[derive(Zeroize, ZeroizeOnDrop)]
pub struct SecureData {
    #[zeroize(skip)]
    created_at: SystemTime,
    data: Vec<u8>,
}

impl SecureData {
    /// Creates new secure data with current timestamp
    pub fn new(data: Vec<u8>) -> Self {
        Self {
            created_at: SystemTime::now(),
            data,
        }
    }

    /// Returns a reference to the data
    pub fn as_slice(&self) -> &[u8] {
        &self.data
    }

    /// Returns the creation timestamp
    pub fn created_at(&self) -> SystemTime {
        self.created_at
    }

    /// Checks if data has exceeded the retention period
    pub fn is_expired(&self, retention_period: Duration) -> bool {
        if let Ok(elapsed) = self.created_at.elapsed() {
            elapsed > retention_period
        } else {
            false
        }
    }
}

/// Data retention policy configuration
#[derive(Debug, Clone)]
pub struct DataRetentionPolicy {
    /// Time-to-live for encrypted data
    pub ttl: Duration,
    /// Whether to enable automatic cleanup
    pub auto_cleanup: bool,
}

impl Default for DataRetentionPolicy {
    fn default() -> Self {
        Self {
            ttl: Duration::from_secs(30 * 24 * 60 * 60), // 30 days
            auto_cleanup: false,
        }
    }
}

impl DataRetentionPolicy {
    /// Creates a new retention policy with the specified TTL
    pub fn new(ttl: Duration) -> Self {
        Self {
            ttl,
            auto_cleanup: true,
        }
    }

    /// Checks if data should be retained based on its age
    pub fn should_retain(&self, created_at: SystemTime) -> bool {
        if let Ok(elapsed) = created_at.elapsed() {
            elapsed <= self.ttl
        } else {
            true // Keep if we can't determine age
        }
    }
}

/// Encryption service for vision and document data
///
/// Uses ChaCha20-Poly1305 AEAD for authenticated encryption.
pub struct EncryptionService {
    cipher: ChaCha20Poly1305,
}

impl EncryptionService {
    /// Creates a new encryption service with a randomly generated key
    ///
    /// # Errors
    ///
    /// Returns `EncryptionError::KeyGenerationError` if key generation fails
    pub fn new() -> Result<Self, EncryptionError> {
        let mut key_bytes = [0u8; 32];
        OsRng.fill_bytes(&mut key_bytes);

        let cipher = ChaCha20Poly1305::new(&key_bytes.into());

        // Zeroize the key material
        key_bytes.zeroize();

        Ok(Self { cipher })
    }

    /// Creates an encryption service from an existing key
    ///
    /// # Arguments
    ///
    /// * `key` - 32-byte encryption key
    ///
    /// # Errors
    ///
    /// Returns error if key length is invalid
    pub fn from_key(key: &[u8]) -> Result<Self, EncryptionError> {
        if key.len() != 32 {
            return Err(EncryptionError::KeyGenerationError(
                "Key must be exactly 32 bytes".to_string(),
            ));
        }

        let cipher = ChaCha20Poly1305::new(key.into());

        Ok(Self { cipher })
    }

    /// Encrypts image data
    ///
    /// # Arguments
    ///
    /// * `data` - Raw image bytes to encrypt
    ///
    /// # Returns
    ///
    /// Encrypted data prepended with the nonce (12 bytes + ciphertext + 16-byte tag)
    ///
    /// # Errors
    ///
    /// Returns `EncryptionError::EncryptionFailed` if encryption fails
    pub fn encrypt_image_data(&self, data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        self.encrypt_data(data)
    }

    /// Decrypts image data
    ///
    /// # Arguments
    ///
    /// * `encrypted` - Encrypted data with prepended nonce
    ///
    /// # Returns
    ///
    /// Decrypted image data wrapped in `SecureData`
    ///
    /// # Errors
    ///
    /// Returns `EncryptionError::DecryptionFailed` if decryption fails or data is invalid
    pub fn decrypt_image_data(&self, encrypted: &[u8]) -> Result<SecureData, EncryptionError> {
        self.decrypt_data(encrypted)
    }

    /// Encrypts document data
    ///
    /// # Arguments
    ///
    /// * `data` - Raw document bytes to encrypt
    ///
    /// # Returns
    ///
    /// Encrypted data prepended with the nonce
    ///
    /// # Errors
    ///
    /// Returns `EncryptionError::EncryptionFailed` if encryption fails
    pub fn encrypt_document_data(&self, data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        self.encrypt_data(data)
    }

    /// Decrypts document data
    ///
    /// # Arguments
    ///
    /// * `encrypted` - Encrypted data with prepended nonce
    ///
    /// # Returns
    ///
    /// Decrypted document data wrapped in `SecureData`
    ///
    /// # Errors
    ///
    /// Returns `EncryptionError::DecryptionFailed` if decryption fails
    pub fn decrypt_document_data(&self, encrypted: &[u8]) -> Result<SecureData, EncryptionError> {
        self.decrypt_data(encrypted)
    }

    /// Internal encryption implementation
    fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>, EncryptionError> {
        // Generate random nonce (12 bytes for ChaCha20-Poly1305)
        let mut nonce_bytes = [0u8; 12];
        OsRng.fill_bytes(&mut nonce_bytes);
        let nonce = Nonce::from(nonce_bytes);

        // Encrypt the data
        let ciphertext = self
            .cipher
            .encrypt(&nonce, data)
            .map_err(|e| EncryptionError::EncryptionFailed(e.to_string()))?;

        // Prepend nonce to ciphertext
        let mut result = Vec::with_capacity(nonce_bytes.len() + ciphertext.len());
        result.extend_from_slice(&nonce_bytes);
        result.extend_from_slice(&ciphertext);

        Ok(result)
    }

    /// Internal decryption implementation
    fn decrypt_data(&self, encrypted: &[u8]) -> Result<SecureData, EncryptionError> {
        // Extract nonce (first 12 bytes)
        if encrypted.len() < 12 {
            return Err(EncryptionError::InvalidFormat(
                "Data too short to contain nonce".to_string(),
            ));
        }

        let (nonce_bytes, ciphertext) = encrypted.split_at(12);
        let nonce = Nonce::from_slice(nonce_bytes);

        // Decrypt the data
        let plaintext = self
            .cipher
            .decrypt(nonce, ciphertext)
            .map_err(|e| EncryptionError::DecryptionFailed(e.to_string()))?;

        Ok(SecureData::new(plaintext))
    }
}

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

    #[test]
    fn test_encryption_service_creation() {
        let service = EncryptionService::new();
        assert!(service.is_ok());
    }

    #[test]
    fn test_encryption_service_from_key() {
        let key = [0u8; 32];
        let service = EncryptionService::from_key(&key);
        assert!(service.is_ok());
    }

    #[test]
    fn test_encryption_service_from_invalid_key() {
        let key = [0u8; 16]; // Wrong size
        let service = EncryptionService::from_key(&key);
        assert!(matches!(
            service,
            Err(EncryptionError::KeyGenerationError(_))
        ));
    }

    #[test]
    fn test_encrypt_decrypt_image_data() {
        let service = EncryptionService::new().unwrap();
        let original = b"fake image data for testing";

        let encrypted = service.encrypt_image_data(original).unwrap();
        assert_ne!(encrypted.as_slice(), original);
        assert!(encrypted.len() > original.len()); // Includes nonce and tag

        let decrypted = service.decrypt_image_data(&encrypted).unwrap();
        assert_eq!(decrypted.as_slice(), original);
    }

    #[test]
    fn test_encrypt_decrypt_document_data() {
        let service = EncryptionService::new().unwrap();
        let original = b"fake PDF document content";

        let encrypted = service.encrypt_document_data(original).unwrap();
        assert_ne!(encrypted.as_slice(), original);

        let decrypted = service.decrypt_document_data(&encrypted).unwrap();
        assert_eq!(decrypted.as_slice(), original);
    }

    #[test]
    fn test_decrypt_invalid_data() {
        let service = EncryptionService::new().unwrap();
        let invalid_data = b"not encrypted data";

        let result = service.decrypt_image_data(invalid_data);
        assert!(matches!(result, Err(EncryptionError::DecryptionFailed(_))));
    }

    #[test]
    fn test_decrypt_data_too_short() {
        let service = EncryptionService::new().unwrap();
        let too_short = b"short";

        let result = service.decrypt_image_data(too_short);
        assert!(matches!(result, Err(EncryptionError::InvalidFormat(_))));
    }

    #[test]
    fn test_secure_data_zeroization() {
        let data = vec![1u8, 2, 3, 4, 5];
        let secure = SecureData::new(data.clone());

        assert_eq!(secure.as_slice(), data.as_slice());

        // SecureData will be dropped here and memory zeroized
        drop(secure);

        // We can't directly verify zeroization in safe Rust,
        // but the zeroize crate handles this automatically
    }

    #[test]
    fn test_secure_data_expiration() {
        let data = vec![1u8, 2, 3];
        let secure = SecureData::new(data);

        // Should not be expired with a long retention period
        let long_period = Duration::from_secs(3600);
        assert!(!secure.is_expired(long_period));

        // Should be expired with a zero retention period
        let zero_period = Duration::from_secs(0);
        std::thread::sleep(Duration::from_millis(10));
        assert!(secure.is_expired(zero_period));
    }

    #[test]
    fn test_data_retention_policy_default() {
        let policy = DataRetentionPolicy::default();
        assert_eq!(policy.ttl, Duration::from_secs(30 * 24 * 60 * 60));
        assert!(!policy.auto_cleanup);
    }

    #[test]
    fn test_data_retention_policy_custom() {
        let ttl = Duration::from_secs(3600);
        let policy = DataRetentionPolicy::new(ttl);
        assert_eq!(policy.ttl, ttl);
        assert!(policy.auto_cleanup);
    }

    #[test]
    fn test_retention_policy_should_retain() {
        let policy = DataRetentionPolicy::new(Duration::from_secs(60));
        let now = SystemTime::now();

        // Should retain recent data
        assert!(policy.should_retain(now));

        // Should not retain old data
        let old = now - Duration::from_secs(120);
        assert!(!policy.should_retain(old));
    }

    #[test]
    fn test_encryption_produces_different_ciphertexts() {
        let service = EncryptionService::new().unwrap();
        let data = b"same data";

        // Encrypt the same data twice
        let encrypted1 = service.encrypt_image_data(data).unwrap();
        let encrypted2 = service.encrypt_image_data(data).unwrap();

        // Should produce different ciphertexts (different nonces)
        assert_ne!(encrypted1, encrypted2);

        // But both should decrypt to the same plaintext
        let decrypted1 = service.decrypt_image_data(&encrypted1).unwrap();
        let decrypted2 = service.decrypt_image_data(&encrypted2).unwrap();
        assert_eq!(decrypted1.as_slice(), data);
        assert_eq!(decrypted2.as_slice(), data);
    }

    #[test]
    fn test_large_data_encryption() {
        let service = EncryptionService::new().unwrap();
        // Test with larger data (simulating a real image)
        let large_data = vec![42u8; 1024 * 100]; // 100KB

        let encrypted = service.encrypt_image_data(&large_data).unwrap();
        let decrypted = service.decrypt_image_data(&encrypted).unwrap();

        assert_eq!(decrypted.as_slice(), large_data.as_slice());
    }
}