ciphern 0.2.1

Enterprise-grade cryptographic library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

use crate::error::{CryptoError, Result};
use crate::i18n::{translate, translate_with_args};
use crate::types::Algorithm;
use chrono::{DateTime, Utc};
use lazy_static::lazy_static;
use prometheus::{Counter, Histogram, HistogramOpts, Registry};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::mpsc::{channel, Sender};
use std::sync::{Arc, Mutex, RwLock};
use std::thread;

lazy_static! {
    pub static ref REGISTRY: Registry = Registry::new();
    pub static ref CRYPTO_OPERATIONS_TOTAL: Counter = Counter::new(
        "crypto_operations_total",
        "Total number of cryptographic operations"
    )
    .expect("Failed to create CRYPTO_OPERATIONS_TOTAL metric");
    pub static ref CRYPTO_OPERATION_LATENCY: Histogram = Histogram::with_opts(HistogramOpts::new(
        "crypto_operation_latency_seconds",
        "Latency of cryptographic operations in seconds"
    ))
    .expect("Failed to create CRYPTO_OPERATION_LATENCY metric");
    pub static ref SECURITY_ALERTS_TOTAL: Counter =
        Counter::new("security_alerts_total", "Total number of security alerts")
            .expect("Failed to create SECURITY_ALERTS_TOTAL metric");
}

/// Sanitize sensitive information from error details for audit logging
fn sanitize_error_for_log(error: &CryptoError) -> String {
    match error {
        CryptoError::InvalidKeySize { .. } => "Invalid key size - operation rejected".to_string(),
        CryptoError::InvalidParameter(msg) => {
            if msg.contains("key") || msg.contains("secret") || msg.contains("password") {
                "Invalid parameter - operation rejected".to_string()
            } else {
                msg.clone()
            }
        }
        CryptoError::InvalidState(msg) => {
            if msg.contains("key") || msg.contains("memory") {
                "Invalid state - operation rejected".to_string()
            } else {
                msg.clone()
            }
        }
        CryptoError::DecryptionFailed(_) => {
            "Decryption operation failed - invalid key or corrupted data".to_string()
        }
        CryptoError::EncryptionFailed(_) => "Encryption operation failed".to_string(),
        CryptoError::KeyNotFound(_) => "Key not found - key_id: [REDACTED]".to_string(),
        CryptoError::KeyError(_) => "Key operation failed".to_string(),
        CryptoError::UnsupportedAlgorithm(msg) => {
            format!(
                "Unsupported algorithm: {}",
                msg.split_whitespace().next().unwrap_or("unknown")
            )
        }
        CryptoError::MemoryProtectionFailed(_) => {
            "Memory protection failure - security violation detected".to_string()
        }
        CryptoError::MemoryAllocationFailed(_) => {
            "Memory allocation failed - operation aborted".to_string()
        }
        CryptoError::MemoryTransferFailed(_) => {
            "Memory transfer failed - data corruption possible".to_string()
        }
        CryptoError::MemoryTampered => "Memory tampering detected - security alert".to_string(),
        CryptoError::FipsError(_) => "FIPS compliance violation detected".to_string(),
        CryptoError::SideChannelError(_) => "Side-channel attack detected or prevented".to_string(),
        CryptoError::NotImplemented(_) => "Operation not implemented".to_string(),
        CryptoError::IoError(_) => "I/O operation failed".to_string(),
        CryptoError::TimeError => "System time error - operation rejected".to_string(),
        CryptoError::PluginError(_) => "Plugin operation failed".to_string(),
        CryptoError::InternalError(_) => "Internal error occurred".to_string(),
        CryptoError::SigningFailed(_) => "Signing operation failed".to_string(),
        CryptoError::VerificationFailed(_) => "Verification operation failed".to_string(),
        CryptoError::UnknownError => "Unknown error occurred".to_string(),
        CryptoError::InsufficientEntropy => {
            "Insufficient entropy for cryptographic operation".to_string()
        }
        CryptoError::KeyUsageLimitExceeded { .. } => {
            "Key usage limit exceeded - operation rejected".to_string()
        }
        CryptoError::SecurityError(_) => "Security error detected - operation rejected".to_string(),
        CryptoError::InvalidKeyLength(_) => "Invalid key length - operation rejected".to_string(),
        CryptoError::HardwareAccelerationUnavailable(_) => {
            "Hardware acceleration unavailable - using software fallback".to_string()
        }
        CryptoError::AsyncOperationFailed(_) => "Async operation failed".to_string(),
        CryptoError::InvalidInput(_) => "Invalid input - operation rejected".to_string(),
        CryptoError::NotInitialized => "System not initialized - operation rejected".to_string(),
        CryptoError::HardwareInitializationFailed(_) => {
            "Hardware initialization failed - operation rejected".to_string()
        }
    }
}

// 注册指标到注册表
#[allow(dead_code)]
fn register_metrics() {
    // 确保指标只被注册一次
    if let Err(e) = REGISTRY.register(Box::new(CRYPTO_OPERATIONS_TOTAL.clone())) {
        eprintln!("Failed to register CRYPTO_OPERATIONS_TOTAL: {}", e);
    }
    if let Err(e) = REGISTRY.register(Box::new(CRYPTO_OPERATION_LATENCY.clone())) {
        eprintln!("Failed to register CRYPTO_OPERATION_LATENCY: {}", e);
    }
    if let Err(e) = REGISTRY.register(Box::new(SECURITY_ALERTS_TOTAL.clone())) {
        eprintln!("Failed to register SECURITY_ALERTS_TOTAL: {}", e);
    }
}

// 全局实例定义
lazy_static! {
    static ref LOGGER: AuditLogger = AuditLogger::new();
    static ref PERFORMANCE_MONITOR: Arc<PerformanceMonitor> = Arc::new(PerformanceMonitor::new());
}

/// Aggregated performance statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceStats {
    /// Total operations performed
    pub total_operations: u64,
    /// Average latency in microseconds
    pub avg_latency_us: f64,
    /// Minimum latency in microseconds
    pub min_latency_us: u64,
    /// Maximum latency in microseconds
    pub max_latency_us: u64,
    /// Average throughput in operations per second
    pub avg_throughput_ops_per_sec: f64,
    /// Average cache hit rate
    pub avg_cache_hit_rate: f64,
    /// Total data processed in bytes
    pub total_data_processed_bytes: u64,
    /// Performance trend (improving/stable/degrading)
    pub performance_trend: String,
}

#[derive(Serialize, Deserialize)]
struct OperationMetrics {
    total_latency_us: u64,
    min_latency_us: u64,
    max_latency_us: u64,
    operation_count: u64,
    total_data_size: u64,
    cache_hits: u64,
    cache_misses: u64,
}

impl Default for OperationMetrics {
    fn default() -> Self {
        Self {
            total_latency_us: 0,
            min_latency_us: u64::MAX,
            max_latency_us: 0,
            operation_count: 0,
            total_data_size: 0,
            cache_hits: 0,
            cache_misses: 0,
        }
    }
}

impl OperationMetrics {
    #[allow(dead_code)]
    fn update(&mut self, latency_us: u64, data_size: usize, cache_hit: bool) {
        self.total_latency_us += latency_us;
        self.min_latency_us = self.min_latency_us.min(latency_us);
        self.max_latency_us = self.max_latency_us.max(latency_us);
        self.operation_count += 1;
        self.total_data_size += data_size as u64;
        if cache_hit {
            self.cache_hits += 1;
        } else {
            self.cache_misses += 1;
        }
    }

    #[allow(dead_code)]
    fn to_stats(&self) -> PerformanceStats {
        let avg_latency = if self.operation_count > 0 {
            self.total_latency_us as f64 / self.operation_count as f64
        } else {
            0.0
        };

        let avg_throughput = if self.operation_count > 0 {
            (self.operation_count as f64 * 1_000_000.0) / self.total_latency_us as f64
        } else {
            0.0
        };

        let avg_cache_hit_rate = if self.cache_hits + self.cache_misses > 0 {
            self.cache_hits as f64 / (self.cache_hits + self.cache_misses) as f64
        } else {
            0.0
        };

        let performance_trend = if avg_throughput > 1000.0 {
            "improving"
        } else if avg_throughput > 500.0 {
            "stable"
        } else {
            "degrading"
        };

        PerformanceStats {
            total_operations: self.operation_count,
            avg_latency_us: avg_latency,
            min_latency_us: if self.operation_count > 0 {
                self.min_latency_us
            } else {
                0
            },
            max_latency_us: self.max_latency_us,
            avg_throughput_ops_per_sec: avg_throughput,
            avg_cache_hit_rate,
            total_data_processed_bytes: self.total_data_size,
            performance_trend: performance_trend.to_string(),
        }
    }
}

/// Performance monitoring system
#[derive(Clone)]
pub struct PerformanceMonitor {
    metrics: Arc<RwLock<HashMap<String, OperationMetrics>>>,
}

impl Default for PerformanceMonitor {
    fn default() -> Self {
        Self::new()
    }
}

impl PerformanceMonitor {
    pub fn new() -> Self {
        Self {
            metrics: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// 记录操作的性能指标
    #[allow(dead_code)]
    pub fn record_operation(
        &self,
        operation: &str,
        algo: Option<Algorithm>,
        latency_us: u64,
        data_size: usize,
        cache_hit: bool,
    ) {
        let key = format!("{}_{:?}", operation, algo);

        // Use write lock with poison recovery
        match self.metrics.write() {
            Ok(mut metrics) => {
                metrics
                    .entry(key)
                    .or_default()
                    .update(latency_us, data_size, cache_hit);
            }
            Err(poisoned) => {
                log::warn!("{}", translate("log.monitor_lock_poisoned"));
                let mut metrics = poisoned.into_inner();
                metrics
                    .entry(key)
                    .or_default()
                    .update(latency_us, data_size, cache_hit);
            }
        }

        // Update Prometheus metrics
        CRYPTO_OPERATIONS_TOTAL.inc();
        CRYPTO_OPERATION_LATENCY.observe(latency_us as f64 / 1_000_000.0);
    }

    /// Get performance statistics for a specific operation
    #[allow(dead_code)]
    pub fn get_stats(&self, operation: &str, algo: Option<Algorithm>) -> Option<PerformanceStats> {
        let key = format!("{}_{:?}", operation, algo);

        // Use read lock with poison recovery
        match self.metrics.read() {
            Ok(metrics) => metrics.get(&key).map(|m| m.to_stats()),
            Err(poisoned) => {
                log::warn!("{}", translate("log.monitor_read_lock_poisoned"));
                let metrics = poisoned.into_inner();
                metrics.get(&key).map(|m| m.to_stats())
            }
        }
    }

    /// Get all performance statistics
    #[allow(dead_code)]
    pub fn get_all_stats(&self) -> HashMap<String, PerformanceStats> {
        // Use read lock with poison recovery
        match self.metrics.read() {
            Ok(metrics) => metrics
                .iter()
                .map(|(k, v)| (k.clone(), v.to_stats()))
                .collect(),
            Err(poisoned) => {
                log::warn!("{}", translate("log.monitor_read_lock_poisoned"));
                let metrics = poisoned.into_inner();
                metrics
                    .iter()
                    .map(|(k, v)| (k.clone(), v.to_stats()))
                    .collect()
            }
        }
    }

    /// Reset statistics for a specific operation
    #[allow(dead_code)]
    pub fn reset_stats(&self, operation: &str, algo: Option<Algorithm>) {
        let key = format!("{}_{:?}", operation, algo);

        // Use write lock with poison recovery
        match self.metrics.write() {
            Ok(mut metrics) => {
                metrics.remove(&key);
            }
            Err(poisoned) => {
                log::warn!("{}", translate("log.monitor_write_lock_poisoned"));
                let mut metrics = poisoned.into_inner();
                metrics.remove(&key);
            }
        }
    }

    /// Reset all statistics
    #[allow(dead_code)]
    pub fn reset_all_stats(&self) {
        // Use write lock with poison recovery
        match self.metrics.write() {
            Ok(mut metrics) => {
                metrics.clear();
            }
            Err(poisoned) => {
                log::warn!("{}", translate("log.monitor_write_lock_poisoned"));
                let mut metrics = poisoned.into_inner();
                metrics.clear();
            }
        }
    }
}

// === 审计日志 ===

/// 审计日志条目
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditLog {
    /// 操作时间戳
    pub timestamp: DateTime<Utc>,
    /// 操作类型(例如:"KEY_GENERATE"、"ENCRYPT"、"DECRYPT")
    pub operation: String,
    /// 使用的算法(如果适用)
    pub algorithm: Option<Algorithm>,
    /// 密钥 ID(如果适用)
    pub key_id: Option<String>,
    /// 租户 ID(如果适用)
    pub tenant_id: Option<String>,
    /// 操作状态("SUCCESS"、"FAILURE"、"UNAUTHORIZED")
    pub status: String,
    /// 附加详细信息
    pub details: String,
    /// 访问类型(例如:"authorized"、"unauthorized")
    pub access_type: String,
}

/// 基于通道的审计日志记录器,用于减少锁竞争
pub struct AuditLogger {
    sender: Arc<Mutex<Sender<String>>>,
    sync_buffer: Arc<Mutex<Vec<String>>>,
    _handle: Option<thread::JoinHandle<()>>, // 保留句柄以防止线程被丢弃
    fallback_enabled: Arc<Mutex<bool>>,      // 优雅降级标志
}

impl Default for AuditLogger {
    fn default() -> Self {
        Self::new()
    }
}

impl AuditLogger {
    /// Send log entry through channel with fallback to sync buffer
    fn send_with_fallback(&self, json: String) {
        // Try to send via channel first
        match self.sender.lock() {
            Ok(sender) => {
                match sender.send(json.clone()) {
                    Ok(_) => {
                        // Reset fallback flag on successful send
                        if let Ok(mut fallback) = self.fallback_enabled.lock() {
                            *fallback = false;
                        }
                    }
                    Err(_) => {
                        log::warn!("{}", translate("log.audit_channel_closed"));
                        if let Ok(mut fallback) = self.fallback_enabled.lock() {
                            *fallback = true;
                        }
                        // Store in sync buffer as fallback
                        self.store_in_sync_buffer(json);
                    }
                }
            }
            Err(_) => {
                log::warn!("{}", translate("log.audit_sender_lock_failed"));
                if let Ok(mut fallback) = self.fallback_enabled.lock() {
                    *fallback = true;
                }
                // Store in sync buffer as fallback
                self.store_in_sync_buffer(json);
            }
        }
    }

    /// Store log entry in sync buffer
    fn store_in_sync_buffer(&self, json: String) {
        match self.sync_buffer.lock() {
            Ok(mut buf) => {
                if buf.len() < 1000 {
                    buf.push(json);
                }
            }
            Err(poisoned) => {
                log::warn!("{}", translate("log.audit_sync_buffer_poisoned"));
                let mut buf = poisoned.into_inner();
                if buf.len() < 1000 {
                    buf.push(json);
                }
            }
        }
    }

    pub fn new() -> Self {
        let (sender, receiver): (
            std::sync::mpsc::Sender<String>,
            std::sync::mpsc::Receiver<String>,
        ) = channel();

        // Spawn background thread for logging with error recovery
        let handle = thread::spawn(move || {
            for log_entry in receiver {
                log::info!(
                    "{}",
                    translate_with_args("audit.audit_entry", &[("entry", log_entry.as_str())])
                );
            }
            log::warn!("{}", translate("log.audit_background_terminated"));
        });

        Self {
            sender: Arc::new(Mutex::new(sender)),
            sync_buffer: Arc::new(Mutex::new(Vec::with_capacity(100))),
            _handle: Some(handle),
            fallback_enabled: Arc::new(Mutex::new(false)),
        }
    }

    /// 初始化审计日志记录器(向后兼容)
    pub fn init() {
        // 日志记录器已通过 lazy_static 初始化
        log::info!("{}", translate("log.audit_initialized"));
    }

    /// 带租户信息的日志记录(向后兼容)
    pub fn log_with_tenant(
        operation: &str,
        algo: Option<Algorithm>,
        key_id: Option<&str>,
        tenant_id: Option<&str>,
        result: Result<()>,
        access_type: &str,
    ) {
        debug_assert!(!operation.is_empty(), "Operation should not be empty");
        debug_assert!(
            operation.len() <= 100,
            "Operation should not exceed 100 characters"
        );
        debug_assert!(!access_type.is_empty(), "Access type should not be empty");
        debug_assert!(
            access_type.len() <= 50,
            "Access type should not exceed 50 characters"
        );
        if let Some(key_id) = key_id {
            debug_assert!(
                !key_id.is_empty(),
                "Key ID should not be empty when provided"
            );
            debug_assert!(
                key_id.len() <= 256,
                "Key ID should not exceed 256 characters"
            );
        }
        if let Some(tenant_id) = tenant_id {
            debug_assert!(
                !tenant_id.is_empty(),
                "Tenant ID should not be empty when provided"
            );
            debug_assert!(
                tenant_id.len() <= 128,
                "Tenant ID should not exceed 128 characters"
            );
        }

        let entry = AuditLog {
            timestamp: Utc::now(),
            operation: operation.to_string(),
            algorithm: algo,
            key_id: key_id.map(|s| s.to_string()),
            tenant_id: tenant_id.map(|s| s.to_string()),
            status: if result.is_ok() { "SUCCESS" } else { "FAILURE" }.to_string(),
            details: result
                .err()
                .map(|e| sanitize_error_for_log(&e))
                .unwrap_or_default(),
            access_type: access_type.to_string(),
        };

        if let Ok(json) = serde_json::to_string(&entry) {
            // Store in sync buffer for testing
            LOGGER.store_in_sync_buffer(json.clone());

            // Send via channel with fallback
            LOGGER.send_with_fallback(json);
        }
    }

    /// Record a cryptographic operation
    pub fn log(operation: &str, algo: Option<Algorithm>, key_id: Option<&str>, result: Result<()>) {
        let entry = AuditLog {
            timestamp: Utc::now(),
            operation: operation.to_string(),
            algorithm: algo,
            key_id: key_id.map(|s| s.to_string()),
            tenant_id: None,
            status: if result.is_ok() { "SUCCESS" } else { "FAILURE" }.to_string(),
            details: result
                .err()
                .map(|e| sanitize_error_for_log(&e))
                .unwrap_or_default(),
            access_type: "system".to_string(),
        };

        if let Ok(json) = serde_json::to_string(&entry) {
            // Store in sync buffer for testing
            LOGGER.store_in_sync_buffer(json.clone());

            // Send via channel with fallback
            LOGGER.send_with_fallback(json.clone());

            // Also print to stdout for demo
            log::info!(
                "{}",
                translate_with_args("audit.entry", &[("entry", &json)])
            );
        }
    }

    /// Record an authorized access
    #[allow(dead_code)]
    pub fn log_authorized_access(
        operation: &str,
        algo: Option<Algorithm>,
        key_id: Option<&str>,
        tenant_id: Option<&str>,
        details: &str,
        access_type: &str,
    ) {
        let entry = AuditLog {
            timestamp: Utc::now(),
            operation: operation.to_string(),
            algorithm: algo,
            key_id: key_id.map(|s| s.to_string()),
            tenant_id: tenant_id.map(|s| s.to_string()),
            status: "SUCCESS".to_string(),
            details: details.to_string(),
            access_type: access_type.to_string(),
        };

        if let Ok(json) = serde_json::to_string(&entry) {
            // Store in sync buffer for testing
            LOGGER.store_in_sync_buffer(json.clone());

            // Send via channel with fallback
            LOGGER.send_with_fallback(json);
        }
    }

    /// Record an unauthorized access attempt
    pub fn log_unauthorized_access(
        operation: &str,
        algo: Option<Algorithm>,
        key_id: Option<&str>,
        tenant_id: Option<&str>,
        details: &str,
    ) {
        let entry = AuditLog {
            timestamp: Utc::now(),
            operation: operation.to_string(),
            algorithm: algo,
            key_id: key_id.map(|s| s.to_string()),
            tenant_id: tenant_id.map(|s| s.to_string()),
            status: "UNAUTHORIZED".to_string(),
            details: format!("SECURITY ALERT: {}", details),
            access_type: "unauthorized".to_string(),
        };

        if let Ok(json) = serde_json::to_string(&entry) {
            // Update Prometheus security alerts
            SECURITY_ALERTS_TOTAL.inc();

            // Store in sync buffer for testing
            LOGGER.store_in_sync_buffer(json.clone());

            // Send via channel with fallback
            LOGGER.send_with_fallback(json.clone());

            // 记录到安全日志并触发警报
            log::warn!(
                "{}",
                translate_with_args("audit.security_alert", &[("alert", &json)])
            );
        }
    }

    /// Record a key operation
    #[allow(dead_code)]
    pub fn log_key_operation(
        operation: &str,
        algo: Algorithm,
        key_id: &str,
        tenant_id: Option<&str>,
        success: bool,
        details: &str,
    ) {
        let entry = AuditLog {
            timestamp: Utc::now(),
            operation: operation.to_string(),
            algorithm: Some(algo),
            key_id: Some(key_id.to_string()),
            tenant_id: tenant_id.map(|s| s.to_string()),
            status: if success { "SUCCESS" } else { "FAILURE" }.to_string(),
            details: details.to_string(),
            access_type: "key_operation".to_string(),
        };

        if let Ok(json) = serde_json::to_string(&entry) {
            // Store in sync buffer for testing
            LOGGER.store_in_sync_buffer(json.clone());

            // Send via channel with fallback
            LOGGER.send_with_fallback(json.clone());

            // Also print to stdout for demo
            log::info!(
                "{}",
                translate_with_args("audit.entry", &[("entry", &json)])
            );
        }
    }

    /// 获取审计日志缓冲区(用于测试)
    #[allow(dead_code)]
    pub fn get_logs() -> Vec<String> {
        match LOGGER.sync_buffer.lock() {
            Ok(buffer) => {
                let logs = buffer.clone();
                // 增加调试输出
                for (i, log) in logs.iter().enumerate() {
                    if log.contains("KEY_GENERATE") {
                        log::debug!(
                            "{}",
                            translate_with_args(
                                "audit.key_generate_found",
                                &[("index", &i.to_string())]
                            )
                        );
                    }
                }
                logs
            }
            Err(poisoned) => {
                log::warn!("{}", translate("log.audit_sync_buffer_poisoned"));
                let buffer = poisoned.into_inner();
                buffer.clone()
            }
        }
    }

    /// 清空审计日志缓冲区(用于测试)
    #[allow(dead_code)]
    pub fn clear_logs() {
        match LOGGER.sync_buffer.lock() {
            Ok(mut buffer) => buffer.clear(),
            Err(poisoned) => {
                log::warn!("{}", translate("log.audit_sync_buffer_poisoned"));
                let mut buffer = poisoned.into_inner();
                buffer.clear();
            }
        }
    }

    /// 导出 Prometheus 指标
    #[allow(dead_code)]
    pub fn gather_metrics() -> Result<String> {
        use prometheus::Encoder;
        let encoder = prometheus::TextEncoder::new();
        let metric_families = REGISTRY.gather();
        let mut buffer = Vec::new();
        encoder
            .encode(&metric_families, &mut buffer)
            .map_err(|e| CryptoError::InternalError(format!("Failed to encode metrics: {}", e)))?;
        String::from_utf8(buffer)
            .map_err(|e| CryptoError::InternalError(format!("Invalid UTF-8 in metrics: {}", e)))
    }

    /// 启动 Prometheus 指标导出器
    ///
    /// # 参数
    /// * `port` - 导出器监听的端口
    #[allow(dead_code)]
    pub fn start_exporter(port: u16) {
        use std::io::{Read, Write};
        use std::net::SocketAddr;
        use std::net::TcpListener;
        use std::thread;

        // 注册指标
        register_metrics();

        let addr = SocketAddr::from(([127, 0, 0, 1], port));

        thread::spawn(move || {
            let addr_str = addr.to_string();
            let listener = match TcpListener::bind(addr) {
                Ok(l) => l,
                Err(e) => {
                    log::error!(
                        "{}",
                        translate_with_args(
                            "audit.prometheus_bind_failed",
                            &[("addr", &addr_str), ("error", &e.to_string())]
                        )
                    );
                    return;
                }
            };

            log::info!(
                "{}",
                translate_with_args("audit.prometheus_listening", &[("addr", &addr_str)])
            );

            for stream in listener.incoming() {
                match stream {
                    Ok(mut stream) => {
                        let mut buffer = [0; 1024];
                        match stream.read(&mut buffer) {
                            Ok(n) if n > 0 => {
                                let metrics = match Self::gather_metrics() {
                                    Ok(m) => m,
                                    Err(e) => {
                                        log::error!(
                                            "{}",
                                            translate_with_args(
                                                "audit.prometheus_gather_failed",
                                                &[("error", &e.to_string())]
                                            )
                                        );
                                        let error_msg = translate_with_args(
                                            "audit.prometheus_gather_failed",
                                            &[("error", &e.to_string())],
                                        );
                                        let response = format!(
                                            "HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                                            error_msg.len(),
                                            error_msg
                                        );
                                        if let Err(write_err) =
                                            stream.write_all(response.as_bytes())
                                        {
                                            log::error!(
                                                "{}",
                                                translate_with_args(
                                                    "audit.prometheus_write_response_failed",
                                                    &[("error", &write_err.to_string())]
                                                )
                                            );
                                        }
                                        let _ = stream.flush();
                                        continue;
                                    }
                                };
                                let response = format!(
                                    "HTTP/1.1 200 OK\r\nContent-Type: text/plain; version=0.0.4\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                                    metrics.len(),
                                    metrics
                                );

                                if let Err(e) = stream.write_all(response.as_bytes()) {
                                    log::error!(
                                        "{}",
                                        translate_with_args(
                                            "audit.prometheus_write_response_failed",
                                            &[("error", &e.to_string())]
                                        )
                                    );
                                }
                                let _ = stream.flush();
                            }
                            _ => {}
                        }
                    }
                    Err(e) => {
                        log::error!(
                            "{}",
                            translate_with_args(
                                "audit.prometheus_accept_failed",
                                &[("error", &e.to_string())]
                            )
                        );
                    }
                }
            }
        });
    }
}

// 全局性能监控函数
#[allow(dead_code)]
pub fn record_operation(
    operation: &str,
    algo: Option<Algorithm>,
    latency_us: u64,
    data_size: usize,
    cache_hit: bool,
) {
    PERFORMANCE_MONITOR.record_operation(operation, algo, latency_us, data_size, cache_hit);
}
#[allow(dead_code)]
pub fn get_performance_stats(operation: &str, algo: Option<Algorithm>) -> Option<PerformanceStats> {
    PERFORMANCE_MONITOR.get_stats(operation, algo)
}

#[allow(dead_code)]
pub fn get_all_performance_stats() -> HashMap<String, PerformanceStats> {
    PERFORMANCE_MONITOR.get_all_stats()
}

#[allow(dead_code)]
pub fn reset_performance_stats(operation: &str, algo: Option<Algorithm>) {
    PERFORMANCE_MONITOR.reset_stats(operation, algo);
}

#[allow(dead_code)]
pub fn reset_all_performance_stats() {
    PERFORMANCE_MONITOR.reset_all_stats();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;
    use std::thread;

    #[test]
    fn test_performance_monitor_basic() {
        let monitor = PerformanceMonitor::new();

        // Record some operations
        monitor.record_operation("encrypt", Some(Algorithm::AES256GCM), 1000, 1024, true);
        monitor.record_operation("encrypt", Some(Algorithm::AES256GCM), 1200, 1024, false);
        monitor.record_operation("decrypt", Some(Algorithm::AES256GCM), 800, 1024, true);

        // Get stats
        let stats = monitor
            .get_stats("encrypt", Some(Algorithm::AES256GCM))
            .unwrap();
        assert_eq!(stats.total_operations, 2);
        assert!(stats.avg_latency_us > 0.0);
        assert!(stats.avg_throughput_ops_per_sec > 0.0);
    }

    #[test]
    fn test_performance_monitor_multiple_operations() {
        let monitor = PerformanceMonitor::new();

        // Record multiple operations concurrently
        let handles: Vec<_> = (0..100)
            .map(|i| {
                let monitor = monitor.clone();
                thread::spawn(move || {
                    monitor.record_operation(
                        "test_op",
                        Some(Algorithm::AES256GCM),
                        1000 + (i * 10) as u64,
                        1024,
                        i % 2 == 0,
                    );
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        let stats = monitor
            .get_stats("test_op", Some(Algorithm::AES256GCM))
            .unwrap();
        assert_eq!(stats.total_operations, 100);
        assert!(stats.avg_latency_us > 0.0);
    }

    #[test]
    fn test_performance_stats_reset() {
        let monitor = PerformanceMonitor::new();

        // Record some operations
        monitor.record_operation("encrypt", Some(Algorithm::AES256GCM), 1000, 1024, true);

        // Verify stats exist
        let stats = monitor.get_stats("encrypt", Some(Algorithm::AES256GCM));
        assert!(stats.is_some());

        // Reset stats
        monitor.reset_stats("encrypt", Some(Algorithm::AES256GCM));

        // Verify stats are gone
        let stats = monitor.get_stats("encrypt", Some(Algorithm::AES256GCM));
        assert!(stats.is_none());
    }

    #[test]
    fn test_audit_logger_basic() {
        // Use a unique key for this test to avoid interference from other tests running in parallel
        let test_key = format!(
            "test_key_basic_{}",
            Utc::now().timestamp_nanos_opt().unwrap_or(0)
        );

        // Capture initial logs to establish baseline and filter out logs from other tests
        let initial_logs: HashSet<String> = AuditLogger::get_logs().into_iter().collect();
        println!("Initial log count: {}", initial_logs.len());

        // Log some operations with our unique key
        AuditLogger::log(
            "KEY_GENERATE",
            Some(Algorithm::AES256GCM),
            Some(&test_key),
            Ok(()),
        );

        AuditLogger::log(
            "ENCRYPT",
            Some(Algorithm::AES256GCM),
            Some(&test_key),
            Err(CryptoError::InternalError("test error".into())),
        );

        // Get all logs after our operations
        let all_logs: HashSet<String> = AuditLogger::get_logs().into_iter().collect();
        println!("Total log count after operations: {}", all_logs.len());

        // Filter to only logs created by this test (new logs not in initial set)
        let new_logs: Vec<String> = all_logs.difference(&initial_logs).cloned().collect();
        println!("New logs added by this test: {}", new_logs.len());

        // Parse new logs and find the ones we're interested in by filtering for our unique key
        let mut keygen_logs = Vec::with_capacity(8);
        let mut encrypt_logs = Vec::with_capacity(16);
        let mut debug_logs = Vec::with_capacity(32);

        for log_str in &new_logs {
            if let Ok(audit_log) = serde_json::from_str::<AuditLog>(log_str) {
                if audit_log.key_id.as_ref() == Some(&test_key) {
                    debug_logs.push(format!(
                        "Found log: operation={}, key_id={:?}, status={}",
                        audit_log.operation, audit_log.key_id, audit_log.status
                    ));
                    if audit_log.operation == "KEY_GENERATE" {
                        keygen_logs.push(log_str.clone());
                    } else if audit_log.operation == "ENCRYPT" {
                        encrypt_logs.push(log_str.clone());
                    }
                }
            }
        }

        // Debug output
        println!("Debug logs for key {}:", test_key);
        for debug_log in debug_logs {
            println!("  {}", debug_log);
        }
        println!("Total new logs in buffer: {}", new_logs.len());
        println!("KEY_GENERATE logs found: {}", keygen_logs.len());
        println!("ENCRYPT logs found: {}", encrypt_logs.len());

        // Verify we have at least the logs we expect
        assert!(
            !keygen_logs.is_empty(),
            "Should have at least 1 KEY_GENERATE log for key {}. Found {} total new logs, {} matching keygen filter",
            test_key,
            new_logs.len(),
            keygen_logs.len()
        );
        assert!(
            !encrypt_logs.is_empty(),
            "Should have at least 1 ENCRYPT log for {}",
            test_key
        );

        // Parse and verify one of the KEY_GENERATE logs
        let audit_log: AuditLog = serde_json::from_str(&keygen_logs[0]).unwrap();
        assert_eq!(audit_log.operation, "KEY_GENERATE");
        assert_eq!(audit_log.status, "SUCCESS");
    }

    #[test]
    fn test_audit_logger_concurrent() {
        // Clear logs first to ensure clean state
        AuditLogger::clear_logs();

        // Use a unique prefix for this test
        let test_prefix = format!(
            "concurrent_key_{}",
            Utc::now().timestamp_nanos_opt().unwrap_or(0)
        );
        let test_prefix_clone = test_prefix.clone();

        // Log operations concurrently
        let handles: Vec<_> = (0..100)
            .map(|i| {
                let prefix = test_prefix_clone.clone();
                thread::spawn(move || {
                    AuditLogger::log(
                        "test_op",
                        Some(Algorithm::AES256GCM),
                        Some(&format!("{}_{}", prefix, i)),
                        if i % 2 == 0 {
                            Ok(())
                        } else {
                            Err(CryptoError::InternalError("test error".into()))
                        },
                    );
                })
            })
            .collect();

        for handle in handles {
            handle.join().unwrap();
        }

        // Wait for logs to be flushed
        thread::sleep(std::time::Duration::from_millis(500));

        let logs = AuditLogger::get_logs();

        // Count logs belonging to this test run
        let test_logs: Vec<_> = logs
            .iter()
            .filter(|log| log.contains(&test_prefix))
            .collect();

        // Verify that we have a reasonable number of logs from this test
        // Due to test parallelism, we might not get exactly 100, but we should have most of them
        assert!(
            test_logs.len() >= 90,
            "Expected at least 90 logs for this test, found {}. Total logs in buffer: {}",
            test_logs.len(),
            logs.len()
        );

        // Verify the pattern of operations: test_op with alternating success/failure
        let success_count = test_logs
            .iter()
            .filter(|log| log.contains("SUCCESS"))
            .count();
        let failure_count = test_logs
            .iter()
            .filter(|log| log.contains("FAILURE"))
            .count();

        // With 100 operations alternating success/failure, we should have roughly 50/50 split
        // Allow for some variation due to potential log loss from test interference
        assert!(
            (40..=60).contains(&success_count),
            "Expected success count between 40-60, got {}. Total test logs: {}",
            success_count,
            test_logs.len()
        );
        assert!(
            (40..=60).contains(&failure_count),
            "Expected failure count between 40-60, got {}. Total test logs: {}",
            failure_count,
            test_logs.len()
        );

        // Verify that we have both success and failure logs
        assert!(success_count > 0, "Expected at least one success log");
        assert!(failure_count > 0, "Expected at least one failure log");
    }

    #[test]
    fn test_audit_logger_unauthorized_access() {
        // Clear logs first
        AuditLogger::clear_logs();

        // Log unauthorized access
        AuditLogger::log_unauthorized_access(
            "KEY_ACCESS",
            Some(Algorithm::AES256GCM),
            Some("test_key"),
            Some("tenant_123"),
            "Test unauthorized access",
        );

        // Get logs
        let logs = AuditLogger::get_logs();
        // Check that at least 1 log is present (other tests might be running concurrently)
        assert!(
            !logs.is_empty(),
            "Expected at least 1 log, got {}",
            logs.len()
        );

        // Find the unauthorized access log
        let unauthorized_log = logs
            .iter()
            .find(|log| log.contains("UNAUTHORIZED"))
            .expect("Should find an unauthorized access log");

        // Parse and verify
        let audit_log: AuditLog = serde_json::from_str(unauthorized_log).unwrap();
        assert_eq!(audit_log.status, "UNAUTHORIZED");
        assert!(audit_log.details.contains("SECURITY ALERT"));
        assert_eq!(audit_log.tenant_id, Some("tenant_123".to_string()));
    }

    #[test]
    fn test_performance_monitor_cache_simulation() {
        let monitor = PerformanceMonitor::new();

        // Simulate cache hits and misses
        for i in 0..100 {
            monitor.record_operation(
                "encrypt",
                Some(Algorithm::AES256GCM),
                1000,
                1024,
                i % 3 == 0, // 33% cache hit rate
            );
        }

        let stats = monitor
            .get_stats("encrypt", Some(Algorithm::AES256GCM))
            .unwrap();
        assert_eq!(stats.total_operations, 100);
        assert!(stats.avg_cache_hit_rate > 0.3 && stats.avg_cache_hit_rate < 0.4);
    }

    #[test]
    fn test_performance_trend_calculation() {
        let monitor = PerformanceMonitor::new();

        // Record operations with improving performance
        for i in 0..50 {
            monitor.record_operation(
                "encrypt",
                Some(Algorithm::AES256GCM),
                2000 - (i * 20), // Decreasing latency = improving performance
                1024,
                true,
            );
        }

        let stats = monitor
            .get_stats("encrypt", Some(Algorithm::AES256GCM))
            .unwrap();
        assert_eq!(stats.performance_trend, "stable"); // Should be stable based on throughput calculation
    }

    #[test]
    fn test_recent_metrics_retrieval() {
        let monitor = PerformanceMonitor::new();

        // Record operations for different algorithms
        monitor.record_operation("encrypt", Some(Algorithm::AES128GCM), 1000, 1024, true);
        monitor.record_operation("encrypt", Some(Algorithm::AES256GCM), 1200, 1024, false);
        monitor.record_operation("decrypt", Some(Algorithm::SM4GCM), 800, 1024, true);

        // Get all stats
        let all_stats = monitor.get_all_stats();
        assert_eq!(all_stats.len(), 3);

        // Verify each operation has stats
        assert!(all_stats.contains_key(&format!("encrypt_{:?}", Some(Algorithm::AES128GCM))));
        assert!(all_stats.contains_key(&format!("encrypt_{:?}", Some(Algorithm::AES256GCM))));
        assert!(all_stats.contains_key(&format!("decrypt_{:?}", Some(Algorithm::SM4GCM))));
    }

    #[test]
    fn test_global_performance_functions() {
        // Reset all stats first
        reset_all_performance_stats();

        // Use global functions
        record_operation("test_op", Some(Algorithm::AES256GCM), 1000, 1024, true);

        let stats = get_performance_stats("test_op", Some(Algorithm::AES256GCM));
        assert!(stats.is_some());
        assert_eq!(stats.unwrap().total_operations, 1);

        // Test reset
        reset_performance_stats("test_op", Some(Algorithm::AES256GCM));
        let stats = get_performance_stats("test_op", Some(Algorithm::AES256GCM));
        assert!(stats.is_none());
    }
}