1#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used))]
49#![cfg_attr(
50 test,
51 allow(
52 clippy::expect_used,
53 clippy::unwrap_used,
54 clippy::panic,
55 clippy::duplicated_attributes
56 )
57)]
58#![allow(clippy::missing_inline_in_public_items)]
61#![allow(clippy::missing_errors_doc)]
62#![allow(clippy::missing_panics_doc)]
63#![allow(clippy::format_push_string)]
64#![allow(clippy::uninlined_format_args)]
65#![allow(clippy::match_same_arms)]
66#![allow(clippy::module_name_repetitions)]
67#![allow(clippy::too_many_lines)]
68#![allow(clippy::must_use_candidate)]
69#![allow(clippy::collapsible_else_if)]
70#![allow(clippy::unused_self)]
71#![allow(clippy::doc_markdown)]
72#![allow(clippy::unnecessary_wraps)]
73#![allow(clippy::cast_possible_wrap)]
74#![allow(clippy::bool_to_int_with_if)]
75#![allow(clippy::cast_lossless)]
76#![allow(clippy::cast_sign_loss)]
77#![allow(clippy::assigning_clones)]
78#![allow(clippy::cast_possible_truncation)]
79#![allow(clippy::manual_midpoint)]
80#![allow(clippy::redundant_closure_for_method_calls)]
81#![allow(clippy::single_match_else)]
82#![allow(clippy::ignored_unit_patterns)]
83
84pub mod compliance;
85pub mod context;
86pub mod event;
87pub mod lineage;
88pub mod logger;
89pub mod performance;
90pub mod report;
91pub mod security;
92
93pub use compliance::{
94 ComplianceConfig, ComplianceEngine, ComplianceProfile, ComplianceResult, ComplianceViolation,
95};
96pub use context::{AuditContext, EnvironmentContext, ProcessingConfig, SecurityContext};
97pub use event::{AuditEvent, AuditEventType, AuditPayload, AuditSeverity};
98pub use lineage::{
99 FieldLineage, ImpactAnalyzer, ImpactAssessment, LineageRecord, LineageTracker, RiskLevel,
100 TransformationType,
101};
102pub use logger::{AuditLogger, AuditLoggerConfig, LogFormat, RetentionPolicy};
103pub use performance::{
104 BaselineManager, PerformanceAuditor, PerformanceBaseline, RegressionDetector, ResourceMetrics,
105 ThroughputMetrics,
106};
107pub use report::{
108 AuditReport, ComplianceReport, PerformanceReport, ReportFormat, ReportGenerator, SecurityReport,
109};
110pub use security::{
111 AccessAuditor, AccessEvent, AccessResult, EncryptionConfig, EventMonitor, SecurityAuditor,
112 SecurityMonitor, SecurityValidation, SecurityViolation,
113};
114
115use serde::{Deserialize, Serialize};
116use std::collections::HashMap;
117use std::time::{Duration, SystemTime, UNIX_EPOCH};
118
119#[derive(Debug, thiserror::Error)]
121pub enum AuditError {
122 #[error("Compliance violation: {message}")]
124 ComplianceViolation {
125 code: String,
127 message: String,
129 context: Option<HashMap<String, String>>,
131 },
132
133 #[error("Security validation failed: {message}")]
135 SecurityValidationFailed {
136 message: String,
138 severity: SecuritySeverity,
140 },
141
142 #[error("Performance regression detected: {message}")]
144 PerformanceRegression {
145 message: String,
147 baseline_deviation: f64,
149 },
150
151 #[error("Audit trail integrity failure: {message}")]
153 AuditTrailIntegrity {
154 message: String,
156 expected_hash: String,
158 actual_hash: String,
160 },
161
162 #[error("Configuration error: {message}")]
164 Configuration {
165 message: String,
167 },
168
169 #[error("I/O error in audit system: {source}")]
171 Io {
172 #[from]
173 source: std::io::Error,
175 },
176
177 #[error("Serialization error: {source}")]
179 Serialization {
180 #[from]
181 source: serde_json::Error,
183 },
184}
185
186#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188pub enum SecuritySeverity {
189 Low,
191 Medium,
193 High,
195 Critical,
197}
198
199pub type AuditResult<T> = std::result::Result<T, AuditError>;
201
202pub fn generate_audit_id() -> String {
204 let timestamp = SystemTime::now()
205 .duration_since(UNIX_EPOCH)
206 .unwrap_or(Duration::ZERO)
207 .as_nanos();
208
209 let random_bytes = rand::random::<[u8; 8]>();
210 let random_hex = hex::encode(random_bytes);
211
212 format!("audit-{}-{}", timestamp, random_hex)
213}
214
215thread_local! {
217 static ID_COUNTER: std::cell::RefCell<u64> = const { std::cell::RefCell::new(0) };
218}
219
220#[inline]
223pub fn generate_lightweight_audit_id() -> String {
224 ID_COUNTER.with(|counter| {
225 let mut counter = counter.borrow_mut();
226 *counter = counter.wrapping_add(1);
227 format!("perf-audit-{}", *counter)
228 })
229}
230
231pub fn generate_integrity_hash(data: &[u8], previous_hash: Option<&str>) -> String {
233 use sha2::{Digest, Sha256};
234
235 let mut hasher = Sha256::new();
236 hasher.update(data);
237
238 if let Some(prev) = previous_hash {
239 hasher.update(prev.as_bytes());
240 }
241
242 format!("{:x}", hasher.finalize())
243}
244
245pub fn validate_audit_chain(events: &[AuditEvent]) -> AuditResult<bool> {
247 if events.is_empty() {
248 return Ok(true);
249 }
250
251 for (i, event) in events.iter().enumerate() {
252 let expected_previous_hash = if i == 0 {
253 None
254 } else {
255 Some(events[i - 1].integrity_hash.as_str())
256 };
257
258 let mut event_for_validation = event.clone();
260 event_for_validation.integrity_hash = String::new();
261 event_for_validation.previous_hash = None;
262
263 let event_bytes = serde_json::to_vec(&event_for_validation)?;
264 let expected_hash = generate_integrity_hash(&event_bytes, expected_previous_hash);
265
266 if event.integrity_hash != expected_hash {
267 return Err(AuditError::AuditTrailIntegrity {
268 message: format!("Integrity hash mismatch for event {}", event.event_id),
269 expected_hash,
270 actual_hash: event.integrity_hash.clone(),
271 });
272 }
273
274 if event.previous_hash.as_deref() != expected_previous_hash {
275 return Err(AuditError::AuditTrailIntegrity {
276 message: format!("Previous hash mismatch for event {}", event.event_id),
277 expected_hash: expected_previous_hash.unwrap_or("None").to_string(),
278 actual_hash: event.previous_hash.as_deref().unwrap_or("None").to_string(),
279 });
280 }
281 }
282
283 Ok(true)
284}
285
286#[cfg(test)]
287#[allow(clippy::expect_used)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn test_generate_audit_id() {
293 let id1 = generate_audit_id();
294 let id2 = generate_audit_id();
295
296 assert!(id1.starts_with("audit-"));
297 assert!(id2.starts_with("audit-"));
298 assert_ne!(id1, id2);
299 }
300
301 #[test]
302 fn test_generate_integrity_hash() {
303 let data = b"test data";
304 let hash1 = generate_integrity_hash(data, None);
305 let hash2 = generate_integrity_hash(data, Some("previous"));
306
307 assert_eq!(hash1.len(), 64); assert_ne!(hash1, hash2); }
310
311 #[test]
312 fn test_empty_audit_chain_validation() {
313 let events = vec![];
314 assert!(validate_audit_chain(&events).expect("Failed to validate audit chain"));
315 }
316}