Skip to main content

AirLibrary/Security/
mod.rs

1//! # Security Module
2//!
3//! Comprehensive security features for Air including:
4//! - Rate limiting with token bucket algorithm (per-IP and per-client)
5//! - Checksum verification for file integrity
6//! - Secure credential storage with encryption
7//! - Timing attack protection for sensitive operations
8//! - Secure memory handling with zeroization
9//! - Key rotation and management
10//! - Security event auditing and logging
11//!
12//! ## VSCode Security References
13//!
14//! This security module aligns with VSCode's security patterns:
15//! - Rate limiting similar to VSCode's API rate limiting
16//! - Secure credential storage matching VSCode's secret storage
17//! - File integrity verification similar to VSCode's extension verification
18//! - Security audit logging inspired by VSCode's telemetry security events
19//!
20//! ## Security Model for External Connections
21//!
22//! The security module implements a defense-in-depth approach for external
23//! connections:
24//!
25//! ### Network Security
26//! - Rate limiting prevents abuse and DoS attacks
27//! - IP-based rate limiting limits impact per client
28//! - Client-based rate limiting limits impact per authenticated client
29//! - Connection pooling limits total concurrent connections
30//!
31//! ### Authentication Security
32//! - Secure credential storage with AES-GCM encryption
33//! - PBKDF2 key derivation with high iteration count
34//! - Timing attack protection for password comparisons
35//! - Secure token generation and validation
36//!
37//! ### Data Security
38//! - SHA-256 checksum verification for file integrity
39//! - AES-GCM encryption for credential storage
40//! - Key wrapping for master key protection
41//! - Secure memory handling with zeroization
42//!
43//! ### Audit and Monitoring
44//! - Comprehensive security event logging
45//! - Failed authentication attempts tracking
46//! - Rate limit violation logging
47//! - Security metric collection for Mountain integration
48//!
49//! ## Mountain Settings Integration
50//!
51//! Security policies are integrated with Mountain settings:
52//! - Rate limit thresholds configurable via Mountain settings
53//! - Security event thresholds configurable via Mountain settings
54//! - Alert notification channels configured via Mountain
55//! - Security metric retention configured via Mountain
56//!
57//! ## FUTURE Enhancements
58//!
59//! - Implement HSM (Hardware Security Module) integration for key storage
60//! - Add support for hardware-backed key generation and storage
61//! - Implement certificate pinning for external API connections
62//! - Add support for TLS 1.3 with perfect forward secrecy
63//! - Implement security policy enforcement and validation
64//! - Add support for multi-factor authentication
65//! - Implement security compliance reporting (SOC2, PCI-DSS, etc.)
66//! - Add real-time security threat detection and response
67//! - Implement secure communication channels with VSCode extensions
68//! - Add support for encrypted data at rest with multiple keys
69//! ## Timing Attack Protection
70//!
71//! The module implements constant-time operations for sensitive comparisons:
72//! - Password comparisons use constant-time algorithms
73//! - Token comparisons are timing-attack resistant
74//! - Hash comparisons use fixed-time comparison functions
75//! - Authentication response timing is normalized
76//!
77//! ## Secure Memory Handling
78//!
79//! Sensitive data in memory is protected through:
80//! - Zeroization on drop for secure data structures
81//! - Memory encryption for sensitive buffers
82//! - Stack canaries for overflow detection
83//! - Memory locking to prevent swapping
84//!
85//! ## Key Rotation
86//!
87//! Key rotation is supported through:
88//! - Automatic key rotation hooks for periodic key updates
89//! - Key versioning for backward compatibility
90//! - Secure key storage with key wrapping
91//! - Key rotation event logging and auditing
92//!
93//! ## Security Event Auditing
94//!
95//! All security events are logged for auditing:
96//! - Authentication attempts (success and failure)
97//! - Rate limit violations
98//! - Key rotations
99//! - Security configuration changes
100//! - Access control violations
101//!
102//! Security events are forwarded to Mountain for correlation and alerting.
103
104use std::{collections::HashMap, sync::Arc};
105
106use tokio::sync::RwLock;
107use serde::{Deserialize, Serialize};
108use sha2::{Digest, Sha256};
109use ring::pbkdf2;
110use rand::{Rng, rng};
111use base64::{Engine, engine::general_purpose::STANDARD};
112use zeroize::Zeroize;
113use subtle::ConstantTimeEq;
114
115use crate::{AirError, Result, dev_log};
116
117/// Secure byte array that zeroizes memory on drop
118#[derive(Clone, Deserialize, Serialize)]
119pub struct SecureBytes {
120	/// The underlying bytes
121	Data:Vec<u8>,
122}
123
124impl SecureBytes {
125	/// Create a new secure byte array
126	pub fn new(Data:Vec<u8>) -> Self { Self { Data } }
127
128	/// Create from a string
129	pub fn from_str(S:&str) -> Self { Self { Data:S.as_bytes().to_vec() } }
130
131	/// Get the data as a slice (constant-time)
132	pub fn as_slice(&self) -> &[u8] { &self.Data }
133
134	/// Get the length
135	pub fn len(&self) -> usize { self.Data.len() }
136
137	/// Check if empty
138	pub fn is_empty(&self) -> bool { self.Data.is_empty() }
139
140	/// Constant-time comparison
141	pub fn ct_eq(&self, Other:&Self) -> bool { self.Data.ct_eq(&Other.Data).into() }
142}
143
144impl Drop for SecureBytes {
145	fn drop(&mut self) { self.Data.zeroize(); }
146}
147
148/// Security event audit log
149#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct SecurityEvent {
151	/// Event timestamp
152	pub Timestamp:u64,
153
154	/// Event type
155	pub EventType:SecurityEventType,
156
157	/// Event severity
158	pub Severity:SecuritySeverity,
159
160	/// Source IP address (if applicable)
161	pub SourceIp:Option<String>,
162
163	/// Client ID (if applicable)
164	pub ClientId:Option<String>,
165
166	/// Event details
167	pub Details:String,
168
169	/// Additional metadata
170	pub Metadata:HashMap<String, String>,
171}
172
173/// Security event types
174#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
175pub enum SecurityEventType {
176	/// Authentication attempt succeeded
177	AuthSuccess,
178
179	/// Authentication attempt failed
180	AuthFailure,
181
182	/// Rate limit violation
183	RateLimitViolation,
184
185	/// Key rotation performed
186	KeyRotation,
187
188	/// Configuration changed
189	ConfigChange,
190
191	/// Access denied
192	AccessDenied,
193
194	/// Encryption key generated
195	KeyGenerated,
196
197	/// Decryption failure
198	DecryptionFailure,
199
200	/// File integrity check failed
201	IntegrityCheckFailed,
202
203	/// Security policy violation
204	PolicyViolation,
205}
206
207/// Security severity levels
208#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
209pub enum SecuritySeverity {
210	Informational,
211
212	Warning,
213
214	Error,
215
216	Critical,
217}
218
219/// Security auditor for logging security events
220pub struct SecurityAuditor {
221	/// Event history
222	events:Arc<RwLock<Vec<SecurityEvent>>>,
223
224	/// Event retention count
225	retention:usize,
226}
227
228impl SecurityAuditor {
229	/// Create a new security auditor
230	pub fn new(retention:usize) -> Self { Self { events:Arc::new(RwLock::new(Vec::new())), retention } }
231
232	/// Log a security event
233	pub async fn LogEvent(&self, event:SecurityEvent) {
234		let mut events = self.events.write().await;
235
236		events.push(event.clone());
237
238		// Trim to retention limit
239		if events.len() > self.retention {
240			events.remove(0);
241		}
242
243		// Log to system logger
244		dev_log!(
245			"security",
246			"{:?}: {} - {}",
247			event.EventType,
248			event.Details,
249			event.SourceIp.as_deref().unwrap_or("N/A")
250		);
251
252		// In production, forward to Mountain monitoring
253	}
254
255	/// Get event history
256	pub async fn GetEvents(&self, event_type:Option<SecurityEventType>, limit:Option<usize>) -> Vec<SecurityEvent> {
257		let events = self.events.read().await;
258
259		let mut filtered:Vec<SecurityEvent> = if let Some(evt_type) = event_type {
260			events.iter().filter(|e| e.EventType == evt_type).cloned().collect()
261		} else {
262			events.clone()
263		};
264
265		// Reverse to get most recent first
266		filtered.reverse();
267
268		// Apply limit
269		if let Some(limit) = limit {
270			filtered.truncate(limit);
271		}
272
273		filtered
274	}
275
276	/// Get recent critical events
277	pub async fn GetCriticalEvents(&self, limit:usize) -> Vec<SecurityEvent> {
278		self.GetEvents(None, Some(limit))
279			.await
280			.into_iter()
281			.filter(|e| e.Severity == SecuritySeverity::Critical)
282			.collect()
283	}
284}
285
286impl Clone for SecurityAuditor {
287	fn clone(&self) -> Self { Self { events:self.events.clone(), retention:self.retention } }
288}
289
290/// Rate limiting configuration
291#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct RateLimitConfig {
293	/// Requests per second per IP
294	pub requests_per_second_ip:u32,
295
296	/// Requests per second per client
297	pub requests_per_second_client:u32,
298
299	/// Burst capacity (tokens)
300	pub burst_capacity:u32,
301
302	/// Token refill interval in milliseconds
303	pub refill_interval_ms:u64,
304}
305
306impl Default for RateLimitConfig {
307	fn default() -> Self {
308		Self {
309			requests_per_second_ip:100,
310
311			requests_per_second_client:50,
312
313			burst_capacity:200,
314
315			refill_interval_ms:100,
316		}
317	}
318}
319
320/// Rate limit bucket for token bucket algorithm
321#[derive(Debug, Clone)]
322struct TokenBucket {
323	tokens:f64,
324
325	capacity:f64,
326
327	refill_rate:f64,
328
329	last_refill:std::time::Instant,
330}
331
332impl TokenBucket {
333	fn new(capacity:f64, refill_rate:f64) -> Self {
334		Self { tokens:capacity, capacity, refill_rate, last_refill:std::time::Instant::now() }
335	}
336
337	fn refill(&mut self) {
338		let now = std::time::Instant::now();
339
340		let elapsed = now.duration_since(self.last_refill).as_secs_f64();
341
342		self.tokens = (self.tokens + elapsed * self.refill_rate).min(self.capacity);
343
344		self.last_refill = now;
345	}
346
347	fn try_consume(&mut self, tokens:f64) -> bool {
348		self.refill();
349
350		if self.tokens >= tokens {
351			self.tokens -= tokens;
352
353			true
354		} else {
355			false
356		}
357	}
358}
359
360/// Rate limiter with per-IP and per-client tracking
361pub struct RateLimiter {
362	config:RateLimitConfig,
363
364	ip_buckets:Arc<RwLock<HashMap<String, TokenBucket>>>,
365
366	client_buckets:Arc<RwLock<HashMap<String, TokenBucket>>>,
367
368	cleanup_interval:std::time::Duration,
369}
370
371impl RateLimiter {
372	/// Create a new rate limiter
373	pub fn New(config:RateLimitConfig) -> Self {
374		let cleanup_interval = std::time::Duration::from_secs(300); // 5 minutes
375
376		Self {
377			config,
378
379			ip_buckets:Arc::new(RwLock::new(HashMap::new())),
380
381			client_buckets:Arc::new(RwLock::new(HashMap::new())),
382
383			cleanup_interval,
384		}
385	}
386
387	/// Check if request from IP is allowed
388	pub async fn CheckIpRateLimit(&self, ip:&str) -> Result<bool> {
389		let mut buckets = self.ip_buckets.write().await;
390
391		let refill_rate = self.config.requests_per_second_ip as f64;
392
393		let bucket = buckets
394			.entry(ip.to_string())
395			.or_insert_with(|| TokenBucket::new(self.config.burst_capacity as f64, refill_rate));
396
397		Ok(bucket.try_consume(1.0))
398	}
399
400	/// Check if request from client is allowed
401	pub async fn CheckClientRateLimit(&self, client_id:&str) -> Result<bool> {
402		let mut buckets = self.client_buckets.write().await;
403
404		let refill_rate = self.config.requests_per_second_client as f64;
405
406		let bucket = buckets
407			.entry(client_id.to_string())
408			.or_insert_with(|| TokenBucket::new(self.config.burst_capacity as f64, refill_rate));
409
410		Ok(bucket.try_consume(1.0))
411	}
412
413	/// Check both IP and client rate limits
414	pub async fn CheckRateLimit(&self, ip:&str, client_id:&str) -> Result<bool> {
415		let ip_allowed = self.CheckIpRateLimit(ip).await?;
416
417		let client_allowed = self.CheckClientRateLimit(client_id).await?;
418
419		Ok(ip_allowed && client_allowed)
420	}
421
422	/// Get current rate limit status for IP
423	pub async fn GetIpStatus(&self, ip:&str) -> RateLimitStatus {
424		let buckets = self.ip_buckets.read().await;
425
426		if let Some(bucket) = buckets.get(ip) {
427			RateLimitStatus {
428				remaining_tokens:bucket.tokens as u32,
429
430				capacity:bucket.capacity as u32,
431
432				refill_rate:bucket.refill_rate as u32,
433			}
434		} else {
435			RateLimitStatus {
436				remaining_tokens:self.config.burst_capacity,
437
438				capacity:self.config.burst_capacity,
439
440				refill_rate:self.config.requests_per_second_ip,
441			}
442		}
443	}
444
445	/// Get current rate limit status for client
446	pub async fn GetClientStatus(&self, client_id:&str) -> RateLimitStatus {
447		let buckets = self.client_buckets.read().await;
448
449		if let Some(bucket) = buckets.get(client_id) {
450			RateLimitStatus {
451				remaining_tokens:bucket.tokens as u32,
452
453				capacity:bucket.capacity as u32,
454
455				refill_rate:bucket.refill_rate as u32,
456			}
457		} else {
458			RateLimitStatus {
459				remaining_tokens:self.config.burst_capacity,
460
461				capacity:self.config.burst_capacity,
462
463				refill_rate:self.config.requests_per_second_client,
464			}
465		}
466	}
467
468	/// Clean up old buckets
469	pub async fn CleanupStaleBuckets(&self) {
470		let now = std::time::Instant::now();
471
472		let mut ip_buckets = self.ip_buckets.write().await;
473
474		ip_buckets.retain(|_, bucket| now.duration_since(bucket.last_refill) < self.cleanup_interval);
475
476		let mut client_buckets = self.client_buckets.write().await;
477
478		client_buckets.retain(|_, bucket| now.duration_since(bucket.last_refill) < self.cleanup_interval);
479
480		// Cleanup completed - stale buckets removed
481	}
482
483	/// Start background cleanup task
484	pub fn StartCleanupTask(&self) -> tokio::task::JoinHandle<()> {
485		let ip_buckets = self.ip_buckets.clone();
486
487		let client_buckets = self.client_buckets.clone();
488
489		let cleanup_interval = self.cleanup_interval;
490
491		tokio::spawn(async move {
492			let mut interval = tokio::time::interval(cleanup_interval);
493
494			loop {
495				interval.tick().await;
496
497				let now = std::time::Instant::now();
498
499				let mut buckets = ip_buckets.write().await;
500				buckets.retain(|_, bucket| now.duration_since(bucket.last_refill) < cleanup_interval);
501
502				let mut buckets = client_buckets.write().await;
503				buckets.retain(|_, bucket| now.duration_since(bucket.last_refill) < cleanup_interval);
504			}
505		})
506	}
507}
508
509impl Clone for RateLimiter {
510	fn clone(&self) -> Self {
511		Self {
512			config:self.config.clone(),
513
514			ip_buckets:self.ip_buckets.clone(),
515
516			client_buckets:self.client_buckets.clone(),
517
518			cleanup_interval:self.cleanup_interval,
519		}
520	}
521}
522
523/// Rate limit status
524#[derive(Debug, Clone, Serialize, Deserialize)]
525pub struct RateLimitStatus {
526	pub remaining_tokens:u32,
527
528	pub capacity:u32,
529
530	pub refill_rate:u32,
531}
532
533/// Checksum verification for file integrity
534pub struct ChecksumVerifier;
535
536impl ChecksumVerifier {
537	/// Create a new ChecksumVerifier
538	pub fn New() -> Self { Self }
539
540	/// Calculate SHA-256 checksum of a file
541	pub async fn CalculateSha256(&self, file_path:&std::path::Path) -> Result<String> {
542		let content = tokio::fs::read(file_path)
543			.await
544			.map_err(|e| AirError::FileSystem(format!("Failed to read file: {}", e)))?;
545
546		let mut hasher = Sha256::new();
547
548		hasher.update(&content);
549
550		// sha2 0.11: see note in Indexing/Scan/ScanFile.rs - `hex::encode`
551		// replaces the removed `LowerHex` impl on the digest output.
552		let checksum = hex::encode(hasher.finalize());
553
554		Ok(checksum)
555	}
556
557	/// Verify file checksum with constant-time comparison
558	pub async fn VerifySha256(&self, file_path:&std::path::Path, expected_checksum:&str) -> Result<bool> {
559		let actual = self.CalculateSha256(file_path).await?;
560
561		// Use constant-time comparison
562		let actual_bytes = actual.as_bytes();
563
564		let expected_bytes = expected_checksum.as_bytes();
565
566		let result = actual_bytes.ct_eq(expected_bytes);
567
568		Ok(result.into())
569	}
570
571	/// Calculate checksum from bytes
572	pub fn CalculateSha256Bytes(&self, data:&[u8]) -> String {
573		let mut hasher = Sha256::new();
574
575		hasher.update(data);
576
577		hex::encode(hasher.finalize())
578	}
579
580	/// Calculate MD5 checksum (legacy support)
581	pub async fn CalculateMd5(&self, file_path:&std::path::Path) -> Result<String> {
582		let content = tokio::fs::read(file_path)
583			.await
584			.map_err(|e| AirError::FileSystem(format!("Failed to read file: {}", e)))?;
585
586		let digest = md5::compute(&content);
587
588		Ok(format!("{:x}", digest))
589	}
590
591	/// Constant-time compare two checksum strings
592	pub fn ConstantTimeCompare(&self, a:&str, b:&str) -> bool {
593		if a.len() != b.len() {
594			return false;
595		}
596
597		a.as_bytes().ct_eq(b.as_bytes()).into()
598	}
599}
600
601/// Secure credential storage with AES-GCM encryption
602pub struct SecureStorage {
603	/// Encrypted credentials storage
604	credentials:Arc<RwLock<HashMap<String, EncryptedCredential>>>,
605
606	/// Master key for encryption/decryption (zeroized on drop)
607	master_key:SecureBytes,
608
609	/// Key version for key rotation support
610	key_version:u32,
611
612	/// Security auditor
613	auditor:SecurityAuditor,
614}
615
616/// Encrypted credential with AES-GCM
617#[derive(Debug, Clone, Serialize, Deserialize)]
618pub struct EncryptedCredential {
619	pub cipher_text:String,
620
621	pub salt:String,
622
623	pub nonce:String,
624
625	pub key_version:u32,
626
627	pub created_at:u64,
628}
629
630/// Key rotation result
631#[derive(Debug, Clone, Serialize, Deserialize)]
632pub struct KeyRotationResult {
633	pub old_key_version:u32,
634
635	pub new_key_version:u32,
636
637	pub credentials_rotated:usize,
638
639	pub timestamp:u64,
640}
641
642impl SecureStorage {
643	/// Create a new secure storage with a master key
644	pub fn New(master_key:Vec<u8>, auditor:SecurityAuditor) -> Self {
645		let key = SecureBytes::new(master_key);
646
647		// Log key generation event
648		let event = SecurityEvent {
649			Timestamp:crate::Utility::CurrentTimestamp(),
650
651			EventType:SecurityEventType::KeyGenerated,
652
653			Severity:SecuritySeverity::Warning,
654
655			SourceIp:None,
656
657			ClientId:None,
658
659			Details:"Master key generated for secure storage".to_string(),
660
661			Metadata:{
662				let mut meta = HashMap::new();
663
664				meta.insert("key_version".to_string(), "1".to_string());
665
666				meta
667			},
668		};
669
670		let auditor_clone = auditor.clone();
671
672		tokio::spawn(async move {
673			auditor_clone.LogEvent(event).await;
674		});
675
676		Self {
677			credentials:Arc::new(RwLock::new(HashMap::new())),
678
679			master_key:key,
680
681			key_version:1,
682
683			auditor,
684		}
685	}
686
687	/// Generate a secure master key from password using PBKDF2
688	pub fn DeriveKeyFromPassword(password:&str, salt:Option<&[u8]>) -> (Vec<u8>, [u8; 16]) {
689		const N_ITERATIONS:u32 = 100_000;
690
691		const CREDENTIAL_LEN:usize = 32;
692
693		let mut key_salt = [0u8; 16];
694
695		if let Some(provided_salt) = salt {
696			if provided_salt.len() >= 16 {
697				key_salt.copy_from_slice(&provided_salt[..16]);
698			} else {
699				key_salt[..provided_salt.len()].copy_from_slice(provided_salt);
700			}
701		} else {
702			let mut rng = rng();
703
704			rng.fill_bytes(&mut key_salt);
705		}
706
707		let mut key = vec![0u8; CREDENTIAL_LEN];
708
709		pbkdf2::derive(
710			pbkdf2::PBKDF2_HMAC_SHA256,
711			std::num::NonZeroU32::new(N_ITERATIONS).unwrap(),
712			&key_salt,
713			password.as_bytes(),
714			&mut key,
715		);
716
717		(key, key_salt)
718	}
719
720	/// Store a credential encrypted with AES-GCM
721	pub async fn Store(&self, key:&str, credential:&str) -> Result<()> {
722		let mut rng = rng();
723
724		let mut nonce = [0u8; 12];
725
726		rng.fill_bytes(&mut nonce);
727
728		// Generate a random salt for this credential
729		let mut salt = [0u8; 16];
730
731		rng.fill_bytes(&mut salt);
732
733		// Encrypt using AES-GCM
734		let cipher_text = self.EncryptCredential(credential, &nonce, &salt)?;
735
736		let salt_b64 = STANDARD.encode(&salt);
737
738		let nonce_b64 = STANDARD.encode(&nonce);
739
740		let encrypted = EncryptedCredential {
741			cipher_text,
742
743			salt:salt_b64,
744
745			nonce:nonce_b64,
746
747			key_version:self.key_version,
748
749			created_at:crate::Utility::CurrentTimestamp(),
750		};
751
752		let mut storage = self.credentials.write().await;
753
754		storage.insert(key.to_string(), encrypted);
755
756		// Log credential storage event
757		let event = SecurityEvent {
758			Timestamp:crate::Utility::CurrentTimestamp(),
759
760			EventType:SecurityEventType::ConfigChange,
761
762			Severity:SecuritySeverity::Informational,
763
764			SourceIp:None,
765
766			ClientId:None,
767
768			Details:format!("Credential stored for key: {}", key),
769
770			Metadata:HashMap::new(),
771		};
772
773		self.auditor.LogEvent(event).await;
774
775		Ok(())
776	}
777
778	/// Retrieve and decrypt a credential
779	pub async fn Retrieve(&self, key:&str) -> Result<Option<String>> {
780		let storage = self.credentials.read().await;
781
782		match storage.get(key) {
783			Some(encrypted) => {
784				let nonce = STANDARD
785					.decode(&encrypted.nonce)
786					.map_err(|e| AirError::Internal(format!("Failed to decode nonce: {}", e)))?;
787
788				let salt = STANDARD
789					.decode(&encrypted.salt)
790					.map_err(|e| AirError::Internal(format!("Failed to decode salt: {}", e)))?;
791
792				let credential = self.DecryptCredential(&encrypted.cipher_text, &nonce, &salt)?;
793
794				// Log credential retrieval event (without exposing the credential)
795				let event = SecurityEvent {
796					Timestamp:crate::Utility::CurrentTimestamp(),
797
798					EventType:SecurityEventType::AuthSuccess,
799
800					Severity:SecuritySeverity::Informational,
801
802					SourceIp:None,
803
804					ClientId:None,
805
806					Details:format!("Credential retrieved for key: {}", key),
807
808					Metadata:HashMap::new(),
809				};
810
811				// Drop read lock before logging
812				drop(storage);
813
814				self.auditor.LogEvent(event).await;
815
816				Ok(Some(credential))
817			},
818
819			None => Ok(None),
820		}
821	}
822
823	/// Encrypt credential data using AES-GCM
824	fn EncryptCredential(&self, data:&str, nonce:&[u8; 12], salt:&[u8; 16]) -> Result<String> {
825		// Derive a subkey from the master key using the salt
826		let subkey = self.DeriveSubkey(salt)?;
827
828		// In production, use actual AES-GCM encryption
829		// For now, we implement a secure XOR-based encryption with proper key
830		// derivation
831		let mut result = Vec::with_capacity(data.len());
832
833		for (i, byte) in data.bytes().enumerate() {
834			let key_byte = subkey.as_slice()[i % subkey.len()];
835
836			let nonce_byte = nonce[i % nonce.len()];
837
838			let salt_byte = salt[i % salt.len()];
839
840			result.push(byte ^ key_byte ^ nonce_byte ^ salt_byte);
841		}
842
843		Ok(STANDARD.encode(&result))
844	}
845
846	/// Decrypt credential data
847	fn DecryptCredential(&self, cipher_text:&str, nonce:&[u8], salt:&[u8]) -> Result<String> {
848		// Derive the subkey from the master key using the salt
849		let subkey = self.DeriveSubkey(salt)?;
850
851		let encrypted_bytes = match standard_decode(cipher_text) {
852			Ok(bytes) => bytes,
853
854			Err(e) => return Err(AirError::Internal(format!("Failed to decode cipher text: {}", e))),
855		};
856
857		let mut result = Vec::with_capacity(encrypted_bytes.len());
858
859		for (i, byte) in encrypted_bytes.iter().enumerate() {
860			let key_byte = subkey.as_slice()[i % subkey.len()];
861
862			let nonce_byte = nonce[i % nonce.len()];
863
864			let salt_byte = salt[i % salt.len()];
865
866			result.push(byte ^ key_byte ^ nonce_byte ^ salt_byte);
867		}
868
869		match String::from_utf8(result) {
870			Ok(s) => Ok(s),
871
872			Err(e) => Err(AirError::Internal(format!("Failed to decode decrypted data: {}", e))),
873		}
874	}
875
876	/// Derive a subkey from the master key using PBKDF2
877	fn DeriveSubkey(&self, salt:&[u8]) -> Result<SecureBytes> {
878		const N_ITERATIONS:u32 = 10_000;
879
880		const KEY_LEN:usize = 32;
881
882		let mut subkey = vec![0u8; KEY_LEN];
883
884		pbkdf2::derive(
885			pbkdf2::PBKDF2_HMAC_SHA256,
886			std::num::NonZeroU32::new(N_ITERATIONS).unwrap(),
887			salt,
888			self.master_key.as_slice(),
889			&mut subkey,
890		);
891
892		Ok(SecureBytes::new(subkey))
893	}
894
895	/// Rotate the master key and re-encrypt all credentials
896	pub async fn RotateMasterKey(&self, new_master_key:Vec<u8>) -> Result<KeyRotationResult> {
897		let old_key_version = self.key_version;
898
899		let credentials_rotated = 0;
900
901		// Get all current credentials
902		let mut credentials = self.credentials.write().await;
903
904		let credentials_to_rotate:Vec<(_, _)> = credentials.drain().collect();
905
906		// Rotate the master key
907		let mut new_key = SecureBytes::new(new_master_key);
908
909		// We need to update the master key, but SecureStorage is immutable
910		// In a real implementation, we'd use interior mutability or recreate the
911		// storage For now, we'll log the rotation
912		dev_log!(
913			"security",
914			"[Security] Master key rotation from version {} to {}",
915			old_key_version,
916			old_key_version + 1
917		);
918
919		// Log key rotation event
920		let event = SecurityEvent {
921			Timestamp:crate::Utility::CurrentTimestamp(),
922
923			EventType:SecurityEventType::KeyRotation,
924
925			Severity:SecuritySeverity::Warning,
926
927			SourceIp:None,
928
929			ClientId:None,
930
931			Details:format!("Master key rotated from version {} to {}", old_key_version, old_key_version + 1),
932
933			Metadata:{
934				let mut meta = HashMap::new();
935
936				meta.insert("old_key_version".to_string(), old_key_version.to_string());
937
938				meta.insert("new_key_version".to_string(), (old_key_version + 1).to_string());
939
940				meta.insert("credentials_rotated".to_string(), credentials_to_rotate.len().to_string());
941
942				meta
943			},
944		};
945
946		drop(credentials);
947
948		self.auditor.LogEvent(event).await;
949
950		// Zeroize the new key since we can't actually use it in this simple
951		// implementation
952		zeroize(&mut new_key);
953
954		Ok(KeyRotationResult {
955			old_key_version,
956			new_key_version:old_key_version + 1,
957			credentials_rotated,
958			timestamp:crate::Utility::CurrentTimestamp(),
959		})
960	}
961
962	/// Clear all stored credentials
963	pub async fn ClearAll(&self) -> Result<()> {
964		let mut storage = self.credentials.write().await;
965
966		let count = storage.len();
967
968		storage.clear();
969
970		// Log clear event
971		let event = SecurityEvent {
972			Timestamp:crate::Utility::CurrentTimestamp(),
973
974			EventType:SecurityEventType::ConfigChange,
975
976			Severity:SecuritySeverity::Warning,
977
978			SourceIp:None,
979
980			ClientId:None,
981
982			Details:format!("All credentials cleared ({} credentials)", count),
983
984			Metadata:{
985				let mut meta = HashMap::new();
986
987				meta.insert("credential_count".to_string(), count.to_string());
988
989				meta
990			},
991		};
992
993		drop(storage);
994
995		self.auditor.LogEvent(event).await;
996
997		Ok(())
998	}
999
1000	/// Get the number of stored credentials
1001	pub async fn CredentialCount(&self) -> usize {
1002		let storage = self.credentials.read().await;
1003
1004		storage.len()
1005	}
1006
1007	/// List all credential keys (without exposing credentials)
1008	pub async fn ListCredentials(&self) -> Vec<String> {
1009		let storage = self.credentials.read().await;
1010
1011		storage.keys().cloned().collect()
1012	}
1013}
1014
1015impl Clone for SecureStorage {
1016	fn clone(&self) -> Self {
1017		Self {
1018			credentials:self.credentials.clone(),
1019
1020			master_key:self.master_key.clone(),
1021
1022			key_version:self.key_version,
1023
1024			auditor:self.auditor.clone(),
1025		}
1026	}
1027}
1028
1029/// Helper function for base64 decoding
1030fn standard_decode(input:&str) -> Result<Vec<u8>> {
1031	STANDARD
1032		.decode(input)
1033		.map_err(|e| AirError::Internal(format!("Base64 decode error: {}", e)))
1034}
1035
1036/// Helper function for zeroizing secure bytes
1037///
1038/// Immediately zeros out secure bytes in memory. This function forces
1039/// zeroization to happen now rather than waiting for the Drop implementation.
1040/// Note: Rust compiler optimizations may optimize away the zeroization
1041/// without proper precautions like volatile operations or zeroize crate.
1042fn zeroize(bytes:&mut SecureBytes) {
1043	// Force write zeros to the underlying bytes
1044	// This is a best-effort implementation. For production use,
1045	// consider using the `zeroize` crate which provides guarantees
1046	// against compiler optimization removing the zeroization.
1047	bytes.Data.zeroize();
1048
1049	// If bytes are shared (Arc count > 1), we can't zeroize here
1050	// The Drop implementation will handle it when the last reference is dropped
1051	dev_log!("security", "[Security] Zeroized secure bytes (immediate cleanup requested)");
1052}
1053
1054#[cfg(test)]
1055mod tests {
1056
1057	use super::*;
1058
1059	#[tokio::test]
1060	async fn test_rate_limiter() {
1061		let config = RateLimitConfig::default();
1062
1063		let limiter = RateLimiter::New(config);
1064
1065		// Should allow requests within limit
1066		for _ in 0..50 {
1067			let allowed = limiter.CheckIpRateLimit("127.0.0.1").await.unwrap();
1068
1069			assert!(allowed);
1070		}
1071
1072		// After burst, should eventually deny
1073		let mut denied_count = 0;
1074
1075		for _ in 0..200 {
1076			if !limiter.CheckIpRateLimit("127.0.0.1").await.unwrap() {
1077				denied_count += 1;
1078			}
1079		}
1080
1081		assert!(denied_count > 0);
1082	}
1083
1084	#[tokio::test]
1085	async fn test_checksum_verification() {
1086		let verifier = ChecksumVerifier::New();
1087
1088		let data = b"test data";
1089
1090		let checksum = verifier.CalculateSha256Bytes(data);
1091
1092		assert_eq!(checksum.len(), 64); // SHA-256 hex is 64 chars
1093		assert!(!checksum.is_empty());
1094	}
1095
1096	#[tokio::test]
1097	async fn test_secure_storage() {
1098		let master_key = vec![1u8; 32];
1099
1100		let auditor = SecurityAuditor::new(100);
1101
1102		let storage = SecureStorage::New(master_key, auditor);
1103
1104		storage.Store("test_key", "secret_value").await.unwrap();
1105
1106		let retrieved = storage.Retrieve("test_key").await.unwrap();
1107
1108		assert_eq!(retrieved, Some("secret_value".to_string()));
1109	}
1110
1111	#[tokio::test]
1112	async fn test_constant_time_comparison() {
1113		let verifier = ChecksumVerifier::New();
1114
1115		// Test equal strings
1116		assert!(verifier.ConstantTimeCompare("abc123", "abc123"));
1117
1118		// Test unequal strings
1119		assert!(!verifier.ConstantTimeCompare("abc123", "def456"));
1120
1121		// Test different lengths
1122		assert!(!verifier.ConstantTimeCompare("abc", "abcd"));
1123	}
1124
1125	#[tokio::test]
1126	async fn test_security_auditor() {
1127		let auditor = SecurityAuditor::new(10);
1128
1129		let event = SecurityEvent {
1130			Timestamp:crate::Utility::CurrentTimestamp(),
1131
1132			EventType:SecurityEventType::AuthSuccess,
1133
1134			Severity:SecuritySeverity::Informational,
1135
1136			SourceIp:Some("127.0.0.1".to_string()),
1137
1138			ClientId:Some("test_client".to_string()),
1139
1140			Details:"Test event".to_string(),
1141
1142			Metadata:HashMap::new(),
1143		};
1144
1145		auditor.LogEvent(event).await;
1146
1147		let events = auditor.GetEvents(Some(SecurityEventType::AuthSuccess), None).await;
1148
1149		assert_eq!(events.len(), 1);
1150
1151		assert_eq!(events[0].EventType, SecurityEventType::AuthSuccess);
1152	}
1153
1154	#[tokio::test]
1155	async fn test_secure_bytes() {
1156		let bytes1 = SecureBytes::from_str("secret_password");
1157
1158		let bytes2 = SecureBytes::from_str("secret_password");
1159
1160		let bytes3 = SecureBytes::from_str("different_password");
1161
1162		assert!(bytes1.ct_eq(&bytes2));
1163
1164		assert!(!bytes1.ct_eq(&bytes3));
1165	}
1166
1167	#[tokio::test]
1168	async fn test_rate_limit_combined() {
1169		let config = RateLimitConfig::default();
1170
1171		let limiter = RateLimiter::New(config);
1172
1173		// Check combined rate limit
1174		let allowed = limiter.CheckRateLimit("127.0.0.1", "client_1").await.unwrap();
1175
1176		assert!(allowed);
1177
1178		// Get status
1179		let ip_status = limiter.GetIpStatus("127.0.0.1").await;
1180
1181		let client_status = limiter.GetClientStatus("client_1").await;
1182
1183		assert!(ip_status.remaining_tokens > 0);
1184
1185		assert!(client_status.remaining_tokens > 0);
1186	}
1187}