Skip to main content

oxirs_cluster/
encryption.rs

1//! Encryption for cluster data with key rotation
2//!
3//! This module provides AES-256-GCM encryption with automatic key rotation
4//! and optional HSM (Hardware Security Module) integration for cloud providers.
5
6use crate::error::{ClusterError, Result};
7use oxicrypto_core::Aead;
8use scirs2_core::metrics::{Counter, Histogram};
9use scirs2_core::random::{Random, Rng};
10use serde::{Deserialize, Serialize};
11use std::sync::Arc;
12use std::time::{Duration, SystemTime};
13use tokio::sync::{Mutex, RwLock};
14
15/// Encryption manager with key rotation support
16pub struct EncryptionManager {
17    current_key: Arc<RwLock<EncryptionKey>>,
18    key_history: Arc<RwLock<Vec<EncryptionKey>>>,
19    config: EncryptionConfig,
20    key_rotator: Option<Arc<KeyRotator>>,
21    metrics: EncryptionMetrics,
22}
23
24/// Encryption key with metadata
25#[derive(Clone)]
26pub struct EncryptionKey {
27    /// Unique identifier for this key
28    pub key_id: KeyId,
29    /// The actual key material (wrapped in LessSafeKey)
30    key_material: Vec<u8>, // Store raw bytes for cloning
31    /// When this key was created
32    pub created_at: SystemTime,
33    /// When this key expires
34    pub expires_at: SystemTime,
35}
36
37impl EncryptionKey {
38    /// Return the 32-byte AES-256 key material after validating its length.
39    ///
40    /// The AEAD primitive ([`oxicrypto_aead::Aes256Gcm`]) is stateless and takes
41    /// the key as a per-call argument, so this simply validates and exposes the
42    /// raw bytes rather than constructing a bound key object.
43    fn key_bytes(&self) -> Result<&[u8]> {
44        if self.key_material.len() != 32 {
45            return Err(ClusterError::Encryption(
46                "Invalid AES-256 key length (expected 32 bytes)".to_string(),
47            ));
48        }
49        Ok(&self.key_material)
50    }
51}
52
53/// Configuration for encryption behavior
54#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct EncryptionConfig {
56    /// Number of days before key rotation
57    pub key_rotation_days: u64,
58    /// Enable HSM integration
59    pub hsm_enabled: bool,
60    /// HSM provider configuration
61    pub hsm_provider: Option<HsmProvider>,
62    /// Enable encryption validation
63    pub enable_validation: bool,
64    /// Require encryption for all data
65    pub require_encryption: bool,
66    /// Allowed encryption algorithms
67    pub allowed_algorithms: Vec<EncryptionAlgorithm>,
68}
69
70/// Supported encryption algorithms
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72pub enum EncryptionAlgorithm {
73    Aes256Gcm,
74    ChaCha20Poly1305,
75}
76
77impl Default for EncryptionConfig {
78    fn default() -> Self {
79        Self {
80            key_rotation_days: 90, // 90 days default
81            hsm_enabled: false,
82            hsm_provider: None,
83            enable_validation: true,
84            require_encryption: true,
85            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
86        }
87    }
88}
89
90/// Encryption validation result
91#[derive(Debug, Clone)]
92pub struct ValidationResult {
93    pub is_valid: bool,
94    pub errors: Vec<String>,
95    pub warnings: Vec<String>,
96}
97
98impl ValidationResult {
99    pub fn success() -> Self {
100        Self {
101            is_valid: true,
102            errors: Vec::new(),
103            warnings: Vec::new(),
104        }
105    }
106
107    pub fn failure(error: String) -> Self {
108        Self {
109            is_valid: false,
110            errors: vec![error],
111            warnings: Vec::new(),
112        }
113    }
114
115    pub fn add_error(&mut self, error: String) {
116        self.errors.push(error);
117        self.is_valid = false;
118    }
119
120    pub fn add_warning(&mut self, warning: String) {
121        self.warnings.push(warning);
122    }
123}
124
125/// Encryption operation metrics
126#[derive(Clone)]
127struct EncryptionMetrics {
128    encryption_operations: Arc<Counter>,
129    decryption_operations: Arc<Counter>,
130    encryption_time: Arc<Histogram>,
131    decryption_time: Arc<Histogram>,
132    encryption_size: Arc<Histogram>,
133    key_rotation_count: Arc<Counter>,
134    validation_failures: Arc<Counter>,
135}
136
137impl EncryptionMetrics {
138    fn new() -> Self {
139        Self {
140            encryption_operations: Arc::new(Counter::new(
141                "encryption_operations_total".to_string(),
142            )),
143            decryption_operations: Arc::new(Counter::new(
144                "decryption_operations_total".to_string(),
145            )),
146            encryption_time: Arc::new(Histogram::new(
147                "encryption_duration_microseconds".to_string(),
148            )),
149            decryption_time: Arc::new(Histogram::new(
150                "decryption_duration_microseconds".to_string(),
151            )),
152            encryption_size: Arc::new(Histogram::new("encryption_data_size_bytes".to_string())),
153            key_rotation_count: Arc::new(Counter::new("key_rotations_total".to_string())),
154            validation_failures: Arc::new(Counter::new(
155                "encryption_validation_failures".to_string(),
156            )),
157        }
158    }
159}
160
161/// Metrics snapshot
162#[derive(Debug, Clone)]
163pub struct EncryptionMetricsSnapshot {
164    pub encryption_operations: u64,
165    pub decryption_operations: u64,
166    pub avg_encryption_time_us: f64,
167    pub avg_decryption_time_us: f64,
168    pub avg_data_size_bytes: f64,
169    pub key_rotation_count: u64,
170    pub validation_failures: u64,
171}
172
173/// HSM provider configuration
174#[derive(Debug, Clone, Serialize, Deserialize)]
175pub enum HsmProvider {
176    /// AWS Key Management Service
177    AwsKms {
178        /// AWS region
179        region: String,
180        /// Key ARN
181        key_arn: String,
182    },
183    /// Azure Key Vault
184    AzureKeyVault {
185        /// Vault URL
186        vault_url: String,
187        /// Key name
188        key_name: String,
189    },
190    /// Google Cloud KMS
191    GcpKms {
192        /// GCP project ID
193        project: String,
194        /// Location (region)
195        location: String,
196        /// Key ring name
197        key_ring: String,
198        /// Key name
199        key_name: String,
200    },
201}
202
203/// Encrypted data container
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct EncryptedData {
206    /// Key ID used for encryption
207    pub key_id: KeyId,
208    /// Nonce (96-bit for AES-GCM)
209    pub nonce: [u8; 12],
210    /// Ciphertext with authentication tag
211    pub ciphertext: Vec<u8>,
212}
213
214/// Key identifier
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
216pub struct KeyId(u64);
217
218impl KeyId {
219    /// Generate a new unique key ID
220    pub fn new() -> Self {
221        use std::sync::atomic::{AtomicU64, Ordering};
222        static COUNTER: AtomicU64 = AtomicU64::new(1);
223        KeyId(COUNTER.fetch_add(1, Ordering::Relaxed))
224    }
225}
226
227impl Default for KeyId {
228    fn default() -> Self {
229        Self::new()
230    }
231}
232
233impl std::fmt::Display for KeyId {
234    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        write!(f, "key-{}", self.0)
236    }
237}
238
239/// Automatic key rotation manager
240pub struct KeyRotator {
241    manager: Arc<Mutex<EncryptionManager>>,
242    config: RotatorConfig,
243}
244
245/// Key rotator configuration
246#[derive(Debug, Clone)]
247pub struct RotatorConfig {
248    /// How often to check for key rotation (in hours)
249    pub check_interval_hours: u64,
250    /// Enable automatic key rotation
251    pub auto_rotate: bool,
252}
253
254impl Default for RotatorConfig {
255    fn default() -> Self {
256        Self {
257            check_interval_hours: 24, // Check daily
258            auto_rotate: true,
259        }
260    }
261}
262
263impl EncryptionManager {
264    /// Create a new encryption manager
265    pub fn new(config: EncryptionConfig) -> Result<Self> {
266        let key = Self::generate_key_internal(&config)?;
267
268        Ok(Self {
269            current_key: Arc::new(RwLock::new(key)),
270            key_history: Arc::new(RwLock::new(Vec::new())),
271            config,
272            key_rotator: None,
273            metrics: EncryptionMetrics::new(),
274        })
275    }
276
277    /// Validate encryption configuration at startup
278    pub fn validate_config(&self) -> ValidationResult {
279        let mut result = ValidationResult::success();
280
281        // Validate key rotation period
282        if self.config.key_rotation_days == 0 {
283            result.add_error("Key rotation days cannot be zero".to_string());
284        } else if self.config.key_rotation_days > 365 {
285            result.add_warning(format!(
286                "Key rotation period ({} days) exceeds recommended maximum (365 days)",
287                self.config.key_rotation_days
288            ));
289        }
290
291        // Validate HSM configuration
292        if self.config.hsm_enabled && self.config.hsm_provider.is_none() {
293            result.add_error("HSM enabled but no provider configured".to_string());
294        }
295
296        // Validate encryption algorithms
297        if self.config.allowed_algorithms.is_empty() {
298            result.add_error("No encryption algorithms configured".to_string());
299        }
300
301        // Validate current algorithm is in allowed list
302        if self.config.enable_validation {
303            let current_algo = EncryptionAlgorithm::Aes256Gcm; // Current implementation
304            if !self.config.allowed_algorithms.contains(&current_algo) {
305                result.add_error(format!(
306                    "Current algorithm {:?} not in allowed algorithms list",
307                    current_algo
308                ));
309            }
310        }
311
312        if !result.is_valid {
313            self.metrics.validation_failures.inc();
314        }
315
316        result
317    }
318
319    /// Validate that data can be encrypted/decrypted
320    pub async fn validate_encryption_roundtrip(&self) -> Result<ValidationResult> {
321        let test_data = b"encryption_validation_test_data";
322
323        match self.encrypt(test_data).await {
324            Ok(encrypted) => match self.decrypt(&encrypted).await {
325                Ok(decrypted) => {
326                    if decrypted == test_data {
327                        Ok(ValidationResult::success())
328                    } else {
329                        Ok(ValidationResult::failure(
330                            "Decrypted data does not match original".to_string(),
331                        ))
332                    }
333                }
334                Err(e) => Ok(ValidationResult::failure(format!(
335                    "Decryption failed: {}",
336                    e
337                ))),
338            },
339            Err(e) => Ok(ValidationResult::failure(format!(
340                "Encryption failed: {}",
341                e
342            ))),
343        }
344    }
345
346    /// Validate key is not expired
347    pub async fn validate_current_key(&self) -> ValidationResult {
348        let mut result = ValidationResult::success();
349        let key = self.current_key.read().await;
350
351        if SystemTime::now() > key.expires_at {
352            result.add_error("Current encryption key has expired".to_string());
353        } else {
354            let remaining = key
355                .expires_at
356                .duration_since(SystemTime::now())
357                .unwrap_or(Duration::from_secs(0));
358
359            if remaining < Duration::from_secs(7 * 86400) {
360                // 7 days
361                result.add_warning(format!(
362                    "Current encryption key expires in {} days",
363                    remaining.as_secs() / 86400
364                ));
365            }
366        }
367
368        result
369    }
370
371    /// Get encryption metrics
372    pub fn get_metrics(&self) -> EncryptionMetricsSnapshot {
373        EncryptionMetricsSnapshot {
374            encryption_operations: self.metrics.encryption_operations.get(),
375            decryption_operations: self.metrics.decryption_operations.get(),
376            avg_encryption_time_us: self.metrics.encryption_time.get_stats().mean,
377            avg_decryption_time_us: self.metrics.decryption_time.get_stats().mean,
378            avg_data_size_bytes: self.metrics.encryption_size.get_stats().mean,
379            key_rotation_count: self.metrics.key_rotation_count.get(),
380            validation_failures: self.metrics.validation_failures.get(),
381        }
382    }
383
384    /// Create a new encryption manager with automatic key rotation
385    pub fn with_auto_rotation(
386        config: EncryptionConfig,
387        rotator_config: RotatorConfig,
388    ) -> Result<Arc<Mutex<Self>>> {
389        let manager = Arc::new(Mutex::new(Self::new(config)?));
390
391        if rotator_config.auto_rotate {
392            let rotator = Arc::new(KeyRotator {
393                manager: Arc::clone(&manager),
394                config: rotator_config,
395            });
396
397            // Start rotation background task
398            rotator.start();
399
400            // Store rotator reference
401            let manager_clone = Arc::clone(&manager);
402            tokio::spawn(async move {
403                let mut mgr = manager_clone.lock().await;
404                mgr.key_rotator = Some(rotator);
405            });
406        }
407
408        Ok(manager)
409    }
410
411    /// Encrypt data with AES-256-GCM
412    pub async fn encrypt(&self, plaintext: &[u8]) -> Result<EncryptedData> {
413        let start = std::time::Instant::now();
414
415        // Record encryption operation
416        self.metrics.encryption_operations.inc();
417
418        let key = self.current_key.read().await;
419
420        // Generate nonce (96-bit) using atomic counter + timestamp for guaranteed uniqueness.
421        // AES-GCM security requires nonces to NEVER repeat under the same key.
422        // A pure timestamp seed can collide when encryptions happen within the same nanosecond.
423        use std::sync::atomic::{AtomicU64, Ordering};
424        static NONCE_COUNTER: AtomicU64 = AtomicU64::new(0);
425
426        let counter = NONCE_COUNTER.fetch_add(1, Ordering::Relaxed);
427        let timestamp = std::time::SystemTime::now()
428            .duration_since(std::time::UNIX_EPOCH)
429            .map_or(0, |d| d.as_nanos() as u64);
430
431        let mut nonce_bytes = [0u8; 12];
432        // First 8 bytes: XOR of counter and timestamp (counter ensures uniqueness,
433        // timestamp adds entropy across process restarts)
434        let unique_val = counter ^ timestamp;
435        nonce_bytes[..8].copy_from_slice(&unique_val.to_le_bytes());
436        // Last 4 bytes: counter low bits (guarantees uniqueness even if XOR collides)
437        nonce_bytes[8..12].copy_from_slice(&(counter as u32).to_le_bytes());
438
439        // Get the key material
440        let key_bytes = key.key_bytes()?;
441
442        // Encrypt with AES-256-GCM (no AAD). The returned vector is
443        // `ciphertext || tag`, preserving the original on-the-wire layout where
444        // the 16-byte GCM tag is appended to the ciphertext.
445        let ciphertext = oxicrypto_aead::Aes256Gcm
446            .seal_to_vec(key_bytes, &nonce_bytes, &[], plaintext)
447            .map_err(|e| ClusterError::Encryption(format!("Encryption failed: {e}")))?;
448
449        // Record metrics
450        let elapsed = start.elapsed();
451        self.metrics
452            .encryption_time
453            .observe(elapsed.as_micros() as f64);
454        self.metrics.encryption_size.observe(plaintext.len() as f64);
455
456        Ok(EncryptedData {
457            key_id: key.key_id,
458            nonce: nonce_bytes,
459            ciphertext,
460        })
461    }
462
463    /// Decrypt data
464    pub async fn decrypt(&self, encrypted: &EncryptedData) -> Result<Vec<u8>> {
465        let start = std::time::Instant::now();
466
467        // Record decryption operation
468        self.metrics.decryption_operations.inc();
469
470        // Find the correct key (current or historical)
471        let key = self.find_key(encrypted.key_id).await?;
472
473        // Get the key material
474        let key_bytes = key.key_bytes()?;
475
476        // Decrypt and authenticate. The payload is `ciphertext || tag`; the AEAD
477        // primitive verifies the tag and returns the plaintext (tag stripped).
478        let plaintext = oxicrypto_aead::Aes256Gcm
479            .open_to_vec(key_bytes, &encrypted.nonce, &[], &encrypted.ciphertext)
480            .map_err(|e| ClusterError::Encryption(format!("Decryption failed: {e}")))?;
481
482        // Record metrics
483        let elapsed = start.elapsed();
484        self.metrics
485            .decryption_time
486            .observe(elapsed.as_micros() as f64);
487
488        Ok(plaintext)
489    }
490
491    /// Rotate encryption key
492    pub async fn rotate_key(&mut self) -> Result<()> {
493        // Generate new key
494        let new_key = if self.config.hsm_enabled {
495            self.generate_key_from_hsm().await?
496        } else {
497            Self::generate_key_internal(&self.config)?
498        };
499
500        // Move current to history
501        let old_key = self.current_key.read().await.clone();
502        self.key_history.write().await.push(old_key);
503
504        // Set new key as current
505        *self.current_key.write().await = new_key;
506
507        // Record key rotation metric
508        self.metrics.key_rotation_count.inc();
509
510        Ok(())
511    }
512
513    /// Check if key rotation is needed
514    pub async fn should_rotate_key(&self) -> bool {
515        let key = self.current_key.read().await;
516        match SystemTime::now().duration_since(key.created_at) {
517            Ok(age) => age >= Duration::from_secs(self.config.key_rotation_days * 86400),
518            Err(_) => true, // If we can't determine age, rotate to be safe
519        }
520    }
521
522    /// Find key by ID (current or historical)
523    async fn find_key(&self, key_id: KeyId) -> Result<EncryptionKey> {
524        // Check current key first
525        let current = self.current_key.read().await;
526        if current.key_id == key_id {
527            return Ok(current.clone());
528        }
529
530        // Check history
531        let history = self.key_history.read().await;
532        for key in history.iter() {
533            if key.key_id == key_id {
534                return Ok(key.clone());
535            }
536        }
537
538        Err(ClusterError::Encryption(format!(
539            "Key not found: {}",
540            key_id
541        )))
542    }
543
544    /// Generate key locally (not from HSM)
545    fn generate_key_internal(config: &EncryptionConfig) -> Result<EncryptionKey> {
546        let mut key_bytes = [0u8; 32]; // 256 bits
547                                       // Use SystemTime with nanosecond precision for better randomness
548        let seed = std::time::SystemTime::now()
549            .duration_since(std::time::UNIX_EPOCH)
550            .map_or(0, |d| d.as_nanos() as u64);
551        let mut rng = Random::seed(seed);
552        rng.fill_bytes(&mut key_bytes);
553
554        // AES-256 requires a 32-byte key; `key_bytes` is sized [u8; 32] so this
555        // is statically guaranteed, but assert it explicitly for safety.
556        debug_assert_eq!(key_bytes.len(), 32);
557
558        let now = SystemTime::now();
559        Ok(EncryptionKey {
560            key_id: KeyId::new(),
561            key_material: key_bytes.to_vec(),
562            created_at: now,
563            expires_at: now + Duration::from_secs(config.key_rotation_days * 86400),
564        })
565    }
566
567    /// Generate key from HSM (placeholder for cloud integration)
568    async fn generate_key_from_hsm(&self) -> Result<EncryptionKey> {
569        match &self.config.hsm_provider {
570            Some(HsmProvider::AwsKms { region, key_arn }) => {
571                // Placeholder for AWS KMS integration
572                // In production, this would use aws-sdk-kms to generate a data key
573                tracing::warn!(
574                    "AWS KMS integration not fully implemented. Using local key generation. Region: {}, ARN: {}",
575                    region,
576                    key_arn
577                );
578                Self::generate_key_internal(&self.config)
579            }
580            Some(HsmProvider::AzureKeyVault {
581                vault_url,
582                key_name,
583            }) => {
584                // Placeholder for Azure Key Vault integration
585                tracing::warn!(
586                    "Azure Key Vault integration not fully implemented. Using local key generation. Vault: {}, Key: {}",
587                    vault_url,
588                    key_name
589                );
590                Self::generate_key_internal(&self.config)
591            }
592            Some(HsmProvider::GcpKms {
593                project,
594                location,
595                key_ring,
596                key_name,
597            }) => {
598                // Placeholder for GCP KMS integration
599                tracing::warn!(
600                    "GCP KMS integration not fully implemented. Using local key generation. Project: {}, Location: {}, KeyRing: {}, Key: {}",
601                    project,
602                    location,
603                    key_ring,
604                    key_name
605                );
606                Self::generate_key_internal(&self.config)
607            }
608            None => Err(ClusterError::Encryption("HSM not configured".to_string())),
609        }
610    }
611
612    /// Get current key ID
613    pub async fn current_key_id(&self) -> KeyId {
614        self.current_key.read().await.key_id
615    }
616
617    /// Get number of historical keys
618    pub async fn historical_key_count(&self) -> usize {
619        self.key_history.read().await.len()
620    }
621
622    /// Get configuration
623    pub fn config(&self) -> &EncryptionConfig {
624        &self.config
625    }
626}
627
628impl KeyRotator {
629    /// Start automatic key rotation background task
630    pub fn start(self: &Arc<Self>) {
631        let rotator = Arc::clone(self);
632
633        tokio::spawn(async move {
634            let interval = Duration::from_secs(rotator.config.check_interval_hours * 3600);
635
636            loop {
637                tokio::time::sleep(interval).await;
638
639                if !rotator.config.auto_rotate {
640                    continue;
641                }
642
643                match rotator.manager.lock().await.should_rotate_key().await {
644                    true => match rotator.manager.lock().await.rotate_key().await {
645                        Ok(()) => {
646                            tracing::info!("Encryption key rotated successfully");
647                        }
648                        Err(e) => {
649                            tracing::error!("Key rotation failed: {}", e);
650                        }
651                    },
652                    false => {
653                        tracing::debug!("Key rotation not needed yet");
654                    }
655                }
656            }
657        });
658    }
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664
665    #[tokio::test]
666    async fn test_encryption_manager_creation() {
667        let config = EncryptionConfig::default();
668        let manager = EncryptionManager::new(config);
669        assert!(manager.is_ok());
670    }
671
672    #[tokio::test]
673    async fn test_encrypt_decrypt_round_trip() {
674        let config = EncryptionConfig::default();
675        let manager = EncryptionManager::new(config).expect("Failed to create manager");
676
677        let plaintext = b"Hello, world! This is a secret message.";
678        let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
679
680        assert_ne!(encrypted.ciphertext, plaintext);
681        assert_eq!(encrypted.nonce.len(), 12);
682
683        let decrypted = manager
684            .decrypt(&encrypted)
685            .await
686            .expect("Decryption failed");
687        assert_eq!(decrypted, plaintext);
688    }
689
690    #[tokio::test]
691    async fn test_encrypt_decrypt_wire_layout_round_trip() {
692        // Verifies the on-the-wire layout after the oxicrypto migration:
693        // `ciphertext` holds `actual_ciphertext || 16-byte GCM tag`, and the
694        // 12-byte nonce is carried separately. An encrypt->decrypt cycle must
695        // recover the exact plaintext.
696        let config = EncryptionConfig::default();
697        let manager = EncryptionManager::new(config).expect("Failed to create manager");
698
699        let plaintext = b"oxicrypto AES-256-GCM round-trip payload";
700        let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
701
702        // Nonce is exactly 96 bits.
703        assert_eq!(encrypted.nonce.len(), 12);
704        // Ciphertext length == plaintext length + 16-byte AEAD tag.
705        assert_eq!(encrypted.ciphertext.len(), plaintext.len() + 16);
706        // Ciphertext differs from plaintext.
707        assert_ne!(&encrypted.ciphertext[..plaintext.len()], &plaintext[..]);
708
709        let decrypted = manager
710            .decrypt(&encrypted)
711            .await
712            .expect("Decryption failed");
713        assert_eq!(decrypted, plaintext);
714    }
715
716    #[tokio::test]
717    async fn test_key_rotation() {
718        let config = EncryptionConfig {
719            key_rotation_days: 90,
720            hsm_enabled: false,
721            hsm_provider: None,
722            enable_validation: true,
723            require_encryption: true,
724            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
725        };
726        let mut manager = EncryptionManager::new(config).expect("Failed to create manager");
727
728        let original_key_id = manager.current_key_id().await;
729
730        // Encrypt with original key
731        let plaintext = b"Test data before rotation";
732        let encrypted_before = manager.encrypt(plaintext).await.expect("Encryption failed");
733        assert_eq!(encrypted_before.key_id, original_key_id);
734
735        // Rotate key
736        manager.rotate_key().await.expect("Key rotation failed");
737
738        let new_key_id = manager.current_key_id().await;
739        assert_ne!(original_key_id, new_key_id);
740
741        // Verify we can still decrypt old data
742        let decrypted_old = manager
743            .decrypt(&encrypted_before)
744            .await
745            .expect("Decryption failed");
746        assert_eq!(decrypted_old, plaintext);
747
748        // Encrypt with new key
749        let encrypted_after = manager.encrypt(plaintext).await.expect("Encryption failed");
750        assert_eq!(encrypted_after.key_id, new_key_id);
751        assert_ne!(encrypted_after.ciphertext, encrypted_before.ciphertext);
752
753        // Verify historical keys
754        assert_eq!(manager.historical_key_count().await, 1);
755    }
756
757    #[tokio::test]
758    async fn test_multiple_rotations() {
759        let config = EncryptionConfig::default();
760        let mut manager = EncryptionManager::new(config).expect("Failed to create manager");
761
762        let plaintext = b"Test data";
763        let mut encrypted_versions = Vec::new();
764
765        // Encrypt and rotate 5 times
766        for i in 0..5 {
767            let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
768            encrypted_versions.push((i, encrypted));
769
770            if i < 4 {
771                manager.rotate_key().await.expect("Key rotation failed");
772            }
773        }
774
775        // Verify we can decrypt all versions
776        for (i, encrypted) in encrypted_versions {
777            let decrypted = manager
778                .decrypt(&encrypted)
779                .await
780                .unwrap_or_else(|_| panic!("Decryption failed for version {}", i));
781            assert_eq!(decrypted, plaintext);
782        }
783
784        // Should have 4 historical keys (original + 3 rotations)
785        assert_eq!(manager.historical_key_count().await, 4);
786    }
787
788    #[tokio::test]
789    async fn test_key_not_found() {
790        let config = EncryptionConfig::default();
791        let manager = EncryptionManager::new(config).expect("Failed to create manager");
792
793        let fake_encrypted = EncryptedData {
794            key_id: KeyId(99999),
795            nonce: [0u8; 12],
796            ciphertext: vec![0u8; 32],
797        };
798
799        let result = manager.decrypt(&fake_encrypted).await;
800        assert!(result.is_err());
801        assert!(result.unwrap_err().to_string().contains("Key not found"));
802    }
803
804    #[tokio::test]
805    async fn test_encryption_different_nonces() {
806        let config = EncryptionConfig::default();
807        let manager = EncryptionManager::new(config).expect("Failed to create manager");
808
809        let plaintext = b"Same data";
810        let encrypted1 = manager.encrypt(plaintext).await.expect("Encryption failed");
811        let encrypted2 = manager.encrypt(plaintext).await.expect("Encryption failed");
812
813        // Same plaintext with different nonces should produce different ciphertexts
814        assert_ne!(encrypted1.nonce, encrypted2.nonce);
815        assert_ne!(encrypted1.ciphertext, encrypted2.ciphertext);
816
817        // Both should decrypt correctly
818        let decrypted1 = manager
819            .decrypt(&encrypted1)
820            .await
821            .expect("Decryption failed");
822        let decrypted2 = manager
823            .decrypt(&encrypted2)
824            .await
825            .expect("Decryption failed");
826        assert_eq!(decrypted1, plaintext);
827        assert_eq!(decrypted2, plaintext);
828    }
829
830    #[test]
831    fn test_key_id_generation() {
832        let id1 = KeyId::new();
833        let id2 = KeyId::new();
834        assert_ne!(id1, id2);
835        assert!(id1.0 < id2.0);
836    }
837
838    #[test]
839    fn test_key_id_display() {
840        let id = KeyId(42);
841        assert_eq!(format!("{}", id), "key-42");
842    }
843
844    #[tokio::test]
845    async fn test_hsm_config_fallback() {
846        let config = EncryptionConfig {
847            key_rotation_days: 90,
848            hsm_enabled: true,
849            hsm_provider: Some(HsmProvider::AwsKms {
850                region: "us-west-2".to_string(),
851                key_arn: "arn:aws:kms:us-west-2:123456789012:key/test".to_string(),
852            }),
853            enable_validation: true,
854            require_encryption: true,
855            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
856        };
857
858        let mut manager = EncryptionManager::new(config).expect("Failed to create manager");
859
860        // Should fall back to local key generation
861        manager.rotate_key().await.expect("Key rotation failed");
862
863        // Verify encryption still works
864        let plaintext = b"Test with HSM fallback";
865        let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
866        let decrypted = manager
867            .decrypt(&encrypted)
868            .await
869            .expect("Decryption failed");
870        assert_eq!(decrypted, plaintext);
871    }
872
873    // ======================================================================
874    // COMPREHENSIVE VALIDATION TESTS
875    // ======================================================================
876
877    #[tokio::test]
878    async fn test_validation_config_zero_rotation_days() {
879        let config = EncryptionConfig {
880            key_rotation_days: 0,
881            hsm_enabled: false,
882            hsm_provider: None,
883            enable_validation: true,
884            require_encryption: true,
885            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
886        };
887
888        let manager = EncryptionManager::new(config).expect("Failed to create manager");
889        let result = manager.validate_config();
890
891        assert!(!result.is_valid);
892        assert!(result
893            .errors
894            .iter()
895            .any(|e| e.contains("rotation days cannot be zero")));
896    }
897
898    #[tokio::test]
899    async fn test_validation_config_excessive_rotation_period() {
900        let config = EncryptionConfig {
901            key_rotation_days: 400,
902            hsm_enabled: false,
903            hsm_provider: None,
904            enable_validation: true,
905            require_encryption: true,
906            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
907        };
908
909        let manager = EncryptionManager::new(config).expect("Failed to create manager");
910        let result = manager.validate_config();
911
912        assert!(result.is_valid); // Valid but with warning
913        assert!(!result.warnings.is_empty());
914        assert!(result
915            .warnings
916            .iter()
917            .any(|w| w.contains("exceeds recommended maximum")));
918    }
919
920    #[tokio::test]
921    async fn test_validation_config_hsm_enabled_no_provider() {
922        let config = EncryptionConfig {
923            key_rotation_days: 90,
924            hsm_enabled: true,
925            hsm_provider: None,
926            enable_validation: true,
927            require_encryption: true,
928            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
929        };
930
931        let manager = EncryptionManager::new(config).expect("Failed to create manager");
932        let result = manager.validate_config();
933
934        assert!(!result.is_valid);
935        assert!(result
936            .errors
937            .iter()
938            .any(|e| e.contains("HSM enabled but no provider")));
939    }
940
941    #[tokio::test]
942    async fn test_validation_config_no_algorithms() {
943        let config = EncryptionConfig {
944            key_rotation_days: 90,
945            hsm_enabled: false,
946            hsm_provider: None,
947            enable_validation: true,
948            require_encryption: true,
949            allowed_algorithms: vec![],
950        };
951
952        let manager = EncryptionManager::new(config).expect("Failed to create manager");
953        let result = manager.validate_config();
954
955        assert!(!result.is_valid);
956        assert!(result
957            .errors
958            .iter()
959            .any(|e| e.contains("No encryption algorithms")));
960    }
961
962    #[tokio::test]
963    async fn test_validation_encryption_roundtrip() {
964        let config = EncryptionConfig::default();
965        let manager = EncryptionManager::new(config).expect("Failed to create manager");
966
967        let result = manager
968            .validate_encryption_roundtrip()
969            .await
970            .expect("Validation failed");
971
972        assert!(result.is_valid);
973        assert!(result.errors.is_empty());
974    }
975
976    #[tokio::test]
977    async fn test_validation_current_key_not_expired() {
978        let config = EncryptionConfig::default();
979        let manager = EncryptionManager::new(config).expect("Failed to create manager");
980
981        let result = manager.validate_current_key().await;
982
983        assert!(result.is_valid);
984        assert!(result.errors.is_empty());
985    }
986
987    #[tokio::test]
988    async fn test_validation_result_add_error() {
989        let mut result = ValidationResult::success();
990        assert!(result.is_valid);
991
992        result.add_error("Test error".to_string());
993
994        assert!(!result.is_valid);
995        assert_eq!(result.errors.len(), 1);
996        assert_eq!(result.errors[0], "Test error");
997    }
998
999    #[tokio::test]
1000    async fn test_validation_result_add_warning() {
1001        let mut result = ValidationResult::success();
1002        assert!(result.is_valid);
1003
1004        result.add_warning("Test warning".to_string());
1005
1006        assert!(result.is_valid); // Warnings don't affect validity
1007        assert_eq!(result.warnings.len(), 1);
1008        assert_eq!(result.warnings[0], "Test warning");
1009    }
1010
1011    #[tokio::test]
1012    async fn test_validation_result_failure() {
1013        let result = ValidationResult::failure("Critical error".to_string());
1014
1015        assert!(!result.is_valid);
1016        assert_eq!(result.errors.len(), 1);
1017        assert_eq!(result.errors[0], "Critical error");
1018    }
1019
1020    #[tokio::test]
1021    async fn test_metrics_collection() {
1022        let config = EncryptionConfig::default();
1023        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1024
1025        let plaintext = b"Test data for metrics";
1026
1027        // Perform multiple operations
1028        for _ in 0..5 {
1029            let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
1030            manager
1031                .decrypt(&encrypted)
1032                .await
1033                .expect("Decryption failed");
1034        }
1035
1036        let metrics = manager.get_metrics();
1037
1038        assert_eq!(metrics.encryption_operations, 5);
1039        assert_eq!(metrics.decryption_operations, 5);
1040        assert!(metrics.avg_encryption_time_us >= 0.0);
1041        assert!(metrics.avg_decryption_time_us >= 0.0);
1042        assert!(metrics.avg_data_size_bytes > 0.0);
1043    }
1044
1045    #[tokio::test]
1046    async fn test_metrics_key_rotation_count() {
1047        let config = EncryptionConfig::default();
1048        let mut manager = EncryptionManager::new(config).expect("Failed to create manager");
1049
1050        let initial_metrics = manager.get_metrics();
1051        assert_eq!(initial_metrics.key_rotation_count, 0);
1052
1053        // Rotate key twice
1054        manager.rotate_key().await.expect("Key rotation failed");
1055        manager.rotate_key().await.expect("Key rotation failed");
1056
1057        let final_metrics = manager.get_metrics();
1058        assert_eq!(final_metrics.key_rotation_count, 2);
1059    }
1060
1061    #[tokio::test]
1062    async fn test_nonce_uniqueness() {
1063        let config = EncryptionConfig::default();
1064        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1065
1066        let plaintext = b"Test data";
1067        let mut nonces = std::collections::HashSet::new();
1068
1069        // Generate 100 encrypted messages and ensure all nonces are unique
1070        for _ in 0..100 {
1071            let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
1072            assert!(nonces.insert(encrypted.nonce), "Duplicate nonce detected!");
1073        }
1074
1075        assert_eq!(nonces.len(), 100);
1076    }
1077
1078    #[tokio::test]
1079    async fn test_empty_plaintext_encryption() {
1080        let config = EncryptionConfig::default();
1081        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1082
1083        let plaintext = b"";
1084        let encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
1085
1086        // Even empty plaintext should produce ciphertext with auth tag
1087        assert!(!encrypted.ciphertext.is_empty());
1088
1089        let decrypted = manager
1090            .decrypt(&encrypted)
1091            .await
1092            .expect("Decryption failed");
1093        assert_eq!(decrypted, plaintext);
1094    }
1095
1096    #[tokio::test]
1097    async fn test_large_plaintext_encryption() {
1098        let config = EncryptionConfig::default();
1099        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1100
1101        // Create 1MB of data
1102        let plaintext = vec![0xAB; 1024 * 1024];
1103        let encrypted = manager
1104            .encrypt(&plaintext)
1105            .await
1106            .expect("Encryption failed");
1107
1108        let decrypted = manager
1109            .decrypt(&encrypted)
1110            .await
1111            .expect("Decryption failed");
1112        assert_eq!(decrypted, plaintext);
1113
1114        // Verify metrics recorded the size
1115        let metrics = manager.get_metrics();
1116        assert!(metrics.avg_data_size_bytes > 1000000.0);
1117    }
1118
1119    #[tokio::test]
1120    async fn test_tampered_ciphertext_detection() {
1121        let config = EncryptionConfig::default();
1122        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1123
1124        let plaintext = b"Secret data";
1125        let mut encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
1126
1127        // Tamper with the ciphertext
1128        if let Some(byte) = encrypted.ciphertext.first_mut() {
1129            *byte ^= 0xFF;
1130        }
1131
1132        // Decryption should fail due to authentication failure
1133        let result = manager.decrypt(&encrypted).await;
1134        assert!(result.is_err());
1135        assert!(result
1136            .unwrap_err()
1137            .to_string()
1138            .contains("Decryption failed"));
1139    }
1140
1141    #[tokio::test]
1142    async fn test_tampered_nonce_detection() {
1143        let config = EncryptionConfig::default();
1144        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1145
1146        let plaintext = b"Secret data";
1147        let mut encrypted = manager.encrypt(plaintext).await.expect("Encryption failed");
1148
1149        // Tamper with the nonce
1150        encrypted.nonce[0] ^= 0xFF;
1151
1152        // Decryption should fail due to authentication failure
1153        let result = manager.decrypt(&encrypted).await;
1154        assert!(result.is_err());
1155    }
1156
1157    #[tokio::test]
1158    async fn test_key_expiration_warning() {
1159        let config = EncryptionConfig {
1160            key_rotation_days: 1, // 1 day for fast expiration testing
1161            hsm_enabled: false,
1162            hsm_provider: None,
1163            enable_validation: true,
1164            require_encryption: true,
1165            allowed_algorithms: vec![EncryptionAlgorithm::Aes256Gcm],
1166        };
1167
1168        let manager = EncryptionManager::new(config).expect("Failed to create manager");
1169
1170        // Key should not be expired yet
1171        let result = manager.validate_current_key().await;
1172        assert!(result.is_valid);
1173    }
1174
1175    #[test]
1176    fn test_encryption_config_default() {
1177        let config = EncryptionConfig::default();
1178
1179        assert_eq!(config.key_rotation_days, 90);
1180        assert!(!config.hsm_enabled);
1181        assert!(config.hsm_provider.is_none());
1182        assert!(config.enable_validation);
1183        assert!(config.require_encryption);
1184        assert_eq!(config.allowed_algorithms.len(), 1);
1185        assert_eq!(config.allowed_algorithms[0], EncryptionAlgorithm::Aes256Gcm);
1186    }
1187
1188    #[test]
1189    fn test_key_id_uniqueness() {
1190        let mut ids = std::collections::HashSet::new();
1191
1192        for _ in 0..1000 {
1193            let id = KeyId::new();
1194            assert!(ids.insert(id), "Duplicate KeyId generated!");
1195        }
1196
1197        assert_eq!(ids.len(), 1000);
1198    }
1199
1200    #[tokio::test]
1201    async fn test_concurrent_encryption() {
1202        let config = EncryptionConfig::default();
1203        let manager =
1204            std::sync::Arc::new(EncryptionManager::new(config).expect("Failed to create manager"));
1205
1206        let mut handles = vec![];
1207
1208        // Spawn 10 concurrent encryption tasks
1209        for i in 0..10 {
1210            let manager_clone = std::sync::Arc::clone(&manager);
1211            let handle = tokio::spawn(async move {
1212                let plaintext = format!("Test data {}", i);
1213                let encrypted = manager_clone
1214                    .encrypt(plaintext.as_bytes())
1215                    .await
1216                    .expect("Encryption failed");
1217                let decrypted = manager_clone
1218                    .decrypt(&encrypted)
1219                    .await
1220                    .expect("Decryption failed");
1221                assert_eq!(decrypted, plaintext.as_bytes());
1222            });
1223            handles.push(handle);
1224        }
1225
1226        // Wait for all tasks to complete
1227        for handle in handles {
1228            handle.await.expect("Task panicked");
1229        }
1230
1231        let metrics = manager.get_metrics();
1232        assert_eq!(metrics.encryption_operations, 10);
1233        assert_eq!(metrics.decryption_operations, 10);
1234    }
1235}