Skip to main content

qualia_core_db/specialized_libs/cryptographic_library/
security.rs

1// Part of the cryptographic_library module (split from the former mod.rs monolith
2// per CLAUDE.md §11 — pure code motion, no behaviour change).
3use super::*;
4
5/// Security monitor
6pub struct SecurityMonitor {
7    threat_detector: ThreatDetector,
8    anomaly_detector: AnomalyDetector,
9    compliance_monitor: ComplianceMonitor,
10    security_metrics: SecurityMetrics,
11}
12
13/// Threat detector
14pub struct ThreatDetector {
15    threat_signatures: HashMap<String, ThreatSignature>,
16    detection_rules: Vec<DetectionRule>,
17    alert_system: SecurityAlertSystem,
18}
19
20/// Threat signatures
21#[derive(Debug, Clone)]
22pub struct ThreatSignature {
23    pub signature_id: String,
24    pub threat_type: ThreatType,
25    pub pattern: Vec<u8>,
26    pub severity: ThreatSeverity,
27    pub description: String,
28}
29
30/// Threat types
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub enum ThreatType {
33    MaliciousKey,
34    CompromisedCertificate,
35    WeakAlgorithm,
36    SideChannelAttack,
37    TimingAttack,
38    Custom(String),
39}
40
41/// Threat severity
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub enum ThreatSeverity {
44    Low,
45    Medium,
46    High,
47    Critical,
48}
49
50/// Detection rules
51#[derive(Debug, Clone)]
52pub struct DetectionRule {
53    pub rule_id: String,
54    pub rule_type: DetectionRuleType,
55    pub conditions: Vec<DetectionCondition>,
56    pub actions: Vec<DetectionAction>,
57}
58
59/// Detection rule types
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub enum DetectionRuleType {
62    Signature,
63    Heuristic,
64    Behavioral,
65    Statistical,
66    Custom(String),
67}
68
69/// Detection conditions
70#[derive(Debug, Clone)]
71pub struct DetectionCondition {
72    pub condition_id: String,
73    pub field: String,
74    pub operator: ComparisonOperator,
75    pub value: Vec<u8>,
76}
77
78/// Comparison operators
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub enum ComparisonOperator {
81    Equals,
82    NotEquals,
83    GreaterThan,
84    LessThan,
85    Contains,
86    Matches,
87}
88
89/// Detection actions
90#[derive(Debug, Clone)]
91pub struct DetectionAction {
92    pub action_id: String,
93    pub action_type: DetectionActionType,
94    pub parameters: HashMap<String, Vec<u8>>,
95}
96
97/// Detection action types
98#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99pub enum DetectionActionType {
100    Alert,
101    Block,
102    Quarantine,
103    Log,
104    Custom(String),
105}
106
107/// Escalation policy for security alerts
108#[derive(Debug, Clone)]
109pub struct EscalationPolicy {
110    pub policy_id: String,
111    pub trigger_conditions: Vec<String>,
112    pub timeout: u64,
113}
114
115/// Security alert system
116pub struct SecurityAlertSystem {
117    alert_types: Vec<SecurityAlertType>,
118    notification_channels: Vec<NotificationChannel>,
119    escalation_policies: Vec<EscalationPolicy>,
120}
121
122/// Security alert types
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124pub enum SecurityAlertType {
125    Threat,
126    Anomaly,
127    Compliance,
128    System,
129    Custom(String),
130}
131
132/// Anomaly detector
133pub struct AnomalyDetector {
134    detection_algorithms: Vec<AnomalyDetectionAlgorithm>,
135    baseline_models: HashMap<String, BaselineModel>,
136    alert_thresholds: HashMap<String, f64>,
137}
138
139/// Anomaly detection algorithms
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141pub enum AnomalyDetectionAlgorithm {
142    Statistical,
143    MachineLearning,
144    DeepLearning,
145    Ensemble,
146    Custom(String),
147}
148
149/// Baseline model
150#[derive(Debug, Clone)]
151pub struct BaselineModel {
152    pub model_id: String,
153    pub model_type: ModelType,
154    pub parameters: Vec<f64>,
155    pub accuracy: f64,
156}
157
158/// Model types
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
160pub enum ModelType {
161    Statistical,
162    NeuralNetwork,
163    DecisionTree,
164    Custom(String),
165}
166
167/// Compliance monitor
168pub struct ComplianceMonitor {
169    compliance_frameworks: HashMap<String, ComplianceFramework>,
170    audit_trail: AuditTrail,
171    reporting_engine: ComplianceReportingEngine,
172}
173
174/// Compliance frameworks
175#[derive(Debug, Clone)]
176pub struct ComplianceFramework {
177    pub framework_id: String,
178    pub framework_name: String,
179    pub requirements: Vec<ComplianceRequirement>,
180    pub controls: Vec<ComplianceControl>,
181}
182
183/// Compliance controls
184#[derive(Debug, Clone)]
185pub struct ComplianceControl {
186    pub control_id: String,
187    pub control_name: String,
188    pub control_type: ControlType,
189    pub implementation_status: ImplementationStatus,
190}
191
192/// Control types
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
194pub enum ControlType {
195    Preventive,
196    Detective,
197    Corrective,
198    Compensating,
199}
200
201/// Implementation status
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub enum ImplementationStatus {
204    Implemented,
205    PartiallyImplemented,
206    NotImplemented,
207    NotApplicable,
208}
209
210/// Audit trail
211pub struct AuditTrail {
212    entries: Vec<AuditEntry>,
213    retention_policy: RetentionPolicy,
214}
215
216/// Audit entry
217#[derive(Debug, Clone)]
218pub struct AuditEntry {
219    pub entry_id: String,
220    pub timestamp: u64,
221    pub event_type: EventType,
222    pub user_id: String,
223    pub resource_id: String,
224    pub action: String,
225    pub result: AuditResult,
226}
227
228/// Event types
229#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
230pub enum EventType {
231    KeyOperation,
232    SignatureOperation,
233    EncryptionOperation,
234    ProofOperation,
235    SecurityEvent,
236    ComplianceEvent,
237}
238
239/// Audit results
240#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
241pub enum AuditResult {
242    Success,
243    Failure,
244    Warning,
245    Error,
246}
247
248/// Compliance reporting engine
249pub struct ComplianceReportingEngine {
250    report_templates: HashMap<String, ReportTemplate>,
251    scheduling_engine: ReportSchedulingEngine,
252    distribution_engine: ReportDistributionEngine,
253}
254
255/// Report templates
256#[derive(Debug, Clone)]
257pub struct ReportTemplate {
258    pub template_id: String,
259    pub template_name: String,
260    pub sections: Vec<ReportSection>,
261    pub format: ReportFormat,
262}
263
264/// Report sections
265#[derive(Debug, Clone)]
266pub struct ReportSection {
267    pub section_id: String,
268    pub section_name: String,
269    pub content_generator: ContentGenerator,
270    pub data_sources: Vec<String>,
271}
272
273/// Content generators
274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
275pub enum ContentGenerator {
276    Static,
277    Dynamic,
278    Template,
279    Custom(String),
280}
281
282/// Report formats
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284pub enum ReportFormat {
285    PDF,
286    HTML,
287    JSON,
288    XML,
289    CSV,
290    Custom(String),
291}
292
293/// Report scheduling engine
294pub struct ReportSchedulingEngine {
295    schedules: HashMap<String, ReportSchedule>,
296    scheduler: ReportScheduler,
297}
298
299/// Report schedules
300#[derive(Debug, Clone)]
301pub struct ReportSchedule {
302    pub schedule_id: String,
303    pub template_id: String,
304    pub schedule_type: ScheduleType,
305    pub parameters: ScheduleParameters,
306}
307
308/// Schedule types
309#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
310pub enum ScheduleType {
311    Daily,
312    Weekly,
313    Monthly,
314    Quarterly,
315    Yearly,
316    OnDemand,
317    Custom(String),
318}
319
320/// Schedule parameters
321#[derive(Debug, Clone)]
322pub struct ScheduleParameters {
323    pub start_date: u64,
324    pub end_date: Option<u64>,
325    pub frequency: u32,
326    pub recipients: Vec<String>,
327}
328
329/// Report scheduler
330pub struct ReportScheduler {
331    scheduler_type: SchedulerType,
332    queue_manager: ReportQueueManager,
333}
334
335/// Scheduler types
336#[derive(Debug, Clone, PartialEq)]
337pub enum SchedulerType {
338    Cron,
339    Interval,
340    EventDriven,
341    Custom(String),
342}
343
344/// Report queue manager
345pub struct ReportQueueManager {
346    pending_reports: Vec<QueuedReport>,
347    running_reports: Vec<RunningReport>,
348    completed_reports: Vec<CompletedReport>,
349}
350
351/// Queued report
352#[derive(Debug, Clone)]
353pub struct QueuedReport {
354    pub report_id: String,
355    pub template_id: String,
356    pub queued_at: u64,
357    pub priority: ReportPriority,
358}
359
360/// Report priorities
361#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
362pub enum ReportPriority {
363    Low,
364    Normal,
365    High,
366    Critical,
367}
368
369/// Running report
370#[derive(Debug, Clone)]
371pub struct RunningReport {
372    pub report_id: String,
373    pub started_at: u64,
374    pub progress: f64,
375}
376
377/// Completed report
378#[derive(Debug, Clone)]
379pub struct CompletedReport {
380    pub report_id: String,
381    pub template_id: String,
382    pub started_at: u64,
383    pub completed_at: u64,
384    pub success: bool,
385}
386
387/// Report distribution engine
388pub struct ReportDistributionEngine {
389    distribution_channels: HashMap<String, DistributionChannel>,
390    delivery_tracker: DeliveryTracker,
391}
392
393/// Distribution channels
394#[derive(Debug, Clone)]
395pub struct DistributionChannel {
396    pub channel_id: String,
397    pub channel_type: DistributionChannelType,
398    pub configuration: ChannelConfiguration,
399}
400
401/// Distribution channel types
402#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
403pub enum DistributionChannelType {
404    Email,
405    FTP,
406    SFTP,
407    API,
408    Webhook,
409    Custom(String),
410}
411
412/// Channel configuration
413#[derive(Debug, Clone)]
414pub struct ChannelConfiguration {
415    pub endpoint: String,
416    pub authentication: AuthenticationMethod,
417    pub encryption: bool,
418    pub retry_policy: RetryPolicy,
419}
420
421/// Retry policy
422#[derive(Debug, Clone)]
423pub struct RetryPolicy {
424    pub max_attempts: u32,
425    pub backoff_strategy: BackoffStrategy,
426    pub retry_intervals: Vec<u64>,
427}
428
429/// Backoff strategies
430#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
431pub enum BackoffStrategy {
432    Fixed,
433    Linear,
434    Exponential,
435    Custom(String),
436}
437
438/// Delivery tracker
439pub struct DeliveryTracker {
440    deliveries: HashMap<String, DeliveryRecord>,
441    status: DeliveryStatus,
442}
443
444/// Delivery records
445#[derive(Debug, Clone)]
446pub struct DeliveryRecord {
447    pub record_id: String,
448    pub report_id: String,
449    pub channel_id: String,
450    pub attempts: Vec<DeliveryAttempt>,
451    pub final_status: DeliveryFinalStatus,
452}
453
454/// Delivery attempts
455#[derive(Debug, Clone)]
456pub struct DeliveryAttempt {
457    pub attempt_number: u32,
458    pub timestamp: u64,
459    pub success: bool,
460    pub error_message: Option<String>,
461}
462
463/// Delivery final status
464#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
465pub enum DeliveryFinalStatus {
466    Delivered,
467    Failed,
468    Pending,
469    Cancelled,
470}
471
472/// Delivery status
473#[derive(Debug, Clone)]
474pub struct DeliveryStatus {
475    pub total_deliveries: u64,
476    pub successful_deliveries: u64,
477    pub failed_deliveries: u64,
478    pub pending_deliveries: u64,
479}
480
481/// Security metrics
482#[derive(Debug, Clone)]
483pub struct SecurityMetrics {
484    pub threat_metrics: ThreatMetrics,
485    pub anomaly_metrics: AnomalyMetrics,
486    pub compliance_metrics: ComplianceMetrics,
487    pub performance_metrics: SecurityPerformanceMetrics,
488}
489
490/// Threat metrics
491#[derive(Debug, Clone)]
492pub struct ThreatMetrics {
493    pub threats_detected: u64,
494    pub threats_blocked: u64,
495    pub false_positives: u64,
496    pub detection_rate: f64,
497    pub response_time: f64,
498}
499
500/// Anomaly metrics
501#[derive(Debug, Clone)]
502pub struct AnomalyMetrics {
503    pub anomalies_detected: u64,
504    pub anomalies_investigated: u64,
505    pub confirmed_anomalies: u64,
506    pub false_positive_rate: f64,
507    pub detection_accuracy: f64,
508}
509
510/// Compliance metrics
511#[derive(Debug, Clone)]
512pub struct ComplianceMetrics {
513    pub compliance_score: f64,
514    pub controls_implemented: u64,
515    pub controls_passed: u64,
516    pub audit_findings: u64,
517    pub remediation_rate: f64,
518}
519
520/// Security performance metrics
521#[derive(Debug, Clone)]
522pub struct SecurityPerformanceMetrics {
523    pub average_response_time: f64,
524    pub throughput: f64,
525    pub resource_utilization: f64,
526    pub error_rate: f64,
527}
528impl SecurityMonitor {
529    /// Creates a monitor with fresh threat detector, anomaly detector, compliance monitor, and zeroed metrics.
530    pub fn new() -> Self {
531        Self {
532            threat_detector: ThreatDetector::new(),
533            anomaly_detector: AnomalyDetector::new(),
534            compliance_monitor: ComplianceMonitor::new(),
535            security_metrics: SecurityMetrics::new(),
536        }
537    }
538
539    /// Initializes the threat detector, anomaly detector, and compliance monitor.
540    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
541        self.threat_detector.initialize()?;
542        self.anomaly_detector.initialize()?;
543        self.compliance_monitor.initialize()?;
544        Ok(())
545    }
546
547    /// Returns a snapshot of the current security metrics.
548    pub fn get_metrics(&self) -> SecurityMetrics {
549        self.security_metrics.clone()
550    }
551}
552
553impl ThreatDetector {
554    /// Creates a detector with empty signature/rule registries and a fresh alert system.
555    pub fn new() -> Self {
556        Self {
557            threat_signatures: HashMap::new(),
558            detection_rules: Vec::new(),
559            alert_system: SecurityAlertSystem::new(),
560        }
561    }
562
563    /// Initializes the inner alert system.
564    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
565        self.alert_system.initialize()?;
566        Ok(())
567    }
568
569    /// Register a threat signature.
570    pub fn add_threat_signature(&mut self, signature: ThreatSignature) {
571        self.threat_signatures
572            .insert(signature.signature_id.clone(), signature);
573    }
574
575    /// Look up a threat signature by id.
576    pub fn get_threat_signature(&self, signature_id: &str) -> Option<&ThreatSignature> {
577        self.threat_signatures.get(signature_id)
578    }
579
580    /// Iterate over all registered threat signatures.
581    pub fn list_threat_signatures(&self) -> impl Iterator<Item = &ThreatSignature> {
582        self.threat_signatures.values()
583    }
584
585    /// Add a detection rule.
586    pub fn add_detection_rule(&mut self, rule: DetectionRule) {
587        self.detection_rules.push(rule);
588    }
589
590    /// Iterate over all registered detection rules.
591    pub fn list_detection_rules(&self) -> impl Iterator<Item = &DetectionRule> {
592        self.detection_rules.iter()
593    }
594}
595
596impl SecurityAlertSystem {
597    /// Creates the alert system defaulting to Threat+Anomaly types over the Email channel.
598    pub fn new() -> Self {
599        Self {
600            alert_types: vec![SecurityAlertType::Threat, SecurityAlertType::Anomaly],
601            notification_channels: vec![NotificationChannel::Email],
602            escalation_policies: Vec::new(),
603        }
604    }
605
606    /// No-op — alert types/channels are set at construction.
607    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
608        Ok(())
609    }
610
611    /// Get the configured alert types.
612    pub fn alert_types(&self) -> &[SecurityAlertType] {
613        &self.alert_types
614    }
615
616    /// Add an alert type if not already present.
617    pub fn add_alert_type(&mut self, alert_type: SecurityAlertType) {
618        if !self.alert_types.contains(&alert_type) {
619            self.alert_types.push(alert_type);
620        }
621    }
622
623    /// Get the configured notification channels.
624    pub fn notification_channels(&self) -> &[NotificationChannel] {
625        &self.notification_channels
626    }
627
628    /// Add a notification channel if not already present.
629    pub fn add_notification_channel(&mut self, channel: NotificationChannel) {
630        if !self.notification_channels.contains(&channel) {
631            self.notification_channels.push(channel);
632        }
633    }
634
635    /// Add an escalation policy.
636    pub fn add_escalation_policy(&mut self, policy: EscalationPolicy) {
637        self.escalation_policies.push(policy);
638    }
639
640    /// Iterate over all registered escalation policies.
641    pub fn list_escalation_policies(&self) -> impl Iterator<Item = &EscalationPolicy> {
642        self.escalation_policies.iter()
643    }
644}
645
646impl AnomalyDetector {
647    /// Creates a detector with an empty baseline-model registry.
648    pub fn new() -> Self {
649        Self {
650            detection_algorithms: vec![AnomalyDetectionAlgorithm::Statistical],
651            baseline_models: HashMap::new(),
652            alert_thresholds: HashMap::new(),
653        }
654    }
655
656    /// No-op — baselines are registered per-entity by callers.
657    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
658        Ok(())
659    }
660
661    /// Get the configured detection algorithms.
662    pub fn detection_algorithms(&self) -> &[AnomalyDetectionAlgorithm] {
663        &self.detection_algorithms
664    }
665
666    /// Add a detection algorithm if not already present.
667    pub fn add_detection_algorithm(&mut self, algorithm: AnomalyDetectionAlgorithm) {
668        if !self.detection_algorithms.contains(&algorithm) {
669            self.detection_algorithms.push(algorithm);
670        }
671    }
672
673    /// Register a baseline model.
674    pub fn add_baseline_model(&mut self, model: BaselineModel) {
675        self.baseline_models.insert(model.model_id.clone(), model);
676    }
677
678    /// Look up a baseline model by id.
679    pub fn get_baseline_model(&self, model_id: &str) -> Option<&BaselineModel> {
680        self.baseline_models.get(model_id)
681    }
682
683    /// Iterate over all registered baseline models.
684    pub fn list_baseline_models(&self) -> impl Iterator<Item = &BaselineModel> {
685        self.baseline_models.values()
686    }
687
688    /// Set an alert threshold for a named metric.
689    pub fn set_alert_threshold(&mut self, metric: String, threshold: f64) {
690        self.alert_thresholds.insert(metric, threshold);
691    }
692
693    /// Look up an alert threshold by metric name.
694    pub fn get_alert_threshold(&self, metric: &str) -> Option<f64> {
695        self.alert_thresholds.get(metric).copied()
696    }
697}
698
699impl ComplianceMonitor {
700    /// Creates a monitor with an empty compliance-framework registry.
701    pub fn new() -> Self {
702        Self {
703            compliance_frameworks: HashMap::new(),
704            audit_trail: AuditTrail::new(),
705            reporting_engine: ComplianceReportingEngine::new(),
706        }
707    }
708
709    /// No-op — frameworks are registered by callers.
710    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
711        self.reporting_engine.initialize()?;
712        Ok(())
713    }
714
715    /// Register a compliance framework.
716    pub fn add_compliance_framework(&mut self, framework: ComplianceFramework) {
717        self.compliance_frameworks
718            .insert(framework.framework_id.clone(), framework);
719    }
720
721    /// Look up a compliance framework by id.
722    pub fn get_compliance_framework(&self, framework_id: &str) -> Option<&ComplianceFramework> {
723        self.compliance_frameworks.get(framework_id)
724    }
725
726    /// Iterate over all registered compliance frameworks.
727    pub fn list_compliance_frameworks(&self) -> impl Iterator<Item = &ComplianceFramework> {
728        self.compliance_frameworks.values()
729    }
730
731    /// Get a reference to the audit trail.
732    pub fn audit_trail(&self) -> &AuditTrail {
733        &self.audit_trail
734    }
735
736    /// Get a mutable reference to the audit trail.
737    pub fn audit_trail_mut(&mut self) -> &mut AuditTrail {
738        &mut self.audit_trail
739    }
740}
741
742impl AuditTrail {
743    /// Creates an empty audit trail.
744    pub fn new() -> Self {
745        Self {
746            entries: Vec::new(),
747            retention_policy: RetentionPolicy {
748                retention_days: 2555, // 7 years
749                auto_delete: false,
750                archive_before_delete: true,
751            },
752        }
753    }
754
755    /// Record an audit entry, enforcing retention policy.
756    pub fn add_entry(&mut self, entry: AuditEntry) {
757        let cutoff = entry
758            .timestamp
759            .saturating_sub((self.retention_policy.retention_days as u64) * 86400);
760        self.entries.retain(|e| e.timestamp >= cutoff);
761        self.entries.push(entry);
762    }
763
764    /// Number of recorded audit entries.
765    pub fn entry_count(&self) -> usize {
766        self.entries.len()
767    }
768
769    /// Iterate over audit entries.
770    pub fn entries(&self) -> &[AuditEntry] {
771        &self.entries
772    }
773
774    /// Get the retention policy for the audit trail.
775    pub fn retention_policy(&self) -> &RetentionPolicy {
776        &self.retention_policy
777    }
778}
779
780impl ComplianceReportingEngine {
781    /// Creates an engine with empty report-template/schedule/distribution registries.
782    pub fn new() -> Self {
783        Self {
784            report_templates: HashMap::new(),
785            scheduling_engine: ReportSchedulingEngine::new(),
786            distribution_engine: ReportDistributionEngine::new(),
787        }
788    }
789
790    /// Initializes the scheduling and distribution sub-engines.
791    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
792        self.scheduling_engine.initialize()?;
793        self.distribution_engine.initialize()?;
794        Ok(())
795    }
796
797    /// Register a report template.
798    pub fn add_report_template(&mut self, template: ReportTemplate) {
799        self.report_templates
800            .insert(template.template_id.clone(), template);
801    }
802
803    /// Look up a report template by id.
804    pub fn get_report_template(&self, template_id: &str) -> Option<&ReportTemplate> {
805        self.report_templates.get(template_id)
806    }
807
808    /// Iterate over all registered report templates.
809    pub fn list_report_templates(&self) -> impl Iterator<Item = &ReportTemplate> {
810        self.report_templates.values()
811    }
812}
813
814impl ReportSchedulingEngine {
815    /// Creates a scheduling engine with an empty schedule registry.
816    pub fn new() -> Self {
817        Self {
818            schedules: HashMap::new(),
819            scheduler: ReportScheduler::new(),
820        }
821    }
822
823    /// Initializes the inner scheduler and queue manager.
824    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
825        Ok(())
826    }
827
828    /// Register a report schedule.
829    pub fn add_schedule(&mut self, schedule: ReportSchedule) {
830        self.schedules
831            .insert(schedule.schedule_id.clone(), schedule);
832    }
833
834    /// Look up a report schedule by id.
835    pub fn get_schedule(&self, schedule_id: &str) -> Option<&ReportSchedule> {
836        self.schedules.get(schedule_id)
837    }
838
839    /// Iterate over all registered report schedules.
840    pub fn list_schedules(&self) -> impl Iterator<Item = &ReportSchedule> {
841        self.schedules.values()
842    }
843
844    /// Get a reference to the report scheduler.
845    pub fn scheduler(&self) -> &ReportScheduler {
846        &self.scheduler
847    }
848
849    /// Get a mutable reference to the report scheduler.
850    pub fn scheduler_mut(&mut self) -> &mut ReportScheduler {
851        &mut self.scheduler
852    }
853}
854
855impl ReportScheduler {
856    /// Creates a scheduler with no queued or running reports.
857    pub fn new() -> Self {
858        Self {
859            scheduler_type: SchedulerType::Cron,
860            queue_manager: ReportQueueManager::new(),
861        }
862    }
863
864    /// Get the scheduler type.
865    pub fn scheduler_type(&self) -> &SchedulerType {
866        &self.scheduler_type
867    }
868
869    /// Set the scheduler type.
870    pub fn set_scheduler_type(&mut self, scheduler_type: SchedulerType) {
871        self.scheduler_type = scheduler_type;
872    }
873
874    /// Get a reference to the queue manager.
875    pub fn queue_manager(&self) -> &ReportQueueManager {
876        &self.queue_manager
877    }
878
879    /// Get a mutable reference to the queue manager.
880    pub fn queue_manager_mut(&mut self) -> &mut ReportQueueManager {
881        &mut self.queue_manager
882    }
883}
884
885impl ReportQueueManager {
886    /// Creates an empty report queue.
887    pub fn new() -> Self {
888        Self {
889            pending_reports: Vec::new(),
890            running_reports: Vec::new(),
891            completed_reports: Vec::new(),
892        }
893    }
894
895    /// Enqueue a pending report.
896    pub fn enqueue_report(&mut self, report: QueuedReport) {
897        self.pending_reports.push(report);
898    }
899
900    /// Dequeue the next pending report and mark it as running.
901    pub fn start_next_report(&mut self) -> Option<QueuedReport> {
902        if self.pending_reports.is_empty() {
903            None
904        } else {
905            let report = self.pending_reports.remove(0);
906            self.running_reports.push(RunningReport {
907                report_id: report.report_id.clone(),
908                started_at: std::time::SystemTime::now()
909                    .duration_since(std::time::UNIX_EPOCH)
910                    .unwrap_or_default()
911                    .as_secs(),
912                progress: 0.0,
913            });
914            Some(report)
915        }
916    }
917
918    /// Mark a running report as completed.
919    pub fn complete_report(&mut self, report: CompletedReport) {
920        self.running_reports
921            .retain(|r| r.report_id != report.report_id);
922        self.completed_reports.push(report);
923    }
924
925    /// Number of pending reports.
926    pub fn pending_count(&self) -> usize {
927        self.pending_reports.len()
928    }
929
930    /// Number of running reports.
931    pub fn running_count(&self) -> usize {
932        self.running_reports.len()
933    }
934
935    /// Number of completed reports.
936    pub fn completed_count(&self) -> usize {
937        self.completed_reports.len()
938    }
939}
940
941impl ReportDistributionEngine {
942    /// Creates an engine with an empty distribution-channel registry.
943    pub fn new() -> Self {
944        Self {
945            distribution_channels: HashMap::new(),
946            delivery_tracker: DeliveryTracker::new(),
947        }
948    }
949
950    /// Initializes the delivery tracker.
951    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
952        Ok(())
953    }
954
955    /// Register a distribution channel.
956    pub fn add_distribution_channel(&mut self, channel: DistributionChannel) {
957        self.distribution_channels
958            .insert(channel.channel_id.clone(), channel);
959    }
960
961    /// Look up a distribution channel by id.
962    pub fn get_distribution_channel(&self, channel_id: &str) -> Option<&DistributionChannel> {
963        self.distribution_channels.get(channel_id)
964    }
965
966    /// Iterate over all registered distribution channels.
967    pub fn list_distribution_channels(&self) -> impl Iterator<Item = &DistributionChannel> {
968        self.distribution_channels.values()
969    }
970
971    /// Get a reference to the delivery tracker.
972    pub fn delivery_tracker(&self) -> &DeliveryTracker {
973        &self.delivery_tracker
974    }
975
976    /// Get a mutable reference to the delivery tracker.
977    pub fn delivery_tracker_mut(&mut self) -> &mut DeliveryTracker {
978        &mut self.delivery_tracker
979    }
980}
981
982impl DeliveryTracker {
983    /// Creates a tracker with an empty delivery-record registry.
984    pub fn new() -> Self {
985        Self {
986            deliveries: HashMap::new(),
987            status: DeliveryStatus {
988                total_deliveries: 0,
989                successful_deliveries: 0,
990                failed_deliveries: 0,
991                pending_deliveries: 0,
992            },
993        }
994    }
995
996    /// Record a delivery and update aggregate status counters.
997    pub fn record_delivery(&mut self, record: DeliveryRecord) {
998        self.status.total_deliveries += 1;
999        match record.final_status {
1000            DeliveryFinalStatus::Delivered => self.status.successful_deliveries += 1,
1001            DeliveryFinalStatus::Failed => self.status.failed_deliveries += 1,
1002            DeliveryFinalStatus::Pending | DeliveryFinalStatus::Cancelled => {
1003                self.status.pending_deliveries += 1;
1004            }
1005        }
1006        self.deliveries.insert(record.record_id.clone(), record);
1007    }
1008
1009    /// Look up a delivery record by id.
1010    pub fn get_delivery(&self, record_id: &str) -> Option<&DeliveryRecord> {
1011        self.deliveries.get(record_id)
1012    }
1013
1014    /// Iterate over all recorded deliveries.
1015    pub fn list_deliveries(&self) -> impl Iterator<Item = &DeliveryRecord> {
1016        self.deliveries.values()
1017    }
1018
1019    /// Get a snapshot of the aggregate delivery status.
1020    pub fn status(&self) -> &DeliveryStatus {
1021        &self.status
1022    }
1023}
1024
1025impl DeliveryStatus {
1026    /// Returns the default (pending) delivery status.
1027    pub fn new() -> Self {
1028        Self {
1029            total_deliveries: 0,
1030            successful_deliveries: 0,
1031            failed_deliveries: 0,
1032            pending_deliveries: 0,
1033        }
1034    }
1035}
1036
1037impl SecurityMetrics {
1038    /// Returns zeroed security metrics.
1039    pub fn new() -> Self {
1040        Self {
1041            threat_metrics: ThreatMetrics::new(),
1042            anomaly_metrics: AnomalyMetrics::new(),
1043            compliance_metrics: ComplianceMetrics::new(),
1044            performance_metrics: SecurityPerformanceMetrics::new(),
1045        }
1046    }
1047
1048    /// Returns a clone of this metrics record.
1049    pub fn get_metrics(&self) -> SecurityMetrics {
1050        self.clone()
1051    }
1052}
1053
1054impl ThreatMetrics {
1055    /// Returns zeroed threat metrics.
1056    pub fn new() -> Self {
1057        Self {
1058            threats_detected: 0,
1059            threats_blocked: 0,
1060            false_positives: 0,
1061            detection_rate: 0.0,
1062            response_time: 0.0,
1063        }
1064    }
1065}
1066
1067impl AnomalyMetrics {
1068    /// Returns zeroed anomaly metrics.
1069    pub fn new() -> Self {
1070        Self {
1071            anomalies_detected: 0,
1072            anomalies_investigated: 0,
1073            confirmed_anomalies: 0,
1074            false_positive_rate: 0.0,
1075            detection_accuracy: 0.0,
1076        }
1077    }
1078}
1079
1080impl ComplianceMetrics {
1081    /// Returns zeroed compliance metrics.
1082    pub fn new() -> Self {
1083        Self {
1084            compliance_score: 1.0,
1085            controls_implemented: 0,
1086            controls_passed: 0,
1087            audit_findings: 0,
1088            remediation_rate: 0.0,
1089        }
1090    }
1091}
1092
1093impl SecurityPerformanceMetrics {
1094    /// Returns zeroed security performance metrics.
1095    pub fn new() -> Self {
1096        Self {
1097            average_response_time: 0.0,
1098            throughput: 0.0,
1099            resource_utilization: 0.0,
1100            error_rate: 0.0,
1101        }
1102    }
1103}