kindly-guard-server 0.11.14

KindlyGuard MCP server - Enterprise-grade security for AI model interactions
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
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
// Copyright 2025 Kindly Software Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Audit logging system for compliance and security monitoring
//!
//! This module provides a trait-based audit architecture that allows
//! different audit backends while maintaining compliance requirements.
//!
//! # Compliance Standards Support
//!
//! The audit system is designed to meet requirements for:
//! - **GDPR** (General Data Protection Regulation) - EU privacy regulation
//! - **SOC2** (Service Organization Control 2) - Security and availability standards
//! - **HIPAA** (Health Insurance Portability and Accountability Act) - Healthcare data protection
//! - **PCI DSS** (Payment Card Industry Data Security Standard) - Payment processing security
//! - **ISO 27001** - Information security management standards
//!
//! # Key Features
//!
//! - Immutable audit trail with cryptographic integrity verification
//! - Configurable retention policies for compliance
//! - Export capabilities for regulatory reporting
//! - Real-time security event monitoring
//! - Tamper-evident logging with integrity checks
//!
//! # Usage Example
//!
//! ```rust,no_run
//! use kindly_guard_server::audit::{
//!     AuditEventBuilder, AuditEventType, AuditSeverity, AuditLogger
//! };
//!
//! # async fn example(logger: &dyn AuditLogger) -> anyhow::Result<()> {
//! // Log a security event
//! let event = AuditEventBuilder::new(
//!     AuditEventType::ThreatDetected {
//!         client_id: "client-123".to_string(),
//!         threat_count: 5,
//!     },
//!     AuditSeverity::Warning,
//! )
//! .ip_address("192.168.1.100".to_string())
//! .tag("security".to_string())
//! .tag("automated-detection".to_string())
//! .build();
//!
//! logger.log(event).await?;
//! # Ok(())
//! # }
//! ```

use anyhow::Result;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

#[cfg(feature = "enhanced")]
pub mod enhanced;
pub mod file;
pub mod memory;
pub mod neutralization;

// Re-exports
pub use file::FileAuditLogger;
pub use memory::InMemoryAuditLogger;

/// Audit event identifier
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AuditEventId(pub String);

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

impl AuditEventId {
    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4().to_string())
    }
}

/// Audit event severity levels
///
/// Severity levels determine the importance and urgency of audit events.
/// They are used for filtering, alerting, and compliance reporting.
///
/// # Compliance Mapping
///
/// Different compliance standards require logging at different severity levels:
/// - **SOC2**: All levels required, with Critical events requiring immediate notification
/// - **PCI DSS**: Error and Critical events must trigger security alerts
/// - **HIPAA**: All access events (regardless of severity) must be logged
/// - **ISO 27001**: Critical events require incident response procedures
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuditSeverity {
    /// Informational events for routine operations
    ///
    /// **When to use:**
    /// - Successful authentication/authorization
    /// - Configuration changes (non-security)
    /// - Normal system lifecycle events
    /// - Successful API calls
    ///
    /// **Compliance notes:**
    /// - GDPR: Required for data access logs
    /// - SOC2: Required for access tracking
    /// - Retention: Typically 30-90 days
    Info,

    /// Warning events that may indicate potential issues
    ///
    /// **When to use:**
    /// - Failed authentication attempts (below threshold)
    /// - Rate limiting triggered
    /// - Deprecated API usage
    /// - Performance degradation
    ///
    /// **Compliance notes:**
    /// - PCI DSS: Must be reviewed daily
    /// - SOC2: Requires monitoring and trend analysis
    /// - Retention: Minimum 90 days
    Warning,

    /// Error events indicating operational problems
    ///
    /// **When to use:**
    /// - System errors that don't compromise security
    /// - Service unavailability
    /// - Integration failures
    /// - Data validation errors
    ///
    /// **Compliance notes:**
    /// - SOC2: Must be included in incident reports
    /// - ISO 27001: Requires root cause analysis
    /// - Retention: Minimum 1 year
    Error,

    /// Critical security events requiring immediate attention
    ///
    /// **When to use:**
    /// - Security threats detected and blocked
    /// - Multiple authentication failures (brute force)
    /// - Data breach attempts
    /// - System compromise indicators
    /// - Unauthorized access attempts
    ///
    /// **Compliance notes:**
    /// - ALL standards: Immediate notification required
    /// - PCI DSS: Must trigger security incident response
    /// - HIPAA: Must be reported within 24-72 hours
    /// - SOC2: Requires executive notification
    /// - Retention: Minimum 3-7 years
    Critical,
}

/// Audit event types
///
/// Each event type captures specific security-relevant activities with fields
/// required for compliance reporting and forensic analysis.
///
/// # Compliance Requirements Matrix
///
/// | Event Category | GDPR | SOC2 | HIPAA | PCI DSS | ISO 27001 |
/// |----------------|------|------|-------|---------|-----------|
/// | Authentication | ✓    | ✓    | ✓     | ✓       | ✓         |
/// | Authorization  | ✓    | ✓    | ✓     | ✓       | ✓         |
/// | Security       | ○    | ✓    | ✓     | ✓       | ✓         |
/// | Configuration  | ○    | ✓    | ○     | ✓       | ✓         |
/// | System         | ○    | ✓    | ○     | ○       | ✓         |
///
/// Legend: ✓ = Required, ○ = Recommended
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditEventType {
    // ==================== Authentication Events ====================
    /// Successful authentication event
    ///
    /// **Triggered when:** User successfully authenticates to the system
    ///
    /// **Required fields:**
    /// - `user_id`: Unique identifier of the authenticated user (required)
    ///
    /// **Additional context to capture:**
    /// - `authentication_method`: (e.g., "password", "mfa", "sso")
    /// - `session_id`: New session identifier
    /// - `ip_address`: Source IP (auto-captured)
    /// - `user_agent`: Client information (auto-captured)
    ///
    /// **Compliance requirements:**
    /// - GDPR: Required for access logs and user activity tracking
    /// - SOC2: Required for access control monitoring (AC-2)
    /// - HIPAA: Required for user activity tracking (§164.312(b))
    /// - PCI DSS: Required for individual user access (8.1.1)
    /// - ISO 27001: Required for access control (A.9.2.1)
    ///
    /// **Typical severity:** Info
    AuthSuccess { user_id: String },

    /// Failed authentication attempt
    ///
    /// **Triggered when:** Authentication attempt fails for any reason
    ///
    /// **Required fields:**
    /// - `user_id`: Attempted username (optional - may be None for invalid users)
    /// - `reason`: Specific failure reason (required)
    ///
    /// **Additional context to capture:**
    /// - `attempt_count`: Number of consecutive failures
    /// - `authentication_method`: Method attempted
    /// - `ip_address`: Source IP (auto-captured)
    /// - `lockout_triggered`: Whether account was locked
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for security monitoring (CA-7)
    /// - HIPAA: Required for login monitoring (§164.308(a)(5)(ii)(C))
    /// - PCI DSS: Required after 6 attempts (8.1.6)
    /// - ISO 27001: Required for security incident detection
    ///
    /// **Typical severity:** Warning (Error if repeated, Critical if threshold exceeded)
    AuthFailure {
        user_id: Option<String>,
        reason: String,
    },

    // ==================== Authorization Events ====================
    /// Successful resource access
    ///
    /// **Triggered when:** User successfully accesses a protected resource
    ///
    /// **Required fields:**
    /// - `user_id`: User performing the access (required)
    /// - `resource`: Resource identifier/path (required)
    ///
    /// **Additional context to capture:**
    /// - `action`: Specific action performed (read/write/delete)
    /// - `resource_type`: Type of resource accessed
    /// - `data_classification`: Sensitivity level of data
    ///
    /// **Compliance requirements:**
    /// - GDPR: Required for personal data access (Article 30)
    /// - SOC2: Required for logical access monitoring
    /// - HIPAA: Required for PHI access logs (§164.312(a)(1))
    /// - PCI DSS: Required for cardholder data access (10.2.1)
    ///
    /// **Typical severity:** Info
    AccessGranted { user_id: String, resource: String },

    /// Denied resource access attempt
    ///
    /// **Triggered when:** User is denied access to a protected resource
    ///
    /// **Required fields:**
    /// - `user_id`: User attempting access (required)
    /// - `resource`: Resource identifier/path (required)
    /// - `reason`: Denial reason (required)
    ///
    /// **Additional context to capture:**
    /// - `required_permission`: Permission that was missing
    /// - `user_permissions`: Current user permissions
    /// - `escalation_attempted`: If privilege escalation was detected
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for unauthorized access attempts
    /// - HIPAA: Required for access violation tracking
    /// - PCI DSS: Required for all access denials (10.2.4)
    /// - ISO 27001: Required for security monitoring
    ///
    /// **Typical severity:** Warning (Critical if privilege escalation detected)
    AccessDenied {
        user_id: String,
        resource: String,
        reason: String,
    },

    // ==================== Security Events ====================
    /// Security threat detected
    ///
    /// **Triggered when:** System detects potential security threats
    ///
    /// **Required fields:**
    /// - `client_id`: Client/session where threat originated (required)
    /// - `threat_count`: Number of threats detected (required)
    ///
    /// **Additional context to capture:**
    /// - `threat_types`: Array of specific threat types detected
    /// - `threat_details`: Detailed threat information
    /// - `risk_score`: Calculated risk level (0-100)
    /// - `automated_response`: Actions taken automatically
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for security monitoring (SI-4)
    /// - HIPAA: Required for malicious software detection
    /// - PCI DSS: Required for intrusion detection (11.5)
    /// - ISO 27001: Required for security event logging
    ///
    /// **Typical severity:** Warning to Critical (based on threat severity)
    ThreatDetected {
        client_id: String,
        threat_count: u32,
    },

    /// Security threat blocked
    ///
    /// **Triggered when:** System successfully blocks a security threat
    ///
    /// **Required fields:**
    /// - `client_id`: Client/session where threat originated (required)
    /// - `threat_type`: Type of threat blocked (required)
    ///
    /// **Additional context to capture:**
    /// - `block_method`: How the threat was blocked
    /// - `threat_signature`: Pattern/signature that matched
    /// - `confidence_score`: Detection confidence (0-100)
    /// - `false_positive_probability`: Likelihood of false positive
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for incident response (IR-4)
    /// - PCI DSS: Required for security controls (6.6)
    /// - ISO 27001: Required for security control effectiveness
    ///
    /// **Typical severity:** Critical
    ThreatBlocked {
        client_id: String,
        threat_type: String,
    },

    // ==================== Neutralization Events ====================
    /// Threat neutralization initiated
    ///
    /// **Triggered when:** System begins automated threat neutralization
    ///
    /// **Required fields:**
    /// - `client_id`: Client being protected (required)
    /// - `threat_id`: Unique threat identifier (required)
    /// - `threat_type`: Type of threat being neutralized (required)
    ///
    /// **Additional context to capture:**
    /// - `neutralization_strategy`: Method being used
    /// - `estimated_duration`: Expected completion time
    /// - `impact_assessment`: Potential user impact
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for automated response tracking
    /// - ISO 27001: Required for incident handling (A.16.1)
    ///
    /// **Typical severity:** Warning
    NeutralizationStarted {
        client_id: String,
        threat_id: String,
        threat_type: String,
    },

    /// Threat neutralization completed successfully
    ///
    /// **Triggered when:** Threat neutralization completes successfully
    ///
    /// **Required fields:**
    /// - `client_id`: Client that was protected (required)
    /// - `threat_id`: Unique threat identifier (required)
    /// - `action`: Specific action taken (required)
    /// - `duration_ms`: Time taken in milliseconds (required)
    ///
    /// **Additional context to capture:**
    /// - `effectiveness_score`: How well the threat was neutralized
    /// - `side_effects`: Any unintended consequences
    /// - `rollback_available`: Whether action can be reversed
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for incident resolution tracking
    /// - ISO 27001: Required for corrective action records
    ///
    /// **Typical severity:** Info
    NeutralizationCompleted {
        client_id: String,
        threat_id: String,
        action: String,
        duration_ms: u64,
    },

    /// Threat neutralization failed
    ///
    /// **Triggered when:** Neutralization attempt fails
    ///
    /// **Required fields:**
    /// - `client_id`: Client affected (required)
    /// - `threat_id`: Unique threat identifier (required)
    /// - `error`: Error description (required)
    ///
    /// **Additional context to capture:**
    /// - `fallback_action`: Alternative action taken
    /// - `manual_intervention_required`: Whether human action needed
    /// - `threat_persists`: Whether threat is still active
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for incident escalation
    /// - ISO 27001: Required for control failure documentation
    ///
    /// **Typical severity:** Error to Critical
    NeutralizationFailed {
        client_id: String,
        threat_id: String,
        error: String,
    },

    /// Neutralization skipped by policy
    ///
    /// **Triggered when:** Neutralization skipped due to policy/configuration
    ///
    /// **Required fields:**
    /// - `client_id`: Client affected (required)
    /// - `threat_id`: Unique threat identifier (required)
    /// - `reason`: Why neutralization was skipped (required)
    ///
    /// **Additional context to capture:**
    /// - `policy_name`: Specific policy that prevented action
    /// - `override_available`: Whether manual override possible
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for policy compliance tracking
    ///
    /// **Typical severity:** Warning
    NeutralizationSkipped {
        client_id: String,
        threat_id: String,
        reason: String,
    },

    /// Neutralization action rolled back
    ///
    /// **Triggered when:** Previous neutralization is reversed
    ///
    /// **Required fields:**
    /// - `client_id`: Client affected (required)
    /// - `threat_id`: Unique threat identifier (required)
    /// - `reason`: Rollback reason (required)
    ///
    /// **Additional context to capture:**
    /// - `original_action`: What was rolled back
    /// - `rollback_complete`: Whether fully reversed
    /// - `initiated_by`: Automatic or manual rollback
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for change management
    /// - ISO 27001: Required for corrective action tracking
    ///
    /// **Typical severity:** Warning
    NeutralizationRolledBack {
        client_id: String,
        threat_id: String,
        reason: String,
    },

    // ==================== Rate Limiting Events ====================
    /// Rate limit exceeded
    ///
    /// **Triggered when:** Client exceeds configured rate limits
    ///
    /// **Required fields:**
    /// - `client_id`: Client that triggered limit (required)
    /// - `limit_type`: Type of limit exceeded (required)
    ///
    /// **Additional context to capture:**
    /// - `limit_value`: The limit that was exceeded
    /// - `current_value`: Current usage value
    /// - `reset_time`: When limit will reset
    /// - `blocked_requests`: Number of requests blocked
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for availability monitoring
    /// - PCI DSS: Required for DoS protection (6.6)
    ///
    /// **Typical severity:** Warning
    RateLimitTriggered {
        client_id: String,
        limit_type: String,
    },

    // ==================== Configuration Events ====================
    /// Configuration modified
    ///
    /// **Triggered when:** System configuration is changed
    ///
    /// **Required fields:**
    /// - `changed_by`: User/system that made change (required)
    /// - `changes`: Map of changed settings (required)
    ///
    /// **Additional context to capture:**
    /// - `change_reason`: Business justification
    /// - `approval_ticket`: Change management reference
    /// - `rollback_plan`: How to reverse if needed
    /// - `security_impact`: Security implications
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for change management (CC6.1)
    /// - PCI DSS: Required for configuration tracking (2.2)
    /// - ISO 27001: Required for change control (A.12.1.2)
    ///
    /// **Typical severity:** Info (Warning for security settings)
    ConfigChanged {
        changed_by: String,
        changes: HashMap<String, String>,
    },

    /// Configuration reloaded
    ///
    /// **Triggered when:** Configuration is reloaded from source
    ///
    /// **Required fields:**
    /// - `success`: Whether reload succeeded (required)
    /// - `error`: Error message if failed (optional)
    ///
    /// **Additional context to capture:**
    /// - `trigger`: What initiated the reload
    /// - `config_version`: New configuration version
    /// - `validation_results`: Configuration validation outcome
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for operational monitoring
    ///
    /// **Typical severity:** Info (Error if failed)
    ConfigReloaded {
        success: bool,
        error: Option<String>,
    },

    // ==================== Plugin Events ====================
    /// Plugin loaded
    ///
    /// **Triggered when:** Security plugin is loaded
    ///
    /// **Required fields:**
    /// - `plugin_id`: Unique plugin identifier (required)
    /// - `plugin_name`: Human-readable name (required)
    ///
    /// **Additional context to capture:**
    /// - `plugin_version`: Version information
    /// - `plugin_vendor`: Plugin creator/vendor
    /// - `plugin_signature`: Digital signature status
    /// - `capabilities`: What the plugin can access
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for third-party management
    /// - ISO 27001: Required for supplier relationships
    ///
    /// **Typical severity:** Info
    PluginLoaded {
        plugin_id: String,
        plugin_name: String,
    },

    /// Plugin unloaded
    ///
    /// **Triggered when:** Security plugin is unloaded
    ///
    /// **Required fields:**
    /// - `plugin_id`: Unique plugin identifier (required)
    /// - `reason`: Why plugin was unloaded (required)
    ///
    /// **Additional context to capture:**
    /// - `initiated_by`: Manual or automatic unload
    /// - `cleanup_status`: Whether resources were freed
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for component lifecycle tracking
    ///
    /// **Typical severity:** Info (Warning if error-triggered)
    PluginUnloaded { plugin_id: String, reason: String },

    /// Plugin error
    ///
    /// **Triggered when:** Plugin encounters an error
    ///
    /// **Required fields:**
    /// - `plugin_id`: Plugin that errored (required)
    /// - `error`: Error description (required)
    ///
    /// **Additional context to capture:**
    /// - `error_code`: Specific error code
    /// - `stack_trace`: Technical details (sanitized)
    /// - `recovery_action`: Automatic recovery attempted
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for third-party monitoring
    ///
    /// **Typical severity:** Error
    PluginError { plugin_id: String, error: String },

    // ==================== System Events ====================
    /// Server started
    ///
    /// **Triggered when:** Security server starts up
    ///
    /// **Required fields:**
    /// - `version`: Server version (required)
    ///
    /// **Additional context to capture:**
    /// - `startup_time_ms`: Time to become operational
    /// - `config_source`: Where configuration was loaded from
    /// - `features_enabled`: Active feature flags
    /// - `security_mode`: Current security posture
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for availability tracking
    /// - ISO 27001: Required for operational procedures
    ///
    /// **Typical severity:** Info
    ServerStarted { version: String },

    /// Server stopped
    ///
    /// **Triggered when:** Security server shuts down
    ///
    /// **Required fields:**
    /// - `reason`: Shutdown reason (required)
    ///
    /// **Additional context to capture:**
    /// - `shutdown_type`: Graceful or forced
    /// - `active_connections`: Connections at shutdown
    /// - `cleanup_complete`: Whether cleanup finished
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for availability tracking
    /// - ISO 27001: Required for operational procedures
    ///
    /// **Typical severity:** Info (Error if unexpected)
    ServerStopped { reason: String },

    /// System error
    ///
    /// **Triggered when:** System-level error occurs
    ///
    /// **Required fields:**
    /// - `component`: System component affected (required)
    /// - `error`: Error description (required)
    ///
    /// **Additional context to capture:**
    /// - `error_type`: Category of error
    /// - `impact`: User/system impact assessment
    /// - `auto_recovery`: Whether self-healing attempted
    ///
    /// **Compliance requirements:**
    /// - SOC2: Required for system monitoring
    /// - ISO 27001: Required for incident management
    ///
    /// **Typical severity:** Error to Critical
    SystemError { component: String, error: String },

    // ==================== Custom Events ====================
    /// Custom audit event
    ///
    /// **Triggered when:** Application needs to log custom security events
    ///
    /// **Required fields:**
    /// - `event_type`: Custom event type name (required)
    /// - `data`: Event-specific data (required)
    ///
    /// **Additional context to capture:**
    /// - Should follow same context patterns as standard events
    /// - Must include compliance-relevant fields
    ///
    /// **Compliance requirements:**
    /// - Must map to appropriate compliance categories
    /// - Must include required fields for relevant standards
    ///
    /// **Typical severity:** Varies by event type
    Custom {
        event_type: String,
        data: serde_json::Value,
    },
}

/// Audit event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEvent {
    /// Unique event ID
    pub id: AuditEventId,
    /// Event timestamp
    pub timestamp: DateTime<Utc>,
    /// Event type
    pub event_type: AuditEventType,
    /// Event severity
    pub severity: AuditSeverity,
    /// Client/session ID if applicable
    pub client_id: Option<String>,
    /// IP address if applicable
    pub ip_address: Option<String>,
    /// User agent if applicable
    pub user_agent: Option<String>,
    /// Additional context
    pub context: HashMap<String, serde_json::Value>,
    /// Event tags for filtering
    pub tags: Vec<String>,
}

impl AuditEvent {
    /// Create a new audit event
    pub fn new(event_type: AuditEventType, severity: AuditSeverity) -> Self {
        Self {
            id: AuditEventId::new(),
            timestamp: Utc::now(),
            event_type,
            severity,
            client_id: None,
            ip_address: None,
            user_agent: None,
            context: HashMap::new(),
            tags: Vec::new(),
        }
    }

    /// Set client ID
    pub fn with_client_id(mut self, client_id: String) -> Self {
        self.client_id = Some(client_id);
        self
    }

    /// Set IP address
    pub fn with_ip_address(mut self, ip: String) -> Self {
        self.ip_address = Some(ip);
        self
    }

    /// Add context data
    pub fn with_context(mut self, key: String, value: serde_json::Value) -> Self {
        self.context.insert(key, value);
        self
    }

    /// Add tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }
}

/// Audit query filter
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditFilter {
    /// Filter by severity (minimum level)
    pub min_severity: Option<AuditSeverity>,
    /// Filter by event type pattern
    pub event_type_pattern: Option<String>,
    /// Filter by client ID
    pub client_id: Option<String>,
    /// Filter by IP address
    pub ip_address: Option<String>,
    /// Filter by time range (start)
    pub start_time: Option<DateTime<Utc>>,
    /// Filter by time range (end)
    pub end_time: Option<DateTime<Utc>>,
    /// Filter by tags (any match)
    pub tags: Vec<String>,
    /// Maximum results
    pub limit: Option<usize>,
    /// Offset for pagination
    pub offset: Option<usize>,
}

/// Audit statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuditStats {
    /// Total events logged
    pub total_events: u64,
    /// Events by severity
    pub events_by_severity: HashMap<String, u64>,
    /// Events by type
    pub events_by_type: HashMap<String, u64>,
    /// Storage size in bytes
    pub storage_size_bytes: u64,
    /// Oldest event timestamp
    pub oldest_event: Option<DateTime<Utc>>,
    /// Newest event timestamp
    pub newest_event: Option<DateTime<Utc>>,
}

/// Audit logger trait
///
/// The core trait that all audit logger implementations must satisfy.
/// Implementations must ensure compliance with security and regulatory requirements.
///
/// # Security Requirements
///
/// All implementations MUST:
/// 1. **Immutability**: Events once written cannot be modified or deleted (except by retention policy)
/// 2. **Integrity**: Provide mechanisms to detect tampering (e.g., checksums, digital signatures)
/// 3. **Availability**: Ensure audit logs remain accessible even during system failures
/// 4. **Confidentiality**: Protect sensitive data in logs (encryption at rest/in transit)
/// 5. **Non-repudiation**: Ensure actions cannot be denied (timestamps, user identification)
///
/// # Compliance Implementation Notes
///
/// - **GDPR**: Implement data minimization - only log necessary data
/// - **HIPAA**: Ensure encryption for any PHI in audit logs
/// - **PCI DSS**: Implement secure log storage with access controls
/// - **SOC2**: Provide continuous monitoring and alerting capabilities
/// - **ISO 27001**: Implement log integrity checking and secure timestamps
///
/// # Performance Considerations
///
/// - Logging must not significantly impact system performance
/// - Batch operations should be preferred for high-volume scenarios
/// - Consider using write-ahead logging for critical events
/// - Implement appropriate buffering and async I/O
#[async_trait]
pub trait AuditLogger: Send + Sync {
    /// Log a single audit event
    ///
    /// # Requirements
    /// - MUST be atomic - either fully logged or not at all
    /// - MUST return unique event ID for tracking
    /// - MUST capture timestamp at log time if not provided
    /// - SHOULD complete within 100ms for critical events
    ///
    /// # Compliance Notes
    /// - Critical events may require synchronous logging
    /// - Some regulations require immediate persistence
    async fn log(&self, event: AuditEvent) -> Result<AuditEventId>;

    /// Log multiple events in an atomic batch
    ///
    /// # Requirements
    /// - All events succeed or all fail (transactional)
    /// - Order must be preserved
    /// - More efficient than multiple log() calls
    ///
    /// # Compliance Notes
    /// - Useful for correlated events that must be logged together
    /// - May improve performance for high-volume logging
    async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<Vec<AuditEventId>>;

    /// Query audit events with filtering
    ///
    /// # Requirements
    /// - MUST NOT allow modification of returned events
    /// - MUST respect access controls (who can see what)
    /// - SHOULD support efficient pagination
    /// - SHOULD optimize common query patterns
    ///
    /// # Compliance Notes
    /// - GDPR: May need to filter out personal data based on consent
    /// - HIPAA: Must enforce minimum necessary standard
    /// - Results must be immutable copies
    async fn query(&self, filter: AuditFilter) -> Result<Vec<AuditEvent>>;

    /// Retrieve a specific event by ID
    ///
    /// # Requirements
    /// - MUST return exact event as originally logged
    /// - MUST verify integrity if available
    ///
    /// # Compliance Notes
    /// - Used for forensic investigation
    /// - May be required for legal proceedings
    async fn get_event(&self, id: &AuditEventId) -> Result<Option<AuditEvent>>;

    /// Delete events older than specified timestamp
    ///
    /// # Requirements
    /// - MUST only delete based on retention policy
    /// - MUST log the deletion action itself
    /// - SHOULD archive before deletion if required
    /// - MUST be irreversible
    ///
    /// # Compliance Notes
    /// - GDPR: Right to erasure may require selective deletion
    /// - Most standards require specific retention periods
    /// - Some events may have legal hold requirements
    /// - Deletion must be audited as a critical event
    async fn delete_before(&self, timestamp: DateTime<Utc>) -> Result<u64>;

    /// Get audit log statistics
    ///
    /// # Requirements
    /// - MUST NOT impact ongoing logging
    /// - SHOULD cache results appropriately
    ///
    /// # Compliance Notes
    /// - Used for compliance reporting
    /// - Helps identify unusual patterns
    async fn get_stats(&self) -> Result<AuditStats>;

    /// Export events in specified format
    ///
    /// # Requirements
    /// - MUST preserve all event data
    /// - MUST include integrity information
    /// - SHOULD support standard formats (CEF, SYSLOG)
    ///
    /// # Compliance Notes
    /// - Required for regulatory reporting
    /// - May need to redact sensitive data
    /// - Format must be suitable for long-term archival
    async fn export(&self, filter: AuditFilter, format: ExportFormat) -> Result<Vec<u8>>;

    /// Verify integrity of audit logs
    ///
    /// # Requirements
    /// - MUST detect any tampering or corruption
    /// - MUST NOT modify logs during verification
    /// - SHOULD be efficient for large log volumes
    ///
    /// # Compliance Notes
    /// - PCI DSS: Required for log integrity monitoring (10.5.5)
    /// - SOC2: Part of security monitoring controls
    /// - Should be run periodically and after incidents
    /// - Results must be logged as audit events
    async fn verify_integrity(&self) -> Result<IntegrityReport>;
}

/// Export formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ExportFormat {
    Json,
    Csv,
    Syslog,
    Cef, // Common Event Format
}

/// Integrity verification report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntegrityReport {
    /// Is integrity intact
    pub intact: bool,
    /// Total events checked
    pub events_checked: u64,
    /// Any issues found
    pub issues: Vec<String>,
    /// Verification timestamp
    pub verified_at: DateTime<Utc>,
}

/// Audit logger configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditConfig {
    /// Enable audit logging
    pub enabled: bool,
    /// Audit backend type
    pub backend: AuditBackend,
    /// Retention period in days
    pub retention_days: u32,
    /// Maximum events to keep
    pub max_events: Option<u64>,
    /// Buffer size for batch operations
    pub buffer_size: usize,
    /// File path (for file backend)
    pub file_path: Option<String>,
    /// Rotation settings (for file backend)
    pub rotation: Option<RotationConfig>,
    /// Enable compression
    pub compress: bool,
    /// Enable encryption
    pub encrypt: bool,
    /// Custom backend configuration
    pub custom_config: HashMap<String, serde_json::Value>,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            backend: AuditBackend::Memory,
            retention_days: 90,
            max_events: Some(1_000_000),
            buffer_size: 1000,
            file_path: Some("./audit.log".to_string()),
            rotation: Some(RotationConfig::default()),
            compress: false,
            encrypt: false,
            custom_config: HashMap::new(),
        }
    }
}

/// Audit backend types
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AuditBackend {
    Memory,
    File,
    #[cfg(feature = "enhanced")]
    Enhanced,
    Custom(String),
}

/// Log rotation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RotationConfig {
    /// Rotation strategy
    pub strategy: RotationStrategy,
    /// Maximum file size (for size-based rotation)
    pub max_size_mb: u64,
    /// Maximum file age (for time-based rotation)
    pub max_age_hours: u64,
    /// Maximum number of backups to keep
    pub max_backups: u32,
}

impl Default for RotationConfig {
    fn default() -> Self {
        Self {
            strategy: RotationStrategy::Size,
            max_size_mb: 100,
            max_age_hours: 24,
            max_backups: 10,
        }
    }
}

/// Rotation strategies
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RotationStrategy {
    Size,
    Time,
    Both,
}

/// Factory for creating audit loggers
pub trait AuditLoggerFactory: Send + Sync {
    /// Create an audit logger
    fn create(&self, config: &AuditConfig) -> Result<Arc<dyn AuditLogger>>;
}

/// Default audit logger factory
pub struct DefaultAuditLoggerFactory;

impl AuditLoggerFactory for DefaultAuditLoggerFactory {
    fn create(&self, config: &AuditConfig) -> Result<Arc<dyn AuditLogger>> {
        if !config.enabled {
            // Return a no-op logger when disabled
            return Ok(Arc::new(NoOpAuditLogger));
        }

        match &config.backend {
            AuditBackend::Memory => Ok(Arc::new(InMemoryAuditLogger::new(config.clone())?)),
            AuditBackend::File => Ok(Arc::new(FileAuditLogger::new(config.clone())?)),
            #[cfg(feature = "enhanced")]
            AuditBackend::Enhanced => Ok(Arc::new(enhanced::EnhancedAuditLogger::new(
                config.clone(),
            )?)),
            AuditBackend::Custom(name) => Err(anyhow::anyhow!(
                "Custom audit backend '{}' not implemented",
                name
            )),
        }
    }
}

/// No-op audit logger for when auditing is disabled
struct NoOpAuditLogger;

#[async_trait]
impl AuditLogger for NoOpAuditLogger {
    async fn log(&self, _event: AuditEvent) -> Result<AuditEventId> {
        Ok(AuditEventId::new())
    }

    async fn log_batch(&self, events: Vec<AuditEvent>) -> Result<Vec<AuditEventId>> {
        Ok(events.into_iter().map(|_| AuditEventId::new()).collect())
    }

    async fn query(&self, _filter: AuditFilter) -> Result<Vec<AuditEvent>> {
        Ok(Vec::new())
    }

    async fn get_event(&self, _id: &AuditEventId) -> Result<Option<AuditEvent>> {
        Ok(None)
    }

    async fn delete_before(&self, _timestamp: DateTime<Utc>) -> Result<u64> {
        Ok(0)
    }

    async fn get_stats(&self) -> Result<AuditStats> {
        Ok(AuditStats::default())
    }

    async fn export(&self, _filter: AuditFilter, _format: ExportFormat) -> Result<Vec<u8>> {
        Ok(Vec::new())
    }

    async fn verify_integrity(&self) -> Result<IntegrityReport> {
        Ok(IntegrityReport {
            intact: true,
            events_checked: 0,
            issues: Vec::new(),
            verified_at: Utc::now(),
        })
    }
}

/// Helper for creating audit events
pub struct AuditEventBuilder {
    event: AuditEvent,
}

impl AuditEventBuilder {
    pub fn new(event_type: AuditEventType, severity: AuditSeverity) -> Self {
        Self {
            event: AuditEvent::new(event_type, severity),
        }
    }

    pub fn client_id(mut self, id: String) -> Self {
        self.event.client_id = Some(id);
        self
    }

    pub fn ip_address(mut self, ip: String) -> Self {
        self.event.ip_address = Some(ip);
        self
    }

    pub fn user_agent(mut self, ua: String) -> Self {
        self.event.user_agent = Some(ua);
        self
    }

    pub fn context(mut self, key: String, value: serde_json::Value) -> Self {
        self.event.context.insert(key, value);
        self
    }

    pub fn tag(mut self, tag: String) -> Self {
        self.event.tags.push(tag);
        self
    }

    pub fn build(self) -> AuditEvent {
        self.event
    }
}

// ==================== COMPLIANCE REFERENCE GUIDE ====================

/// Compliance reference guide for audit requirements
///
/// This module provides detailed mapping between compliance standards and audit requirements.
/// Use this guide to ensure your audit configuration meets regulatory requirements.
pub mod compliance {
    /// GDPR (General Data Protection Regulation) Requirements
    ///
    /// # Required Events
    /// - AuthSuccess/AuthFailure - Track who accesses personal data
    /// - AccessGranted/AccessDenied - Monitor data access attempts
    /// - ConfigChanged - Track consent and privacy settings changes
    ///
    /// # Key Requirements
    /// - Data minimization: Only log necessary information
    /// - Right to erasure: Must support selective deletion
    /// - Data portability: Export functionality required
    /// - Breach notification: Critical events within 72 hours
    ///
    /// # Retention
    /// - Access logs: 6 months typical
    /// - Security events: 1 year
    /// - Consent records: Duration of processing + 3 years
    pub struct GDPR;

    /// SOC2 (Service Organization Control 2) Requirements
    ///
    /// # Required Events
    /// - ALL authentication and authorization events
    /// - ALL security events (threat detection/blocking)
    /// - Configuration changes
    /// - System lifecycle events
    /// - Rate limiting (availability)
    ///
    /// # Key Requirements
    /// - Continuous monitoring and alerting
    /// - Change management tracking
    /// - Incident response documentation
    /// - Access control monitoring
    ///
    /// # Retention
    /// - Minimum 1 year for all events
    /// - 3 years for security incidents
    /// - 7 years for critical events
    pub struct SOC2;

    /// HIPAA (Health Insurance Portability and Accountability Act) Requirements
    ///
    /// # Required Events
    /// - ALL authentication events (successful and failed)
    /// - ALL authorization events (PHI access)
    /// - System errors that could affect PHI
    /// - Configuration changes affecting security
    ///
    /// # Key Requirements
    /// - Encryption required for PHI in logs
    /// - Minimum necessary standard for access
    /// - User activity tracking mandatory
    /// - Regular log reviews required
    ///
    /// # Retention
    /// - 6 years minimum for all PHI-related events
    /// - Immediate notification for breaches
    pub struct HIPAA;

    /// PCI DSS (Payment Card Industry Data Security Standard) Requirements
    ///
    /// # Required Events
    /// - User access to cardholder data (10.2.1)
    /// - All administrator actions (10.2.2)
    /// - Access to audit trails (10.2.3)
    /// - Invalid access attempts (10.2.4)
    /// - Authentication/authorization changes (10.2.5)
    /// - System/log initialization (10.2.6)
    /// - System-level object changes (10.2.7)
    ///
    /// # Key Requirements
    /// - Daily log review required
    /// - Secure centralized logging
    /// - Log integrity monitoring
    /// - Time synchronization critical
    ///
    /// # Retention
    /// - 1 year online, readily available
    /// - 3 months immediately accessible
    /// - Secure archival after 1 year
    pub struct PciDss;

    /// ISO 27001 Information Security Management Requirements
    ///
    /// # Required Events
    /// - ALL security events
    /// - Access control events
    /// - System changes and errors
    /// - Security control effectiveness
    ///
    /// # Key Requirements
    /// - Risk-based approach to logging
    /// - Regular log analysis and review
    /// - Incident management integration
    /// - Corrective action tracking
    ///
    /// # Retention
    /// - Based on risk assessment
    /// - Typically 1-3 years minimum
    /// - 7 years for major incidents
    pub struct ISO27001;

    /// Quick reference: Event types by compliance standard
    ///
    /// ```text
    /// | Event Type                | GDPR | SOC2 | HIPAA | PCI DSS | ISO 27001 |
    /// |---------------------------|------|------|-------|---------|-----------|
    /// | AuthSuccess              | ✓    | ✓    | ✓     | ✓       | ✓         |
    /// | AuthFailure              | ✓    | ✓    | ✓     | ✓       | ✓         |
    /// | AccessGranted            | ✓    | ✓    | ✓     | ✓       | ✓         |
    /// | AccessDenied             | ✓    | ✓    | ✓     | ✓       | ✓         |
    /// | ThreatDetected           | ○    | ✓    | ✓     | ✓       | ✓         |
    /// | ThreatBlocked            | ○    | ✓    | ✓     | ✓       | ✓         |
    /// | NeutralizationStarted    |      | ✓    |       |         | ✓         |
    /// | NeutralizationCompleted  |      | ✓    |       |         | ✓         |
    /// | NeutralizationFailed     |      | ✓    |       |         | ✓         |
    /// | RateLimitTriggered       |      | ✓    |       | ✓       |           |
    /// | ConfigChanged            | ○    | ✓    | ○     | ✓       | ✓         |
    /// | ServerStarted            |      | ✓    |       | ✓       | ✓         |
    /// | ServerStopped            |      | ✓    |       | ✓       | ✓         |
    /// | SystemError              |      | ✓    | ○     |         | ✓         |
    ///
    /// Legend: ✓ = Required, ○ = Recommended
    /// ```
    pub struct ComplianceMatrix;

    /// Recommended audit configuration for multi-compliance
    ///
    /// ```toml
    /// [audit]
    /// enabled = true
    /// backend = "file"  # or "enhanced" for high-security environments
    /// retention_days = 2555  # 7 years for maximum compliance
    /// encrypt = true  # Required for HIPAA
    /// compress = true  # For efficient storage
    ///
    /// [audit.alerts]
    /// critical_events = ["email", "siem"]  # Immediate notification
    /// threshold_events = ["email"]  # Repeated failures, rate limits
    ///
    /// [audit.integrity]
    /// checksum = "sha256"  # For tamper detection
    /// verify_interval = "daily"  # PCI DSS requirement
    /// ```
    pub struct RecommendedConfig;
}

/// Create an audit logger based on configuration
pub fn create_audit_logger(_config: &crate::config::Config) -> Arc<dyn AuditLogger> {
    // For now, use default audit config
    // TODO: Add audit config to main Config struct
    let audit_config = AuditConfig::default();

    let factory = DefaultAuditLoggerFactory;
    factory
        .create(&audit_config)
        .unwrap_or_else(|_| Arc::new(NoOpAuditLogger))
}