anya-core 1.2.0

Enterprise-grade Bitcoin Infrastructure Platform
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
use crate::security::hsm::error::{AuditEventResult, AuditEventSeverity, AuditEventType, HsmError};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{debug, warn};
use uuid::Uuid;

// [AIR-3][AIS-3][BPC-3][RES-3] Imports cleaned up for BDF v2.5 compliance

/// Audit logger configuration for HSM operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditLoggerConfig {
    /// Whether audit logging is enabled
    pub enabled: bool,

    /// Log storage type
    pub storage_type: AuditStorageType,

    /// File path for file storage
    pub file_path: Option<String>,

    /// Database connection string for DB storage
    pub db_connection: Option<String>,

    /// Retention period in days
    pub retention_days: u32,

    /// Maximum number of events to keep
    pub max_events: u32,

    /// Whether to log sensitive details
    pub log_sensitive: bool,

    /// Additional audit metrics to collect
    #[serde(default)]
    pub additional_metrics: Vec<String>,
}

impl Default for AuditLoggerConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            storage_type: AuditStorageType::File,
            file_path: Some("./logs/hsm_audit.log".to_string()),
            db_connection: None,
            retention_days: 90,
            max_events: 10000,
            log_sensitive: false,
            additional_metrics: vec![],
        }
    }
}

/// Type of storage for audit logs
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuditStorageType {
    /// In-memory storage (for testing)
    Memory,

    /// File-based storage
    File,

    /// Database storage
    Database,
}

/// Audit logger for HSM operations
/// [AIR-3][AIS-3][AIM-3][AIP-3][RES-3]
#[derive(Debug)]
pub struct AuditLogger {
    /// Configuration for the audit logger
    config: AuditLoggerConfig,

    /// Storage for audit events
    storage: Arc<Mutex<Box<dyn AuditStorage + Send + Sync>>>,

    /// Operation tracker for tracking related operations
    operation_tracker: Arc<Mutex<HashMap<String, (DateTime<Utc>, String)>>>,
}

impl AuditLogger {
    /// Creates a new audit logger with the specified configuration
    pub async fn new(config: &AuditLoggerConfig) -> Result<Self, HsmError> {
        debug!(
            "Creating HSM audit logger with storage type: {:?}",
            config.storage_type
        );

        // Create storage based on configuration
        let storage = create_storage(config).await?;

        let logger = Self {
            config: config.clone(),
            storage: Arc::new(Mutex::new(storage)),
            operation_tracker: Arc::new(Mutex::new(HashMap::new())),
        };

        // Initialize the storage
        logger.initialize().await?;

        Ok(logger)
    }

    /// Initializes the audit logger
    pub async fn initialize(&self) -> Result<(), HsmError> {
        debug!("Initializing HSM audit logger");

        // Initialize the storage
        let storage = self.storage.lock().await;
        storage.initialize().await?;

        // Log initialization event
        let event = AuditEvent::new(
            AuditEventType::HsmInitialize,
            AuditEventResult::Success,
            AuditEventSeverity::Info,
        );

        storage.store_event(event).await?;

        // Perform cleanup if needed
        if let Err(e) = storage
            .cleanup(
                self.config.retention_days,
                Some(self.config.max_events as usize),
            )
            .await
        {
            warn!("Failed to cleanup audit logs: {}", e);
        }

        debug!("HSM audit logger initialized");
        Ok(())
    }

    /// Logs an HSM event
    pub async fn log_event<T: Serialize>(
        &self,
        event_type: AuditEventType,
        result: AuditEventResult,
        severity: AuditEventSeverity,
        details: T,
    ) -> Result<(), HsmError> {
        if !self.config.enabled {
            return Ok(());
        }

        let details_value = serde_json::to_value(details)
            .map_err(|e| HsmError::SerializationError(e.to_string()))?;

        let mut event = AuditEvent::new(event_type, result, severity);

        // Add details to the event
        let details_map: HashMap<String, String> =
            match serde_json::from_value(details_value.clone()) {
                Ok(map) => map,
                Err(_) => {
                    // If we can't convert to a HashMap, create a single detail entry
                    let mut map = HashMap::new();
                    map.insert(
                        "data".to_string(),
                        serde_json::to_string(&details_value).unwrap_or_default(),
                    );
                    map
                }
            };

        for (key, value) in details_map {
            event = event.with_detail(key, value);
        }

        let storage = self.storage.lock().await;
        storage.store_event(event).await
    }

    /// Compatibility log method for legacy code
    pub async fn log<T: serde::Serialize>(
        &self,
        event_type: crate::security::hsm::error::AuditEventType,
        result: crate::security::hsm::error::AuditEventResult,
        severity: crate::security::hsm::error::AuditEventSeverity,
        details: T,
    ) -> Result<(), crate::security::hsm::error::HsmError> {
        self.log_event(event_type, result, severity, details).await
    }

    /// Compatibility method for legacy code that uses the types::HsmAuditEvent
    pub async fn log_event_legacy(
        &self,
        _event_name: &str,
        event: &crate::security::hsm::types::HsmAuditEvent,
    ) -> Result<(), HsmError> {
        if !self.config.enabled {
            return Ok(());
        }

        // Convert the legacy HsmAuditEvent to parameters for the standard log_event method
        let event_type = match event.event_type.as_str() {
            "health_check" => AuditEventType::HsmInitialize,
            "key_generation" => AuditEventType::KeyGeneration,
            "encryption" => AuditEventType::Encrypt,
            "decryption" => AuditEventType::Decrypt,
            "signing" => AuditEventType::Sign,
            "verification" => AuditEventType::Verify,
            "key_rotation" => AuditEventType::KeyRotation,
            "operation" => AuditEventType::OperationRequest,
            _ => AuditEventType::Custom(event.event_type.clone()),
        };

        let result = match event.status.as_str() {
            "started" => AuditEventResult::InProgress,
            "success" => AuditEventResult::Success,
            "failed" => AuditEventResult::Failure,
            _ => AuditEventResult::InProgress,
        };

        let severity = AuditEventSeverity::Info;

        // Build a details object
        let details = serde_json::json!({
            "provider": event.provider,
            "status": event.status,
            "details": event.details,
            "operation_id": event.operation_id,
        });

        self.log_event(event_type, result, severity, details).await
    }

    /// Gets events from the audit log
    pub async fn get_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<AuditEvent>, HsmError> {
        if !self.config.enabled {
            return Ok(Vec::new());
        }

        let storage = self.storage.lock().await;
        storage.get_events(start_time, end_time, limit).await
    }

    /// Count audit events
    pub async fn count_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<usize, HsmError> {
        if !self.config.enabled {
            return Ok(0);
        }

        let storage = self.storage.lock().await;
        storage.count_events(start_time, end_time).await
    }

    /// Clean up old events
    pub async fn cleanup(&self) -> Result<usize, HsmError> {
        if !self.config.enabled {
            return Ok(0);
        }

        let storage = self.storage.lock().await;
        storage
            .cleanup(
                self.config.retention_days,
                Some(self.config.max_events as usize),
            )
            .await
    }

    /// Track an operation
    pub async fn track_operation(&self, operation_id: &str, details: &str) -> Result<(), HsmError> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut tracker = self.operation_tracker.lock().await;
        tracker.insert(operation_id.to_string(), (Utc::now(), details.to_string()));
        Ok(())
    }

    /// Check if an operation is being tracked
    pub async fn is_operation_tracked(&self, operation_id: &str) -> bool {
        if !self.config.enabled {
            return false;
        }

        let tracker = self.operation_tracker.lock().await;
        tracker.contains_key(operation_id)
    }

    /// Get operation details
    pub async fn get_operation_details(
        &self,
        operation_id: &str,
    ) -> Option<(DateTime<Utc>, String)> {
        if !self.config.enabled {
            return None;
        }

        let tracker = self.operation_tracker.lock().await;
        tracker.get(operation_id).cloned()
    }

    /// Remove tracked operation
    pub async fn remove_operation(&self, operation_id: &str) -> Result<(), HsmError> {
        if !self.config.enabled {
            return Ok(());
        }

        let mut tracker = self.operation_tracker.lock().await;
        tracker.remove(operation_id);
        Ok(())
    }
}

/// Creates an appropriate storage backend based on configuration
async fn create_storage(
    config: &AuditLoggerConfig,
) -> Result<Box<dyn AuditStorage + Send + Sync>, HsmError> {
    match config.storage_type {
        AuditStorageType::Memory => Ok(Box::new(MemoryAuditStorage::new())),
        AuditStorageType::File => {
            let path = config.file_path.clone().ok_or_else(|| {
                HsmError::ConfigError("File path is required for file storage".to_string())
            })?;

            Ok(Box::new(FileAuditStorage::new(path)))
        }
        AuditStorageType::Database => {
            let conn_string = config.db_connection.clone().ok_or_else(|| {
                HsmError::ConfigError(
                    "Database connection string is required for DB storage".to_string(),
                )
            })?;

            Ok(Box::new(DbAuditStorage::new(conn_string)))
        }
    }
}

/// Storage trait for audit events
#[async_trait]
pub trait AuditStorage: std::fmt::Debug {
    /// Initialize the storage
    async fn initialize(&self) -> Result<(), HsmError>;

    /// Store an audit event
    async fn store_event(&self, event: AuditEvent) -> Result<(), HsmError>;

    /// Get audit events matching criteria
    async fn get_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<AuditEvent>, HsmError>;

    /// Count audit events matching criteria
    async fn count_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<usize, HsmError>;

    /// Clean up old events
    async fn cleanup(
        &self,
        retention_days: u32,
        max_events: Option<usize>,
    ) -> Result<usize, HsmError>;
}

/// Audit event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEvent {
    /// Unique event ID
    pub id: String,

    /// Timestamp of the event
    pub timestamp: DateTime<Utc>,

    /// Type of event
    pub event_type: String,

    /// Result of the event
    pub result: String,

    /// Severity of the event
    pub severity: String,

    /// User or service that performed the operation
    pub actor: Option<String>,

    /// Operation ID (for tracking related events)
    pub operation_id: Option<String>,

    /// Key ID (if applicable)
    pub key_id: Option<String>,

    /// Error message (if applicable)
    pub error: Option<String>,

    /// Additional details
    pub details: HashMap<String, String>,

    /// IP address of the client (if applicable)
    pub client_ip: Option<String>,
}

impl AuditEvent {
    /// Create a new audit event
    pub fn new(
        event_type: AuditEventType,
        result: AuditEventResult,
        severity: AuditEventSeverity,
    ) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            timestamp: Utc::now(),
            event_type: event_type.to_string(),
            result: result.to_string(),
            severity: severity.to_string(),
            actor: None,
            operation_id: None,
            key_id: None,
            error: None,
            details: HashMap::new(),
            client_ip: None,
        }
    }

    /// Create a new success event
    pub fn success(event_type: AuditEventType) -> Self {
        Self::new(
            event_type,
            AuditEventResult::Success,
            AuditEventSeverity::Info,
        )
    }

    /// Create a new failure event
    pub fn failure(event_type: AuditEventType, error: impl Into<String>) -> Self {
        let mut event = Self::new(
            event_type,
            AuditEventResult::Failure,
            AuditEventSeverity::Error,
        );
        event.error = Some(error.into());
        event
    }

    /// Create a new in-progress event
    pub fn in_progress(event_type: AuditEventType) -> Self {
        Self::new(
            event_type,
            AuditEventResult::InProgress,
            AuditEventSeverity::Info,
        )
    }

    /// Set actor
    pub fn with_actor(mut self, actor: impl Into<String>) -> Self {
        self.actor = Some(actor.into());
        self
    }

    /// Set operation ID
    pub fn with_operation_id(mut self, operation_id: impl Into<String>) -> Self {
        self.operation_id = Some(operation_id.into());
        self
    }

    /// Set key ID
    pub fn with_key_id(mut self, key_id: impl Into<String>) -> Self {
        self.key_id = Some(key_id.into());
        self
    }

    /// Add detail
    pub fn with_detail(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.details.insert(key.into(), value.into());
        self
    }

    /// Set client IP
    pub fn with_client_ip(mut self, client_ip: impl Into<String>) -> Self {
        self.client_ip = Some(client_ip.into());
        self
    }

    /// Convert to HsmAuditEvent
    pub fn to_hsm_audit_event(&self) -> crate::security::hsm::error::HsmAuditEvent {
        use crate::security::hsm::error::{
            AuditEventResult, AuditEventSeverity, AuditEventType, HsmAuditEvent,
        };

        // Convert the string type to AuditEventType enum
        let event_type = match self.event_type.as_str() {
            "HsmOperation" => AuditEventType::HsmOperation,
            "KeyGeneration" => AuditEventType::KeyGeneration,
            "Authentication" => AuditEventType::Authentication,
            // Fixed: Authorization doesn't exist in AuditEventType, using Custom instead
            "Authorization" => AuditEventType::Custom("Authorization".to_string()),
            "ConfigChange" => AuditEventType::ConfigChange,
            _ => AuditEventType::Custom(self.event_type.clone()),
        };

        // Convert the string result to AuditEventResult enum
        let result = match self.result.as_str() {
            "Success" => AuditEventResult::Success,
            "Failure" => AuditEventResult::Failure,
            // Fixed: These variants don't exist in AuditEventResult
            "Denied" => AuditEventResult::Rejected, // Using closest match
            "Error" => AuditEventResult::Failure,   // Using closest match
            "Timeout" => AuditEventResult::Timeout,
            _ => AuditEventResult::Unknown,
        };

        // Convert the string severity to AuditEventSeverity enum
        let severity = match self.severity.as_str() {
            "Critical" => AuditEventSeverity::Critical,
            "Error" => AuditEventSeverity::Error,
            "Warning" => AuditEventSeverity::Warning,
            "Info" => AuditEventSeverity::Info,
            "Debug" => AuditEventSeverity::Debug,
            _ => AuditEventSeverity::Info,
        };

        // Create the base event
        let mut event = HsmAuditEvent::new(event_type, result, severity);

        // Build up parameters and metadata for a single call
        let mut metadata = serde_json::Map::new();
        let mut params = serde_json::Map::new();

        // Add actor and key_id directly without moving event
        if let Some(actor) = &self.actor {
            event = event.with_user(actor.clone());
        }

        if let Some(key_id) = &self.key_id {
            event = event.with_key(key_id.clone());
        }

        // Add error to metadata if present
        if let Some(error) = &self.error {
            metadata.insert(
                "error".to_string(),
                serde_json::Value::String(error.clone()),
            );
        }

        // Add all details to metadata
        for (key, value) in &self.details {
            metadata.insert(key.clone(), serde_json::Value::String(value.clone()));
        }

        // Add operation_id to parameters if present
        if let Some(operation_id) = &self.operation_id {
            params.insert(
                "operation_id".to_string(),
                serde_json::Value::String(operation_id.clone()),
            );
        }

        // Apply metadata and parameters at the end - avoiding multiple moves
        if !metadata.is_empty() {
            event = match event
                .clone()
                .with_metadata(&serde_json::Value::Object(metadata))
            {
                Ok(updated_event) => updated_event,
                Err(_) => event, // Keep original event if metadata application fails
            };
        }

        if !params.is_empty() {
            event = match event
                .clone()
                .with_parameters(&serde_json::Value::Object(params))
            {
                Ok(updated_event) => updated_event,
                Err(_) => event, // Keep original event if parameters application fails
            };
        }

        event
    }
}

/// In-memory storage for audit events (for testing)
#[derive(Debug)]
pub struct MemoryAuditStorage {
    events: Mutex<Vec<AuditEvent>>,
}

impl MemoryAuditStorage {
    pub fn new() -> Self {
        Self {
            events: Mutex::new(Vec::new()),
        }
    }
}

#[async_trait]
impl AuditStorage for MemoryAuditStorage {
    async fn initialize(&self) -> Result<(), HsmError> {
        // No initialization needed for in-memory storage
        Ok(())
    }

    async fn store_event(&self, event: AuditEvent) -> Result<(), HsmError> {
        let mut events = self.events.lock().await;
        events.push(event);
        Ok(())
    }

    async fn get_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<AuditEvent>, HsmError> {
        let events = self.events.lock().await;

        let filtered_events: Vec<AuditEvent> = events
            .iter()
            .filter(|event| {
                if let Some(start) = start_time {
                    if event.timestamp < start {
                        return false;
                    }
                }

                if let Some(end) = end_time {
                    if event.timestamp > end {
                        return false;
                    }
                }

                true
            })
            .cloned()
            .collect();

        let result = if let Some(limit_val) = limit {
            filtered_events.into_iter().take(limit_val).collect()
        } else {
            filtered_events
        };

        Ok(result)
    }

    async fn count_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<usize, HsmError> {
        let events = self.events.lock().await;

        let count = events
            .iter()
            .filter(|event| {
                if let Some(start) = start_time {
                    if event.timestamp < start {
                        return false;
                    }
                }

                if let Some(end) = end_time {
                    if event.timestamp > end {
                        return false;
                    }
                }

                true
            })
            .count();

        Ok(count)
    }

    async fn cleanup(
        &self,
        retention_days: u32,
        max_events: Option<usize>,
    ) -> Result<usize, HsmError> {
        let mut events = self.events.lock().await;
        let initial_count = events.len();

        // Remove old events
        let cutoff = Utc::now() - chrono::Duration::days(retention_days as i64);
        events.retain(|e| e.timestamp >= cutoff);

        // Apply max events limit
        if let Some(max) = max_events {
            if events.len() > max {
                // Sort by timestamp (newest first)
                events.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
                events.truncate(max);
            }
        }

        let removed = initial_count - events.len();
        Ok(removed)
    }
}

/// File-based storage for audit events
#[derive(Debug)]
pub struct FileAuditStorage {
    file_path: String,
}

impl FileAuditStorage {
    pub fn new(file_path: String) -> Self {
        Self { file_path }
    }

    /// Load events from file
    async fn load_events(&self) -> Result<Vec<AuditEvent>, HsmError> {
        let path = Path::new(&self.file_path);

        // If file doesn't exist, return empty vector
        if !path.exists() {
            return Ok(Vec::new());
        }

        // Read file contents
        let contents = fs::read_to_string(path).map_err(|e| {
            HsmError::AuditStorageError(format!("Failed to read audit log file: {}", e))
        })?;

        // Parse events (each line is a JSON object)
        let mut events = Vec::new();
        for line in contents.lines() {
            if line.trim().is_empty() {
                continue;
            }

            match serde_json::from_str::<AuditEvent>(line) {
                Ok(event) => events.push(event),
                Err(e) => {
                    warn!("Failed to parse audit event: {}", e);
                }
            }
        }

        Ok(events)
    }
}

#[async_trait]
impl AuditStorage for FileAuditStorage {
    async fn initialize(&self) -> Result<(), HsmError> {
        let file_path = &self.file_path;
        let dir_path = Path::new(file_path).parent();

        if let Some(dir) = dir_path {
            if !dir.exists() {
                fs::create_dir_all(dir).map_err(|e| {
                    HsmError::AuditStorageError(format!("Failed to create directory: {}", e))
                })?;
            }
        }

        // Create the file if it doesn't exist
        if !Path::new(file_path).exists() {
            File::create(file_path).map_err(|e| {
                HsmError::AuditStorageError(format!("Failed to create audit log file: {}", e))
            })?;
        }

        Ok(())
    }

    async fn store_event(&self, event: AuditEvent) -> Result<(), HsmError> {
        // Serialize the event
        let json = serde_json::to_string(&event)
            .map_err(|e| HsmError::SerializationError(e.to_string()))?;

        // Open the file in append mode
        let mut file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.file_path)
            .map_err(|e| {
                HsmError::AuditStorageError(format!("Failed to open audit log file: {}", e))
            })?;

        // Write the event with a newline
        writeln!(file, "{}", json).map_err(|e| {
            HsmError::AuditStorageError(format!("Failed to write to audit log file: {}", e))
        })?;

        Ok(())
    }

    async fn get_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<AuditEvent>, HsmError> {
        // Load all events
        let mut events = self.load_events().await?;

        // Filter by time range
        if let Some(start) = start_time {
            events.retain(|e| e.timestamp >= start);
        }

        if let Some(end) = end_time {
            events.retain(|e| e.timestamp <= end);
        }

        // Sort by timestamp (newest first)
        events.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));

        // Apply limit
        if let Some(lim) = limit {
            events.truncate(lim);
        }

        Ok(events)
    }

    async fn count_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<usize, HsmError> {
        // Load and filter events
        let events = self.load_events().await?;

        let count = events
            .iter()
            .filter(|e| {
                if let Some(start) = start_time {
                    if e.timestamp < start {
                        return false;
                    }
                }

                if let Some(end) = end_time {
                    if e.timestamp > end {
                        return false;
                    }
                }

                true
            })
            .count();

        Ok(count)
    }

    async fn cleanup(
        &self,
        retention_days: u32,
        max_events: Option<usize>,
    ) -> Result<usize, HsmError> {
        // Load all events
        let mut events = self.load_events().await?;
        let initial_count = events.len();

        // Filter out old events
        let cutoff = Utc::now() - chrono::Duration::days(retention_days as i64);
        events.retain(|e| e.timestamp >= cutoff);

        // Apply max events limit
        if let Some(max) = max_events {
            if events.len() > max {
                // Sort by timestamp (newest first)
                events.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
                events.truncate(max);
            }
        }

        // If we removed any events, rewrite the file
        if events.len() < initial_count {
            // Open file for writing (truncate)
            let mut file = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&self.file_path)
                .map_err(|e| {
                    HsmError::AuditStorageError(format!("Failed to open audit log file: {}", e))
                })?;

            // Write each event
            for event in &events {
                let json = serde_json::to_string(event)
                    .map_err(|e| HsmError::SerializationError(e.to_string()))?;

                writeln!(file, "{}", json).map_err(|e| {
                    HsmError::AuditStorageError(format!("Failed to write to audit log file: {}", e))
                })?;
            }
        }

        Ok(initial_count - events.len())
    }
}

/// Database storage for audit events
#[derive(Debug)]
pub struct DbAuditStorage {
    memory_storage: MemoryAuditStorage, // Fallback storage
}

impl DbAuditStorage {
    pub fn new(_connection_string: String) -> Self {
        Self {
            memory_storage: MemoryAuditStorage::new(),
        }
    }
}

#[async_trait]
impl AuditStorage for DbAuditStorage {
    async fn initialize(&self) -> Result<(), HsmError> {
        // In a real implementation, this would initialize the database
        // For now, just use the memory storage as a fallback
        debug!("Initializing database audit storage (using memory fallback)");
        self.memory_storage.initialize().await
    }

    async fn store_event(&self, event: AuditEvent) -> Result<(), HsmError> {
        // In a real implementation, this would store in the database
        // For now, just use the memory storage as a fallback
        debug!(
            "Storing event in database (using memory fallback): {}",
            event.id
        );
        self.memory_storage.store_event(event).await
    }

    async fn get_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
        limit: Option<usize>,
    ) -> Result<Vec<AuditEvent>, HsmError> {
        // In a real implementation, this would query the database
        // For now, just use the memory storage as a fallback
        debug!("Getting events from database (using memory fallback)");
        self.memory_storage
            .get_events(start_time, end_time, limit)
            .await
    }

    async fn count_events(
        &self,
        start_time: Option<DateTime<Utc>>,
        end_time: Option<DateTime<Utc>>,
    ) -> Result<usize, HsmError> {
        // In a real implementation, this would count in the database
        // For now, just use the memory storage as a fallback
        debug!("Counting events in database (using memory fallback)");
        self.memory_storage.count_events(start_time, end_time).await
    }

    async fn cleanup(
        &self,
        retention_days: u32,
        max_events: Option<usize>,
    ) -> Result<usize, HsmError> {
        // In a real implementation, this would delete from the database
        // For now, just use the memory storage as a fallback
        debug!("Cleaning up database (using memory fallback)");
        self.memory_storage
            .cleanup(retention_days, max_events)
            .await
    }
}