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
//! Advanced audit system with immutable logs and cryptographic proofs
//!
//! Provides comprehensive audit trails, tamper-evident logging, and audit analytics
use crate::error::CoreError;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use uuid::Uuid;
/// Audit log manager with immutable, tamper-evident logging
pub struct AuditLogManager {
/// Audit log entries
logs: Arc<RwLock<Vec<AuditLogEntry>>>,
/// Hash chain for tamper detection
hash_chain: Arc<RwLock<Vec<String>>>,
/// Analytics engine
analytics: Arc<RwLock<AuditAnalytics>>,
}
/// A single audit log entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditLogEntry {
/// Entry ID
pub id: Uuid,
/// Timestamp
pub timestamp: DateTime<Utc>,
/// Actor (user/system)
pub actor: String,
/// Tenant ID (for multi-tenancy)
pub tenant_id: Option<Uuid>,
/// Action performed
pub action: AuditAction,
/// Resource type
pub resource_type: String,
/// Resource ID
pub resource_id: String,
/// Previous state (JSON)
pub previous_state: Option<String>,
/// New state (JSON)
pub new_state: Option<String>,
/// IP address
pub ip_address: Option<String>,
/// User agent
pub user_agent: Option<String>,
/// Metadata
pub metadata: HashMap<String, String>,
/// Previous hash (for chain)
pub previous_hash: String,
/// Current hash
pub hash: String,
}
/// Audit action types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum AuditAction {
/// A new resource was created
Create,
/// A resource was read or queried
Read,
/// An existing resource was modified
Update,
/// A resource was deleted
Delete,
/// A user authenticated successfully
Login,
/// A user ended their session
Logout,
/// A user changed their password
PasswordChange,
/// A user's permissions were changed
PermissionChange,
/// System or platform configuration was changed
ConfigChange,
/// A trade was executed
Trade,
/// Funds were withdrawn from the platform
Withdrawal,
/// Funds were deposited into the platform
Deposit,
/// A custom action not covered by other variants
Custom(String),
}
impl AuditLogManager {
/// Create a new audit log manager
pub fn new() -> Self {
Self {
logs: Arc::new(RwLock::new(Vec::new())),
hash_chain: Arc::new(RwLock::new(vec!["genesis".to_string()])),
analytics: Arc::new(RwLock::new(AuditAnalytics::new())),
}
}
/// Log an audit event
#[allow(clippy::too_many_arguments)]
pub fn log(
&self,
actor: String,
tenant_id: Option<Uuid>,
action: AuditAction,
resource_type: String,
resource_id: String,
previous_state: Option<String>,
new_state: Option<String>,
ip_address: Option<String>,
user_agent: Option<String>,
metadata: HashMap<String, String>,
) -> Result<Uuid, CoreError> {
let id = Uuid::new_v4();
let timestamp = Utc::now();
// Get previous hash from chain
let previous_hash = {
let chain = self.hash_chain.read().unwrap();
chain.last().unwrap().clone()
};
// Create entry
let entry = AuditLogEntry {
id,
timestamp,
actor: actor.clone(),
tenant_id,
action: action.clone(),
resource_type: resource_type.clone(),
resource_id: resource_id.clone(),
previous_state: previous_state.clone(),
new_state: new_state.clone(),
ip_address,
user_agent,
metadata: metadata.clone(),
previous_hash: previous_hash.clone(),
hash: String::new(), // Will be computed
};
// Compute hash
let hash = self.compute_hash(&entry);
let mut entry = entry;
entry.hash = hash.clone();
// Add to logs
self.logs.write().unwrap().push(entry.clone());
// Add to hash chain
self.hash_chain.write().unwrap().push(hash);
// Update analytics
self.analytics
.write()
.unwrap()
.record_event(&actor, &action, &resource_type);
Ok(id)
}
/// Compute cryptographic hash of an entry
fn compute_hash(&self, entry: &AuditLogEntry) -> String {
let mut hasher = Sha256::new();
// Include all fields in hash
hasher.update(entry.id.to_string().as_bytes());
hasher.update(entry.timestamp.to_rfc3339().as_bytes());
hasher.update(entry.actor.as_bytes());
if let Some(tid) = &entry.tenant_id {
hasher.update(tid.to_string().as_bytes());
}
hasher.update(format!("{:?}", entry.action).as_bytes());
hasher.update(entry.resource_type.as_bytes());
hasher.update(entry.resource_id.as_bytes());
if let Some(ps) = &entry.previous_state {
hasher.update(ps.as_bytes());
}
if let Some(ns) = &entry.new_state {
hasher.update(ns.as_bytes());
}
hasher.update(entry.previous_hash.as_bytes());
hex::encode(hasher.finalize().as_slice())
}
/// Verify integrity of audit log
pub fn verify_integrity(&self) -> Result<bool, CoreError> {
let logs = self.logs.read().unwrap();
let chain = self.hash_chain.read().unwrap();
if logs.is_empty() {
return Ok(true);
}
// Verify each entry's hash
for (i, entry) in logs.iter().enumerate() {
let computed_hash = self.compute_hash(entry);
if computed_hash != entry.hash {
return Ok(false);
}
// Verify chain linkage
if i > 0 {
let prev_entry = &logs[i - 1];
if entry.previous_hash != prev_entry.hash {
return Ok(false);
}
}
// Verify against chain
if chain.get(i + 1) != Some(&entry.hash) {
return Ok(false);
}
}
Ok(true)
}
/// Get audit logs with filtering
pub fn get_logs(&self, filter: AuditLogFilter) -> Vec<AuditLogEntry> {
let logs = self.logs.read().unwrap();
logs.iter()
.filter(|entry| {
// Filter by actor
if let Some(ref actor) = filter.actor {
if &entry.actor != actor {
return false;
}
}
// Filter by tenant
if let Some(ref tenant_id) = filter.tenant_id {
if entry.tenant_id.as_ref() != Some(tenant_id) {
return false;
}
}
// Filter by action
if let Some(ref action) = filter.action {
if &entry.action != action {
return false;
}
}
// Filter by resource type
if let Some(ref resource_type) = filter.resource_type {
if &entry.resource_type != resource_type {
return false;
}
}
// Filter by time range
if let Some(start) = filter.start_time {
if entry.timestamp < start {
return false;
}
}
if let Some(end) = filter.end_time {
if entry.timestamp > end {
return false;
}
}
true
})
.cloned()
.collect()
}
/// Get audit analytics
pub fn get_analytics(&self) -> AuditAnalytics {
self.analytics.read().unwrap().clone()
}
/// Detect anomalies in audit logs
pub fn detect_anomalies(&self) -> Vec<AuditAnomaly> {
let logs = self.logs.read().unwrap();
let mut anomalies = Vec::new();
// Detect unusual activity patterns
let mut actor_actions: HashMap<String, Vec<&AuditLogEntry>> = HashMap::new();
for entry in logs.iter() {
actor_actions
.entry(entry.actor.clone())
.or_default()
.push(entry);
}
// Check for suspicious patterns
for (actor, entries) in actor_actions.iter() {
// Rapid successive actions
let mut sorted = entries.to_vec();
sorted.sort_by_key(|e| e.timestamp);
for window in sorted.windows(5) {
if window.len() == 5 {
let duration = window[4].timestamp - window[0].timestamp;
if duration.num_seconds() < 5 {
anomalies.push(AuditAnomaly {
anomaly_type: AnomalyType::RapidActivity,
actor: actor.clone(),
description: format!("5 actions in {} seconds", duration.num_seconds()),
severity: AnomalySeverity::Medium,
timestamp: window[0].timestamp,
});
}
}
}
// Multiple failed login attempts
let failed_logins = entries
.iter()
.filter(|e| {
e.action == AuditAction::Login
&& e.metadata.get("status") == Some(&"failed".to_string())
})
.count();
if failed_logins > 3 {
anomalies.push(AuditAnomaly {
anomaly_type: AnomalyType::FailedLogins,
actor: actor.clone(),
description: format!("{} failed login attempts", failed_logins),
severity: AnomalySeverity::High,
timestamp: Utc::now(),
});
}
// Unusual action patterns (e.g., reading then immediately deleting)
for window in sorted.windows(2) {
if window[0].action == AuditAction::Read
&& window[1].action == AuditAction::Delete
&& window[0].resource_id == window[1].resource_id
{
let duration = window[1].timestamp - window[0].timestamp;
if duration.num_seconds() < 2 {
anomalies.push(AuditAnomaly {
anomaly_type: AnomalyType::SuspiciousPattern,
actor: actor.clone(),
description: "Read followed by immediate delete".to_string(),
severity: AnomalySeverity::Medium,
timestamp: window[1].timestamp,
});
}
}
}
}
anomalies
}
/// Generate compliance report
pub fn generate_compliance_report(
&self,
start: DateTime<Utc>,
end: DateTime<Utc>,
) -> ComplianceReport {
let logs = self.get_logs(AuditLogFilter {
actor: None,
tenant_id: None,
action: None,
resource_type: None,
start_time: Some(start),
end_time: Some(end),
});
let mut action_counts: HashMap<String, usize> = HashMap::new();
let mut resource_counts: HashMap<String, usize> = HashMap::new();
let mut unique_actors = std::collections::HashSet::new();
for entry in &logs {
let action_key = format!("{:?}", entry.action);
*action_counts.entry(action_key).or_insert(0) += 1;
*resource_counts
.entry(entry.resource_type.clone())
.or_insert(0) += 1;
unique_actors.insert(entry.actor.clone());
}
ComplianceReport {
period_start: start,
period_end: end,
total_events: logs.len(),
unique_actors: unique_actors.len(),
action_breakdown: action_counts,
resource_breakdown: resource_counts,
integrity_verified: self.verify_integrity().unwrap_or(false),
}
}
/// Export audit logs for forensic analysis
pub fn export_logs(&self, format: ExportFormat) -> Result<String, CoreError> {
let logs = self.logs.read().unwrap();
match format {
ExportFormat::Json => serde_json::to_string_pretty(&*logs)
.map_err(|e| CoreError::Validation(format!("JSON export failed: {}", e))),
ExportFormat::Csv => {
let mut csv =
String::from("id,timestamp,actor,action,resource_type,resource_id,hash\n");
for entry in logs.iter() {
csv.push_str(&format!(
"{},{},{},{:?},{},{},{}\n",
entry.id,
entry.timestamp,
entry.actor,
entry.action,
entry.resource_type,
entry.resource_id,
entry.hash
));
}
Ok(csv)
}
}
}
/// Get total log count
pub fn log_count(&self) -> usize {
self.logs.read().unwrap().len()
}
}
impl Default for AuditLogManager {
fn default() -> Self {
Self::new()
}
}
/// Filter for querying audit logs
#[derive(Debug, Clone, Default)]
pub struct AuditLogFilter {
/// Return only entries where the actor matches this value
pub actor: Option<String>,
/// Return only entries belonging to this tenant
pub tenant_id: Option<Uuid>,
/// Return only entries for this action type
pub action: Option<AuditAction>,
/// Return only entries affecting this resource type
pub resource_type: Option<String>,
/// Return only entries at or after this timestamp
pub start_time: Option<DateTime<Utc>>,
/// Return only entries at or before this timestamp
pub end_time: Option<DateTime<Utc>>,
}
/// Audit analytics
#[derive(Debug, Clone)]
pub struct AuditAnalytics {
/// Actions per actor
actions_per_actor: HashMap<String, usize>,
/// Actions per type
actions_per_type: HashMap<String, usize>,
/// Resources accessed
resources_accessed: HashMap<String, usize>,
}
impl AuditAnalytics {
fn new() -> Self {
Self {
actions_per_actor: HashMap::new(),
actions_per_type: HashMap::new(),
resources_accessed: HashMap::new(),
}
}
fn record_event(&mut self, actor: &str, action: &AuditAction, resource_type: &str) {
*self.actions_per_actor.entry(actor.to_string()).or_insert(0) += 1;
*self
.actions_per_type
.entry(format!("{:?}", action))
.or_insert(0) += 1;
*self
.resources_accessed
.entry(resource_type.to_string())
.or_insert(0) += 1;
}
/// Get top actors by activity
pub fn top_actors(&self, limit: usize) -> Vec<(String, usize)> {
let mut actors: Vec<_> = self.actions_per_actor.iter().collect();
actors.sort_by(|a, b| b.1.cmp(a.1));
actors.truncate(limit);
actors.into_iter().map(|(k, v)| (k.clone(), *v)).collect()
}
/// Get action distribution
pub fn action_distribution(&self) -> HashMap<String, usize> {
self.actions_per_type.clone()
}
}
/// Detected anomaly in the audit log
#[derive(Debug, Clone)]
pub struct AuditAnomaly {
/// Category of the anomaly
pub anomaly_type: AnomalyType,
/// Actor whose behaviour triggered the anomaly
pub actor: String,
/// Human-readable description of the anomaly
pub description: String,
/// How serious this anomaly is considered
pub severity: AnomalySeverity,
/// When the anomaly was detected
pub timestamp: DateTime<Utc>,
}
/// Category of audit anomaly
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnomalyType {
/// Unusually high action rate from a single actor
RapidActivity,
/// Multiple consecutive failed login attempts
FailedLogins,
/// Action sequence that matches a known suspicious pattern
SuspiciousPattern,
/// Access to resources outside the user's normal scope
UnusualAccess,
}
/// Severity level of an audit anomaly
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum AnomalySeverity {
/// Informational; does not require immediate action
Low,
/// Worth investigating but not urgent
Medium,
/// Likely malicious; requires prompt response
High,
/// Active attack or data breach; requires immediate response
Critical,
}
/// Summary compliance report for a time period
#[derive(Debug, Clone)]
pub struct ComplianceReport {
/// Start of the reporting period
pub period_start: DateTime<Utc>,
/// End of the reporting period
pub period_end: DateTime<Utc>,
/// Total number of audit events in the period
pub total_events: usize,
/// Number of distinct actors that generated events
pub unique_actors: usize,
/// Count of events broken down by action type
pub action_breakdown: HashMap<String, usize>,
/// Count of events broken down by resource type
pub resource_breakdown: HashMap<String, usize>,
/// Whether the log integrity was verified successfully
pub integrity_verified: bool,
}
/// Export format for audit logs
#[derive(Debug, Clone, Copy)]
pub enum ExportFormat {
/// Export as pretty-printed JSON
Json,
/// Export as comma-separated values
Csv,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_audit_log_creation() {
let manager = AuditLogManager::new();
let id = manager
.log(
"user123".to_string(),
None,
AuditAction::Create,
"order".to_string(),
"order_456".to_string(),
None,
Some("{\"status\": \"pending\"}".to_string()),
Some("192.168.1.1".to_string()),
None,
HashMap::new(),
)
.unwrap();
assert!(id != Uuid::nil());
assert_eq!(manager.log_count(), 1);
}
#[test]
fn test_integrity_verification() {
let manager = AuditLogManager::new();
manager
.log(
"user1".to_string(),
None,
AuditAction::Create,
"token".to_string(),
"token_1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
manager
.log(
"user2".to_string(),
None,
AuditAction::Update,
"token".to_string(),
"token_1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
assert!(manager.verify_integrity().unwrap());
}
#[test]
fn test_audit_log_filtering() {
let manager = AuditLogManager::new();
manager
.log(
"alice".to_string(),
None,
AuditAction::Create,
"order".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
manager
.log(
"bob".to_string(),
None,
AuditAction::Delete,
"order".to_string(),
"2".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
let filter = AuditLogFilter {
actor: Some("alice".to_string()),
..Default::default()
};
let logs = manager.get_logs(filter);
assert_eq!(logs.len(), 1);
assert_eq!(logs[0].actor, "alice");
}
#[test]
fn test_anomaly_detection() {
let manager = AuditLogManager::new();
// Create rapid activity
for _ in 0..6 {
manager
.log(
"suspicious_user".to_string(),
None,
AuditAction::Read,
"account".to_string(),
"acc_1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
}
let anomalies = manager.detect_anomalies();
assert!(!anomalies.is_empty());
}
#[test]
fn test_compliance_report() {
let manager = AuditLogManager::new();
let start = Utc::now();
manager
.log(
"user1".to_string(),
None,
AuditAction::Trade,
"order".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
let end = Utc::now();
let report = manager.generate_compliance_report(start, end);
assert_eq!(report.total_events, 1);
assert_eq!(report.unique_actors, 1);
assert!(report.integrity_verified);
}
#[test]
fn test_export_json() {
let manager = AuditLogManager::new();
manager
.log(
"user1".to_string(),
None,
AuditAction::Create,
"token".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
let json = manager.export_logs(ExportFormat::Json).unwrap();
assert!(json.contains("user1"));
}
#[test]
fn test_export_csv() {
let manager = AuditLogManager::new();
manager
.log(
"user1".to_string(),
None,
AuditAction::Create,
"token".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
let csv = manager.export_logs(ExportFormat::Csv).unwrap();
assert!(csv.contains("user1"));
assert!(csv.contains("id,timestamp,actor"));
}
#[test]
fn test_analytics() {
let manager = AuditLogManager::new();
manager
.log(
"alice".to_string(),
None,
AuditAction::Create,
"order".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
manager
.log(
"alice".to_string(),
None,
AuditAction::Update,
"order".to_string(),
"1".to_string(),
None,
None,
None,
None,
HashMap::new(),
)
.unwrap();
let analytics = manager.get_analytics();
let top_actors = analytics.top_actors(5);
assert_eq!(top_actors[0].0, "alice");
assert_eq!(top_actors[0].1, 2);
}
}