Skip to main content

copybook_audit/
lib.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2//! Enterprise Audit System for copybook-rs
3//!
4//! **EXPERIMENTAL**: This crate is experimental and subject to breaking changes.
5//! It lives outside the stable `copybook-core` surface; depend on
6//! `copybook-audit` explicitly to opt in.
7//!
8//! ## Status
9//!
10//! This audit system is under active development and should be considered unstable.
11//! The API may change significantly between releases, and production use is not
12//! recommended without thorough validation in your specific environment.
13//!
14//! ## Opt-in dependency
15//!
16//! To enable the audit system, depend on this crate directly:
17//!
18//! ```toml
19//! [dependencies]
20//! copybook-audit = "0.5"
21//! ```
22//!
23//! **Performance Note**: Keep this dependency out of hot paths unless you require
24//! comprehensive audit capabilities for compliance or security monitoring.
25//!
26//! ## Capabilities
27//!
28//! When enabled, this module provides comprehensive audit capabilities for enterprise
29//! mainframe data processing, including:
30//!
31//! - **Regulatory Compliance**: SOX, HIPAA, GDPR, PCI-DSS compliance tracking
32//! - **Security Monitoring**: Access control validation and security event auditing
33//! - **Performance Tracking**: Throughput metrics and regression detection
34//! - **Data Lineage**: Complete field-level transformation and impact tracking
35//! - **Audit Trail Integrity**: Cryptographic hash chains for tamper detection
36//!
37//! ## Stability Guarantees
38//!
39//! **None**. This is experimental software:
40//!
41//! - APIs may change without notice between minor versions
42//! - Serialization formats may be incompatible across releases
43//! - Performance characteristics are not yet optimized
44//! - Error handling patterns may evolve
45//!
46//! Use at your own risk and validate thoroughly before production deployment.
47
48#![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// Crate-level allows carried with the audit surface moved out of
59// `copybook-core` (#656 Phase E); the code below was developed under them.
60#![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/// Enterprise audit system error types
120#[derive(Debug, thiserror::Error)]
121pub enum AuditError {
122    /// Regulatory compliance rule violation.
123    #[error("Compliance violation: {message}")]
124    ComplianceViolation {
125        /// Stable error code identifying the violation.
126        code: String,
127        /// Human-readable description of the violation.
128        message: String,
129        /// Optional key-value context about the violation.
130        context: Option<HashMap<String, String>>,
131    },
132
133    /// Security validation check failure.
134    #[error("Security validation failed: {message}")]
135    SecurityValidationFailed {
136        /// Human-readable description of the failure.
137        message: String,
138        /// Severity classification.
139        severity: SecuritySeverity,
140    },
141
142    /// Throughput regression beyond the allowed baseline deviation.
143    #[error("Performance regression detected: {message}")]
144    PerformanceRegression {
145        /// Human-readable description of the regression.
146        message: String,
147        /// Fractional deviation from baseline (e.g. 0.15 = 15%).
148        baseline_deviation: f64,
149    },
150
151    /// Tamper-detection failure in the audit hash chain.
152    #[error("Audit trail integrity failure: {message}")]
153    AuditTrailIntegrity {
154        /// Human-readable description.
155        message: String,
156        /// Expected integrity hash value.
157        expected_hash: String,
158        /// Actual computed hash value.
159        actual_hash: String,
160    },
161
162    /// Invalid or missing audit configuration parameter.
163    #[error("Configuration error: {message}")]
164    Configuration {
165        /// Human-readable description.
166        message: String,
167    },
168
169    /// Underlying I/O error in the audit subsystem.
170    #[error("I/O error in audit system: {source}")]
171    Io {
172        #[from]
173        /// The wrapped I/O error.
174        source: std::io::Error,
175    },
176
177    /// JSON serialization / deserialization failure.
178    #[error("Serialization error: {source}")]
179    Serialization {
180        #[from]
181        /// The wrapped serde error.
182        source: serde_json::Error,
183    },
184}
185
186/// Security severity levels for audit events
187#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
188pub enum SecuritySeverity {
189    /// Informational or low-impact event.
190    Low,
191    /// Moderate risk that may need attention.
192    Medium,
193    /// High risk requiring prompt action.
194    High,
195    /// Critical risk requiring immediate response.
196    Critical,
197}
198
199/// Audit result type
200pub type AuditResult<T> = std::result::Result<T, AuditError>;
201
202/// Generate a unique audit event identifier
203pub 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
215// Thread-local counter for lightweight ID generation
216thread_local! {
217    static ID_COUNTER: std::cell::RefCell<u64> = const { std::cell::RefCell::new(0) };
218}
219
220/// Generate a lightweight audit ID for performance-critical operations
221/// Uses thread-local counter instead of expensive timestamp and crypto
222#[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
231/// Generate a cryptographic hash for audit trail integrity
232pub 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
245/// Validate audit trail integrity chain
246pub 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        // Serialize event without integrity_hash for validation
259        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); // SHA-256 produces 64 character hex string
308        assert_ne!(hash1, hash2); // Including previous hash should change result
309    }
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}