ggen-core 26.7.3

Core graph-aware code generation engine
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
//! Comprehensive security logging system
//!
//! This module provides a unified security logging interface that combines:
//! - Event logging with structured data
//! - Immutable audit trail with tamper-proofing
//! - Intrusion detection with pattern matching
//! - Security metrics collection
//! - Real-time alerting
//!
//! ## Usage
//!
//! ```rust,no_run
//! use crate::security::logging::SecurityLogger;
//! use crate::security::events::{SecurityEvent, SecuritySeverity, EventCategory};
//! use std::path::PathBuf;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create logger with audit trail persistence
//! let mut logger = SecurityLogger::with_repository(PathBuf::from("./audit"))?;
//!
//! // Log a security event
//! let event = SecurityEvent::new(
//!     SecuritySeverity::High,
//!     EventCategory::Authentication,
//!     "Login attempt failed"
//! );
//! logger.log(event)?;
//!
//! // Get security metrics
//! if let Some(metrics) = logger.get_metrics_for_last_hour() {
//!     println!("Failed logins in last hour: {}", metrics.failed_auth_count);
//! }
//! # Ok(())
//! # }
//! ```

use super::alerting::{AlertManager, ConsoleAlertHandler, FileAlertHandler};
use super::audit_trail::{AuditError, AuditTrail};
use super::events::SecurityEvent;
use super::intrusion_detection::{DetectionError, IntrusionDetector};
use super::metrics::{MetricsCollector, SecurityMetrics, TimeWindow};
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
use tracing::{error, info, warn};

/// Security logging errors
#[derive(Debug, Error)]
pub enum LoggingError {
    #[error("Audit error: {0}")]
    AuditError(#[from] AuditError),

    #[error("Detection error: {0}")]
    DetectionError(#[from] DetectionError),

    #[error("Alert error: {0}")]
    AlertError(#[from] super::alerting::AlertError),

    #[error("Metrics error: {0}")]
    MetricsError(#[from] super::metrics::MetricsError),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// Boolean feature enables for security logging
#[allow(clippy::struct_excessive_bools)] // Four bools are semantically distinct security feature enables
#[derive(Debug, Clone, Copy)]
pub struct SecurityFeatures {
    /// Enable audit trail
    pub enable_audit: bool,
    /// Enable intrusion detection
    pub enable_intrusion_detection: bool,
    /// Enable metrics collection
    pub enable_metrics: bool,
    /// Enable alerting
    pub enable_alerting: bool,
}

impl Default for SecurityFeatures {
    fn default() -> Self {
        Self {
            enable_audit: true,
            enable_intrusion_detection: true,
            enable_metrics: true,
            enable_alerting: true,
        }
    }
}

/// Security logger configuration
#[derive(Debug, Clone)]
pub struct SecurityLoggerConfig {
    /// Feature enable flags
    pub features: SecurityFeatures,
    /// Repository path for audit trail
    pub audit_repo_path: Option<PathBuf>,
    /// Alert log file path
    pub alert_log_path: Option<PathBuf>,
}

impl Default for SecurityLoggerConfig {
    fn default() -> Self {
        Self {
            features: SecurityFeatures::default(),
            audit_repo_path: None,
            alert_log_path: None,
        }
    }
}

/// Comprehensive security logger
pub struct SecurityLogger {
    /// Configuration
    config: SecurityLoggerConfig,
    /// Audit trail
    audit_trail: Option<AuditTrail>,
    /// Intrusion detector
    intrusion_detector: Option<IntrusionDetector>,
    /// Metrics collector
    metrics: Option<MetricsCollector>,
    /// Alert manager
    alert_manager: Option<AlertManager>,
}

impl SecurityLogger {
    /// Create a new security logger with default configuration
    pub fn new() -> Result<Self, LoggingError> {
        Self::with_config(SecurityLoggerConfig::default())
    }

    /// Get the current configuration
    pub fn get_config(&self) -> &SecurityLoggerConfig {
        &self.config
    }

    /// Create a security logger with custom configuration
    pub fn with_config(config: SecurityLoggerConfig) -> Result<Self, LoggingError> {
        let audit_trail = if config.features.enable_audit {
            Some(if let Some(ref path) = config.audit_repo_path {
                AuditTrail::with_repository(path.clone())?
            } else {
                AuditTrail::new()
            })
        } else {
            None
        };

        let intrusion_detector = if config.features.enable_intrusion_detection {
            Some(IntrusionDetector::new()?)
        } else {
            None
        };

        let metrics = if config.features.enable_metrics {
            Some(MetricsCollector::new())
        } else {
            None
        };

        let alert_manager = if config.features.enable_alerting {
            let mut manager = AlertManager::new();

            // Register console handler
            manager.register_handler(Arc::new(ConsoleAlertHandler));

            // Register file handler if path provided
            if let Some(ref path) = config.alert_log_path {
                manager.register_handler(Arc::new(FileAlertHandler::new(
                    path.to_string_lossy().to_string(),
                )));
            }

            Some(manager)
        } else {
            None
        };

        Ok(Self {
            config,
            audit_trail,
            intrusion_detector,
            metrics,
            alert_manager,
        })
    }

    /// Create a security logger with repository-based audit trail
    pub fn with_repository(repo_path: PathBuf) -> Result<Self, LoggingError> {
        let config = SecurityLoggerConfig {
            features: SecurityFeatures {
                enable_audit: true,
                ..Default::default()
            },
            audit_repo_path: Some(repo_path),
            ..Default::default()
        };
        Self::with_config(config)
    }

    /// Log a security event
    pub fn log(&mut self, event: SecurityEvent) -> Result<(), LoggingError> {
        let event_id = event.id.clone();
        let severity = event.severity;
        let category = event.category.clone();

        // Log to tracing
        match severity {
            super::events::SecuritySeverity::Critical | super::events::SecuritySeverity::High => {
                error!(
                    event_id = %event_id,
                    severity = ?severity,
                    category = ?category,
                    message = %event.message,
                    "Security event"
                );
            }
            super::events::SecuritySeverity::Medium => {
                warn!(
                    event_id = %event_id,
                    severity = ?severity,
                    category = ?category,
                    message = %event.message,
                    "Security event"
                );
            }
            _ => {
                info!(
                    event_id = %event_id,
                    severity = ?severity,
                    category = ?category,
                    message = %event.message,
                    "Security event"
                );
            }
        }

        // Append to audit trail
        if let Some(ref mut audit) = self.audit_trail {
            audit.append(event.clone())?;
        }

        // Collect metrics
        if let Some(ref mut metrics) = self.metrics {
            metrics.record(event.clone());
        }

        // Send alert if required
        if let Some(ref mut alerter) = self.alert_manager {
            alerter.send_from_event(&event)?;
        }

        Ok(())
    }

    /// Analyze input for attack patterns
    pub fn analyze_input(&mut self, input: &str) -> Result<Option<SecurityEvent>, LoggingError> {
        if let Some(ref detector) = self.intrusion_detector {
            if let Some(event) = detector.analyze_input(input) {
                self.log(event.clone())?;
                return Ok(Some(event));
            }
        }
        Ok(None)
    }

    /// Check authentication rate limit
    pub fn check_auth_rate(&mut self, source: &str) -> Result<(), LoggingError> {
        if let Some(ref mut detector) = self.intrusion_detector {
            if let Some(event) = detector.check_auth_rate(source) {
                self.log(event)?;
            }
        }
        Ok(())
    }

    /// Check request rate limit
    pub fn check_request_rate(&mut self, source: &str) -> Result<(), LoggingError> {
        if let Some(ref mut detector) = self.intrusion_detector {
            if let Some(event) = detector.check_request_rate(source) {
                self.log(event)?;
            }
        }
        Ok(())
    }

    /// Get metrics for a time window
    pub fn get_metrics(&self, window: TimeWindow) -> Option<SecurityMetrics> {
        self.metrics.as_ref().map(|m| m.get_metrics(window))
    }

    /// Get metrics for the last hour
    pub fn get_metrics_for_last_hour(&self) -> Option<SecurityMetrics> {
        self.get_metrics(TimeWindow::Hour)
    }

    /// Get metrics for the last day
    pub fn get_metrics_for_last_day(&self) -> Option<SecurityMetrics> {
        self.get_metrics(TimeWindow::Day)
    }

    /// Verify audit trail integrity
    pub fn verify_audit_trail(&self) -> Result<bool, LoggingError> {
        if let Some(ref audit) = self.audit_trail {
            Ok(audit.verify_chain()?)
        } else {
            Ok(true) // No audit trail to verify
        }
    }

    /// Export audit trail to JSON
    pub fn export_audit_trail(&self) -> Result<String, LoggingError> {
        if let Some(ref audit) = self.audit_trail {
            Ok(audit.export_json()?)
        } else {
            Ok("[]".to_string())
        }
    }

    /// Export metrics to JSON
    pub fn export_metrics(&self, window: TimeWindow) -> Result<String, LoggingError> {
        if let Some(ref metrics) = self.metrics {
            Ok(metrics.export_json(window)?)
        } else {
            Ok("{}".to_string())
        }
    }

    /// Get audit entry count
    pub fn audit_entry_count(&self) -> usize {
        self.audit_trail.as_ref().map(|a| a.len()).unwrap_or(0)
    }

    /// Get total event count
    pub fn total_events(&self) -> usize {
        self.metrics.as_ref().map(|m| m.total_events()).unwrap_or(0)
    }
}

impl Default for SecurityLogger {
    fn default() -> Self {
        // The security logger with default config should never fail in practice
        // since all components have sensible defaults. However, we propagate
        // the error by panicking with context if initialization fails unexpectedly.
        Self::new().unwrap_or_else(|e| {
            log::error!("Failed to initialize default security logger: {}", e);
            // Create a logger with minimal functionality as fallback
            Self {
                config: SecurityLoggerConfig::default(),
                audit_trail: None,
                intrusion_detector: None,
                metrics: None,
                alert_manager: None,
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::security::events::{EventCategory, SecuritySeverity};
    use crate::security::AttackPattern;
    use std::net::{IpAddr, Ipv4Addr};

    #[test]
    fn test_security_logger_creation() {
        // Arrange & Act
        let result = SecurityLogger::new();

        // Assert
        assert!(result.is_ok());
    }

    #[test]
    fn test_log_event() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();
        let event = SecurityEvent::new(
            SecuritySeverity::High,
            EventCategory::Authentication,
            "Test event",
        );

        // Act
        let result = logger.log(event);

        // Assert
        assert!(result.is_ok());
        assert_eq!(logger.audit_entry_count(), 1);
        assert_eq!(logger.total_events(), 1);
    }

    #[test]
    fn test_analyze_input_attack_detected() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        // Act
        let result = logger.analyze_input("SELECT * FROM users WHERE id = 1");

        // Assert
        assert!(result.is_ok());
        let event = result.unwrap();
        assert!(event.is_some());
        assert_eq!(event.unwrap().attack_pattern, AttackPattern::SqlInjection);
    }

    #[test]
    fn test_analyze_input_no_attack() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        // Act
        let result = logger.analyze_input("normal user input");

        // Assert
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_check_auth_rate() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        // Act - make multiple auth attempts
        for _ in 0..6 {
            let result = logger.check_auth_rate("192.168.1.1");
            assert!(result.is_ok());
        }

        // Assert - should have logged rate limit event
        assert!(logger.total_events() > 0);
    }

    #[test]
    fn test_get_metrics() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        logger
            .log(SecurityEvent::new(
                SecuritySeverity::High,
                EventCategory::Authentication,
                "Event 1",
            ))
            .unwrap();
        logger
            .log(SecurityEvent::new(
                SecuritySeverity::Medium,
                EventCategory::Authorization,
                "Event 2",
            ))
            .unwrap();

        // Act
        let metrics = logger.get_metrics(TimeWindow::AllTime);

        // Assert
        assert!(metrics.is_some());
        let m = metrics.unwrap();
        assert_eq!(m.total_events, 2);
    }

    #[test]
    fn test_verify_audit_trail() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        logger
            .log(SecurityEvent::new(
                SecuritySeverity::Info,
                EventCategory::DataAccess,
                "Access event",
            ))
            .unwrap();

        // Act
        let result = logger.verify_audit_trail();

        // Assert
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_export_audit_trail() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        logger
            .log(SecurityEvent::new(
                SecuritySeverity::Critical,
                EventCategory::Integrity,
                "Breach detected",
            ))
            .unwrap();

        // Act
        let result = logger.export_audit_trail();

        // Assert
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.contains("Breach detected"));
    }

    #[test]
    fn test_export_metrics() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();

        logger
            .log(SecurityEvent::new(
                SecuritySeverity::High,
                EventCategory::Authentication,
                "Login failed",
            ))
            .unwrap();

        // Act
        let result = logger.export_metrics(TimeWindow::AllTime);

        // Assert
        assert!(result.is_ok());
        let json = result.unwrap();
        assert!(json.contains("total_events"));
    }

    #[test]
    fn test_disabled_features() {
        // Arrange
        let config = SecurityLoggerConfig {
            features: SecurityFeatures {
                enable_audit: false,
                enable_intrusion_detection: false,
                enable_metrics: false,
                enable_alerting: false,
                ..Default::default()
            },
            ..Default::default()
        };

        // Act
        let logger = SecurityLogger::with_config(config).unwrap();

        // Assert
        assert!(logger.audit_trail.is_none());
        assert!(logger.intrusion_detector.is_none());
        assert!(logger.metrics.is_none());
        assert!(logger.alert_manager.is_none());
    }

    #[test]
    fn test_with_repository() {
        // Arrange
        let temp_dir = tempfile::tempdir().unwrap();
        let repo_path = temp_dir.path().to_path_buf();

        // Act
        let result = SecurityLogger::with_repository(repo_path);

        // Assert
        assert!(result.is_ok());
    }

    #[test]
    fn test_multiple_events_logging() {
        // Arrange
        let mut logger = SecurityLogger::new().unwrap();
        let ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));

        // Act
        logger
            .log(SecurityEvent::authentication_failed("user1", ip))
            .unwrap();
        logger
            .log(SecurityEvent::authorization_failed(
                "user2", "/admin", "read",
            ))
            .unwrap();
        logger
            .log(SecurityEvent::input_validation_failed(
                "' OR '1'='1",
                AttackPattern::SqlInjection,
            ))
            .unwrap();

        // Assert
        assert_eq!(logger.audit_entry_count(), 3);
        assert_eq!(logger.total_events(), 3);

        let metrics = logger.get_metrics(TimeWindow::AllTime).unwrap();
        assert_eq!(metrics.total_events, 3);
        assert_eq!(metrics.total_attacks, 1);
        assert_eq!(metrics.failed_auth_count, 1);
        assert_eq!(metrics.failed_authz_count, 1);
    }

    #[test]
    fn test_logger_with_custom_config() {
        // Arrange
        let temp_dir = tempfile::tempdir().unwrap();
        let config = SecurityLoggerConfig {
            features: SecurityFeatures {
                enable_audit: true,
                enable_intrusion_detection: true,
                enable_metrics: true,
                enable_alerting: true,
            },
            audit_repo_path: Some(temp_dir.path().to_path_buf()),
            alert_log_path: Some(temp_dir.path().join("alerts.log")),
        };

        // Act
        let logger = SecurityLogger::with_config(config);

        // Assert
        assert!(logger.is_ok());
    }
}