1use 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#[derive(Clone, Deserialize, Serialize)]
119pub struct SecureBytes {
120 Data:Vec<u8>,
122}
123
124impl SecureBytes {
125 pub fn new(Data:Vec<u8>) -> Self { Self { Data } }
127
128 pub fn from_str(S:&str) -> Self { Self { Data:S.as_bytes().to_vec() } }
130
131 pub fn as_slice(&self) -> &[u8] { &self.Data }
133
134 pub fn len(&self) -> usize { self.Data.len() }
136
137 pub fn is_empty(&self) -> bool { self.Data.is_empty() }
139
140 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#[derive(Debug, Clone, Serialize, Deserialize)]
150pub struct SecurityEvent {
151 pub Timestamp:u64,
153
154 pub EventType:SecurityEventType,
156
157 pub Severity:SecuritySeverity,
159
160 pub SourceIp:Option<String>,
162
163 pub ClientId:Option<String>,
165
166 pub Details:String,
168
169 pub Metadata:HashMap<String, String>,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
175pub enum SecurityEventType {
176 AuthSuccess,
178
179 AuthFailure,
181
182 RateLimitViolation,
184
185 KeyRotation,
187
188 ConfigChange,
190
191 AccessDenied,
193
194 KeyGenerated,
196
197 DecryptionFailure,
199
200 IntegrityCheckFailed,
202
203 PolicyViolation,
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
209pub enum SecuritySeverity {
210 Informational,
211
212 Warning,
213
214 Error,
215
216 Critical,
217}
218
219pub struct SecurityAuditor {
221 events:Arc<RwLock<Vec<SecurityEvent>>>,
223
224 retention:usize,
226}
227
228impl SecurityAuditor {
229 pub fn new(retention:usize) -> Self { Self { events:Arc::new(RwLock::new(Vec::new())), retention } }
231
232 pub async fn LogEvent(&self, event:SecurityEvent) {
234 let mut events = self.events.write().await;
235
236 events.push(event.clone());
237
238 if events.len() > self.retention {
240 events.remove(0);
241 }
242
243 dev_log!(
245 "security",
246 "{:?}: {} - {}",
247 event.EventType,
248 event.Details,
249 event.SourceIp.as_deref().unwrap_or("N/A")
250 );
251
252 }
254
255 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 filtered.reverse();
267
268 if let Some(limit) = limit {
270 filtered.truncate(limit);
271 }
272
273 filtered
274 }
275
276 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#[derive(Debug, Clone, Serialize, Deserialize)]
292pub struct RateLimitConfig {
293 pub requests_per_second_ip:u32,
295
296 pub requests_per_second_client:u32,
298
299 pub burst_capacity:u32,
301
302 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#[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
360pub 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 pub fn New(config:RateLimitConfig) -> Self {
374 let cleanup_interval = std::time::Duration::from_secs(300); 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 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 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 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 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 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 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 }
482
483 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#[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
533pub struct ChecksumVerifier;
535
536impl ChecksumVerifier {
537 pub fn New() -> Self { Self }
539
540 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 let checksum = hex::encode(hasher.finalize());
553
554 Ok(checksum)
555 }
556
557 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 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 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 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 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
601pub struct SecureStorage {
603 credentials:Arc<RwLock<HashMap<String, EncryptedCredential>>>,
605
606 master_key:SecureBytes,
608
609 key_version:u32,
611
612 auditor:SecurityAuditor,
614}
615
616#[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#[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 pub fn New(master_key:Vec<u8>, auditor:SecurityAuditor) -> Self {
645 let key = SecureBytes::new(master_key);
646
647 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 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 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 let mut salt = [0u8; 16];
730
731 rng.fill_bytes(&mut salt);
732
733 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 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 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 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(storage);
813
814 self.auditor.LogEvent(event).await;
815
816 Ok(Some(credential))
817 },
818
819 None => Ok(None),
820 }
821 }
822
823 fn EncryptCredential(&self, data:&str, nonce:&[u8; 12], salt:&[u8; 16]) -> Result<String> {
825 let subkey = self.DeriveSubkey(salt)?;
827
828 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 fn DecryptCredential(&self, cipher_text:&str, nonce:&[u8], salt:&[u8]) -> Result<String> {
848 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 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 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 let mut credentials = self.credentials.write().await;
903
904 let credentials_to_rotate:Vec<(_, _)> = credentials.drain().collect();
905
906 let mut new_key = SecureBytes::new(new_master_key);
908
909 dev_log!(
913 "security",
914 "[Security] Master key rotation from version {} to {}",
915 old_key_version,
916 old_key_version + 1
917 );
918
919 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(&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 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 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 pub async fn CredentialCount(&self) -> usize {
1002 let storage = self.credentials.read().await;
1003
1004 storage.len()
1005 }
1006
1007 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
1029fn 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
1036fn zeroize(bytes:&mut SecureBytes) {
1043 bytes.Data.zeroize();
1048
1049 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 for _ in 0..50 {
1067 let allowed = limiter.CheckIpRateLimit("127.0.0.1").await.unwrap();
1068
1069 assert!(allowed);
1070 }
1071
1072 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); 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 assert!(verifier.ConstantTimeCompare("abc123", "abc123"));
1117
1118 assert!(!verifier.ConstantTimeCompare("abc123", "def456"));
1120
1121 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 let allowed = limiter.CheckRateLimit("127.0.0.1", "client_1").await.unwrap();
1175
1176 assert!(allowed);
1177
1178 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}