Mountain/IPC/Permission/Audit/
LogEvent.rs

1//! # Audit
2//!
3//! ## File: IPC/Permission/Audit/LogEvent.rs
4//!
5//! ## Role in Mountain Architecture
6//!
7//! Provides comprehensive security event logging and audit trail functionality
8//! for IPC operations, enabling security compliance monitoring, forensic
9//! analysis, and performance tracking.
10//!
11//! ## Primary Responsibility
12//!
13//! Log security events for audit trails including permission checks, access
14//! attempts, security violations, and configuration changes.
15//!
16//! ## Secondary Responsibilities
17//!
18//! - Manage log storage with automatic rotation
19//! - Export audit logs to JSON format
20//! - Filter and query events by user, type, severity, or date range
21//! - Track performance anomalies for optimization
22//! - Maintain bounded log size to prevent memory exhaustion
23//! - Provide builder pattern for flexible event creation
24//!
25//! ## Dependencies
26//!
27//! **External Crates:**
28//! - `std::collections::VecDeque` - Bounded log storage with efficient rotation
29//! - `std::sync::Arc` - Shared ownership across threads
30//! - `tokio::sync::RwLock` - Async-safe concurrent access
31//! - `log` - Event logging infrastructure
32//! - `serde` - Serialization for JSON export
33//! - `serde_json` - JSON formatting
34//! - `chrono` - Timestamp management (optional, falls back to std::time)
35//!
36//! **Internal Modules:**
37//! - `Validate::ValidatePermission::{Permission, SecurityContext}` - Permission
38//!   context
39//! - `Role::ManageRole::Role` - Role change events
40//!
41//! ## Dependents
42//!
43//! - `Validate::ValidatePermission` - Logs permission validation results
44//! - `Role::ManageRole` - Logs role management operations
45//! - `TauriIPCServer` - Logs all IPC security events
46//! - `Send` - Logs message transmission events
47//! - `Receive` - Logs message reception events
48//!
49//! ## VSCode Pattern Reference
50//!
51//! Inspired by VSCode's audit logging in
52//! `vs/platform/telemetry/common/telemetryService.ts`
53//! - Structured event logging with contextual metadata
54//! - Severity classification for event filtering
55//! - Bounded buffer for log rotation
56//! - Export capabilities for compliance reporting
57//!
58//! ## Security Considerations
59//!
60//! - All security events logged for compliance auditing
61//! - PII (Personally Identifiable Information) sanitized by default
62//! - IpAddresses optionally redacted based on privacy settings
63//! - Sensitive details masked before log export
64//! - Log access controlled through RBAC (not implemented in this module)
65//! - Tamper-evident logging via hash chain (future enhancement)
66//! - Log injection prevented via input validation
67//! - Memory bounds prevent log-based denial of service
68//!
69//! ## Performance Considerations
70//!
71//! - VecDeque provides O(1) push/pop for log rotation
72//! - RwLock allows concurrent reads, exclusive writes
73//! - Index-based filtering is O(n) in worst case but acceptable
74//! - JSON export performed lazily, not on every log event
75//! - Bounded log size (1000 events) provides constant memory profile
76//! - Log rotation is amortized O(1) per event
77//! - Async logging prevents blocking main thread
78//!
79//! ## Error Handling Strategy
80//!
81//! - Returns Result for explicit error handling
82//! - Partial log export succeeds even if some events fail serialization
83//! - Invalid event data sanitized rather than causing failure
84//! - Log overflow handled via rotation, not error
85//! - Malformed filter criteria default to empty result
86//! - JSON export errors logged but don't crash
87//!
88//! ## Thread Safety
89//!
90//! - RwLock wrapped in Arc for safe concurrent access
91//! - Multiple concurrent reads, exclusive writes
92//! - Lock contention minimized by short critical sections
93//! - Event struct is Clone for safe sharing
94//!
95//! ## TODO Items
96//!
97//! - [ ] Implement hash chain for tamper-evident logging
98//! - [ ] Add persistent log storage to disk
99//! - [ ] Implement log compression for archival
100//! - [ ] Add anonymization options for PII redaction
101//! - [ ] Support structured queries (SQL-like syntax)
102//! - [ ] Add real-time alerting for critical events
103//! - [ ] Implement log aggregation across multiple instances
104
105use std::{
106	collections::VecDeque,
107	net::IpAddr,
108	sync::Arc,
109	time::{Duration, SystemTime, UNIX_EPOCH},
110};
111
112use tokio::sync::RwLock;
113use log::{debug, error, info, warn};
114use serde::{Deserialize, Serialize};
115
116/// Maximum number of events to store in the audit log
117/// bounded to prevent memory exhaustion
118const MAX_LOG_SIZE:usize = 1000;
119
120/// Default timeout for log operations in milliseconds
121const LOG_TIMEOUT_MS:u64 = 5000;
122
123/// Security event type categorization for audit trail classification
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
125pub enum SecurityEventType {
126	/// Access was granted to a resource or operation
127	AccessGranted,
128	/// Access was denied due to insufficient permissions
129	PermissionDenied,
130	/// Authentication attempt failed
131	AuthenticationFailed,
132	/// Application configuration was modified
133	ConfigurationChange,
134	/// Security policy was violated
135	SecurityViolation,
136	/// Performance anomaly detected
137	PerformanceAnomaly,
138	/// User role was changed
139	RoleChange,
140	/// Permission was added, removed, or modified
141	PermissionChange,
142	/// Security policy was updated
143	PolicyChange,
144}
145
146impl SecurityEventType {
147	/// Get display name for event type
148	pub fn DisplayName(&self) -> String {
149		match self {
150			SecurityEventType::AccessGranted => String::from("AccessGranted"),
151			SecurityEventType::PermissionDenied => String::from("PermissionDenied"),
152			SecurityEventType::AuthenticationFailed => String::from("AuthenticationFailed"),
153			SecurityEventType::ConfigurationChange => String::from("ConfigurationChange"),
154			SecurityEventType::SecurityViolation => String::from("SecurityViolation"),
155			SecurityEventType::PerformanceAnomaly => String::from("PerformanceAnomaly"),
156			SecurityEventType::RoleChange => String::from("RoleChange"),
157			SecurityEventType::PermissionChange => String::from("PermissionChange"),
158			SecurityEventType::PolicyChange => String::from("PolicyChange"),
159		}
160	}
161}