copybook-core 0.4.3

Core COBOL copybook parser, schema, and validation primitives.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Audit Context System
//!
//! Provides comprehensive context tracking for all audit operations including
//! user context, environment information, security classification, and
//! compliance requirements.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

use super::{ComplianceProfile, generate_audit_id, generate_lightweight_audit_id};

/// Comprehensive audit context for all operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditContext {
    /// Unique operation identifier for correlation
    pub operation_id: String,

    /// User context information
    pub user: Option<String>,

    /// System environment context
    pub environment: EnvironmentContext,

    /// Processing configuration context
    pub processing_config: ProcessingConfig,

    /// Security context and classification
    pub security: SecurityContext,

    /// Compliance requirements for this operation
    pub compliance_profiles: Vec<ComplianceProfile>,

    /// Custom metadata for operation-specific context
    pub metadata: HashMap<String, String>,

    /// Operation start timestamp
    pub started_at: String,

    /// Parent operation ID for nested operations
    pub parent_operation_id: Option<String>,
}

impl AuditContext {
    /// Create a new audit context with default values
    pub fn new() -> Self {
        Self {
            operation_id: generate_audit_id(),
            user: None,
            environment: EnvironmentContext::current(),
            processing_config: ProcessingConfig::default(),
            security: SecurityContext::default(),
            compliance_profiles: Vec::new(),
            metadata: HashMap::new(),
            started_at: chrono::Utc::now().to_rfc3339(),
            parent_operation_id: None,
        }
    }

    /// Create a lightweight audit context for performance-critical operations
    /// Avoids expensive system calls and allocations for better performance
    pub fn new_lightweight() -> Self {
        Self {
            operation_id: generate_lightweight_audit_id(),
            user: None,
            environment: EnvironmentContext::lightweight(),
            processing_config: ProcessingConfig::default(),
            security: SecurityContext::default(),
            compliance_profiles: Vec::new(),
            metadata: HashMap::new(),
            started_at: "1970-01-01T00:00:00Z".to_string(), // Avoid timestamp generation
            parent_operation_id: None,
        }
    }

    /// Create an audit context from a reusable template to avoid repeated allocations
    pub fn from_template(template: &Self, operation_id: impl Into<String>) -> Self {
        let mut context = template.clone();
        context.operation_id = operation_id.into();
        context.started_at = chrono::Utc::now().to_rfc3339();
        context.parent_operation_id = None;
        context
    }

    /// Set the operation identifier
    #[must_use]
    pub fn with_operation_id(mut self, operation_id: impl Into<String>) -> Self {
        self.operation_id = operation_id.into();
        self
    }

    /// Set the user context
    #[must_use]
    pub fn with_user(mut self, user: impl Into<String>) -> Self {
        self.user = Some(user.into());
        self
    }

    /// Set the environment context
    #[must_use]
    pub fn with_environment(mut self, environment: EnvironmentContext) -> Self {
        self.environment = environment;
        self
    }

    /// Set the processing configuration
    #[must_use]
    pub fn with_processing_config(mut self, config: ProcessingConfig) -> Self {
        self.processing_config = config;
        self
    }

    /// Set the security context
    #[must_use]
    pub fn with_security_context(mut self, security: SecurityContext) -> Self {
        self.security = security;
        self
    }

    /// Add compliance profiles
    #[must_use]
    pub fn with_compliance_profiles(mut self, profiles: &[ComplianceProfile]) -> Self {
        self.compliance_profiles = profiles.to_vec();
        self
    }

    /// Add a single compliance profile
    #[must_use]
    pub fn with_compliance_profile(mut self, profile: ComplianceProfile) -> Self {
        self.compliance_profiles.push(profile);
        self
    }

    /// Set security classification
    #[must_use]
    pub fn with_security_classification(mut self, classification: SecurityClassification) -> Self {
        self.security.classification = classification;
        self
    }

    /// Add metadata key-value pair
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Set parent operation ID for nested operations
    #[must_use]
    pub fn with_parent_operation_id(mut self, parent_id: impl Into<String>) -> Self {
        self.parent_operation_id = Some(parent_id.into());
        self
    }

    /// Create a child context for nested operations
    #[must_use]
    pub fn create_child_context(&self, child_operation_id: impl Into<String>) -> Self {
        let mut child = self.clone();
        child.operation_id = child_operation_id.into();
        child.parent_operation_id = Some(self.operation_id.clone());
        child.started_at = chrono::Utc::now().to_rfc3339();
        child
    }

    /// Create a lightweight child context for performance-critical operations
    /// Avoids timestamp generation and expensive cloning
    #[must_use]
    pub fn create_lightweight_child_context(&self, child_operation_id: impl Into<String>) -> Self {
        Self {
            operation_id: child_operation_id.into(),
            user: self.user.clone(),
            environment: EnvironmentContext::lightweight(),
            processing_config: ProcessingConfig::default(),
            security: self.security.clone(),
            compliance_profiles: self.compliance_profiles.clone(),
            metadata: HashMap::new(), // Don't clone metadata for performance
            started_at: "1970-01-01T00:00:00Z".to_string(),
            parent_operation_id: Some(self.operation_id.clone()),
        }
    }

    /// Check if this context requires specific compliance validation
    pub fn requires_compliance(&self, profile: ComplianceProfile) -> bool {
        self.compliance_profiles.contains(&profile)
    }

    /// Get the effective security level for this context
    pub fn effective_security_level(&self) -> SecurityLevel {
        // Determine effective security level based on classification and compliance
        match self.security.classification {
            SecurityClassification::Public => SecurityLevel::Low,
            SecurityClassification::Internal => SecurityLevel::Medium,
            SecurityClassification::Confidential => {
                if self.compliance_profiles.contains(&ComplianceProfile::SOX)
                    || self.compliance_profiles.contains(&ComplianceProfile::HIPAA)
                {
                    SecurityLevel::High
                } else {
                    SecurityLevel::Medium
                }
            }
            SecurityClassification::MaterialTransaction | SecurityClassification::PHI => {
                SecurityLevel::Critical
            }
        }
    }
}

impl Default for AuditContext {
    fn default() -> Self {
        Self::new()
    }
}

/// System environment context information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentContext {
    /// System hostname or identifier
    pub hostname: String,

    /// Process ID
    pub process_id: u32,

    /// System architecture (x86_64, aarch64, etc.)
    pub system_arch: String,

    /// copybook-rs version
    pub version: String,

    /// Command line invocation
    pub command_line: Vec<String>,

    /// Environment variables (filtered for security)
    pub environment_variables: HashMap<String, String>,

    /// Working directory
    pub working_directory: String,

    /// System timestamp when context was created
    pub system_timestamp: u64,
}

impl EnvironmentContext {
    /// Create environment context from current system state
    pub fn current() -> Self {
        Self {
            hostname: Self::get_hostname(),
            process_id: std::process::id(),
            system_arch: std::env::consts::ARCH.to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            command_line: std::env::args().collect(),
            environment_variables: Self::get_filtered_env_vars(),
            working_directory: std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string(),
            system_timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }

    /// Create lightweight environment context for performance-critical operations
    /// Avoids expensive system calls and allocations
    #[inline]
    pub fn lightweight() -> Self {
        Self {
            hostname: "performance-host".to_string(),
            process_id: std::process::id(),
            system_arch: std::env::consts::ARCH.to_string(),
            version: env!("CARGO_PKG_VERSION").to_string(),
            command_line: vec!["copybook-rs".to_string()],
            environment_variables: HashMap::new(),
            working_directory: "/tmp".to_string(),
            system_timestamp: 0, // Avoid system time call
        }
    }

    fn get_hostname() -> String {
        std::env::var("HOSTNAME")
            .or_else(|_| std::env::var("COMPUTERNAME"))
            .unwrap_or_else(|_| "unknown".to_string())
    }

    fn get_filtered_env_vars() -> HashMap<String, String> {
        let allowed_vars = [
            "USER", "USERNAME", "HOME", "PATH", "SHELL", "TERM", "LANG", "LC_ALL", "TZ", "PWD",
        ];

        std::env::vars()
            .filter(|(key, _)| allowed_vars.contains(&key.as_str()))
            .collect()
    }
}

/// Processing configuration context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessingConfig {
    /// Input file or data source information
    pub input_source: Option<String>,

    /// Output destination information
    pub output_destination: Option<String>,

    /// Processing mode (batch, streaming, etc.)
    pub processing_mode: ProcessingMode,

    /// Batch size for batch processing
    pub batch_size: Option<usize>,

    /// Number of processing threads
    pub thread_count: Option<usize>,

    /// Processing timeout settings
    pub timeout_seconds: Option<u64>,

    /// Memory limit settings
    pub memory_limit_mb: Option<usize>,

    /// Retry configuration
    pub retry_config: RetryConfig,
}

impl Default for ProcessingConfig {
    fn default() -> Self {
        Self {
            input_source: None,
            output_destination: None,
            processing_mode: ProcessingMode::Batch,
            batch_size: Some(1000),
            thread_count: Some(1),
            timeout_seconds: Some(3600), // 1 hour default
            memory_limit_mb: Some(512),
            retry_config: RetryConfig::default(),
        }
    }
}

/// Processing mode enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ProcessingMode {
    /// Process records in fixed-size batches.
    Batch,
    /// Process records as a continuous stream.
    Streaming,
    /// Process records interactively with user input.
    Interactive,
    /// Process records on a timed schedule.
    Scheduled,
}

/// Retry configuration for processing operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    /// Maximum number of retry attempts before giving up.
    pub max_retries: u32,
    /// Initial delay in milliseconds before the first retry.
    pub initial_delay_ms: u64,
    /// Maximum delay in milliseconds between retries.
    pub max_delay_ms: u64,
    /// Multiplier applied to the delay after each retry attempt.
    pub backoff_multiplier: f64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_retries: 3,
            initial_delay_ms: 100,
            max_delay_ms: 30000,
            backoff_multiplier: 2.0,
        }
    }
}

/// Security context and classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityContext {
    /// Data security classification
    pub classification: SecurityClassification,

    /// Access control requirements
    pub access_control: AccessControlRequirements,

    /// Encryption requirements
    pub encryption: EncryptionRequirements,

    /// Network security context
    pub network: NetworkSecurityContext,

    /// Audit trail requirements
    pub audit_requirements: AuditRequirements,
}

impl Default for SecurityContext {
    fn default() -> Self {
        Self {
            classification: SecurityClassification::Internal,
            access_control: AccessControlRequirements::default(),
            encryption: EncryptionRequirements::default(),
            network: NetworkSecurityContext::default(),
            audit_requirements: AuditRequirements::default(),
        }
    }
}

/// Data security classification levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum SecurityClassification {
    /// Data intended for public access with no restrictions.
    Public,
    /// Data restricted to internal organizational use.
    Internal,
    /// Sensitive data requiring access controls.
    Confidential,
    /// Data related to material financial transactions (SOX scope).
    MaterialTransaction,
    /// Protected Health Information subject to HIPAA regulations.
    PHI, // Protected Health Information
}

/// Effective security level derived from classification and compliance
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum SecurityLevel {
    /// Minimal security controls required.
    Low,
    /// Standard security controls required.
    Medium,
    /// Enhanced security controls and monitoring required.
    High,
    /// Maximum security controls with real-time monitoring.
    Critical,
}

/// Access control requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct AccessControlRequirements {
    /// Whether authentication is required for access.
    pub authentication_required: bool,
    /// Whether authorization checks are required after authentication.
    pub authorization_required: bool,
    /// Whether multi-factor authentication is enforced.
    pub multi_factor_authentication: bool,
    /// Whether role-based access control is enabled.
    pub role_based_access: bool,
    /// Whether segregation of duties is enforced.
    pub segregation_of_duties: bool,
}

impl Default for AccessControlRequirements {
    fn default() -> Self {
        Self {
            authentication_required: true,
            authorization_required: true,
            multi_factor_authentication: false,
            role_based_access: true,
            segregation_of_duties: false,
        }
    }
}

/// Encryption requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionRequirements {
    /// Required encryption standard for data at rest.
    pub at_rest: EncryptionStandard,
    /// Required encryption standard for data in transit.
    pub in_transit: EncryptionStandard,
    /// Key management policy requirements.
    pub key_management: KeyManagementRequirements,
    /// Whether data is actually encrypted at rest
    pub at_rest_encrypted: bool,
    /// Whether data is encrypted in transit
    pub transit_encrypted: bool,
}

impl Default for EncryptionRequirements {
    fn default() -> Self {
        Self {
            at_rest: EncryptionStandard::AES256,
            in_transit: EncryptionStandard::TLS12,
            key_management: KeyManagementRequirements::default(),
            at_rest_encrypted: true,
            transit_encrypted: true,
        }
    }
}

/// Encryption standards
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EncryptionStandard {
    /// No encryption applied.
    None,
    /// AES encryption with 128-bit key.
    AES128,
    /// AES encryption with 256-bit key.
    AES256,
    /// TLS version 1.2 transport encryption.
    TLS12,
    /// TLS version 1.3 transport encryption.
    TLS13,
}

/// Key management requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KeyManagementRequirements {
    /// Number of days before cryptographic keys must be rotated.
    pub key_rotation_days: Option<u32>,
    /// Whether a hardware security module (HSM) is required.
    pub hardware_security_module: bool,
    /// Whether key escrow is enabled for recovery purposes.
    pub key_escrow: bool,
}

impl Default for KeyManagementRequirements {
    fn default() -> Self {
        Self {
            key_rotation_days: Some(90),
            hardware_security_module: false,
            key_escrow: false,
        }
    }
}

/// Network security context
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NetworkSecurityContext {
    /// Source IP address of the request, if available.
    pub source_ip: Option<String>,
    /// List of allowed network CIDR ranges.
    pub allowed_networks: Vec<String>,
    /// Whether a VPN connection is required.
    pub vpn_required: bool,
    /// Active firewall rule identifiers.
    pub firewall_rules: Vec<String>,
}

/// Audit trail requirements
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct AuditRequirements {
    /// Whether comprehensive logging of all operations is enabled.
    pub comprehensive_logging: bool,
    /// Whether integrity protection for audit records is enabled.
    pub integrity_protection: bool,
    /// Whether real-time monitoring of audit events is enabled.
    pub real_time_monitoring: bool,
    /// Number of days audit records must be retained.
    pub retention_days: u32,
    /// Whether tamper detection mechanisms are enabled.
    pub tamper_detection: bool,
    /// Whether key management is properly implemented
    pub key_management: bool,
}

impl Default for AuditRequirements {
    fn default() -> Self {
        Self {
            comprehensive_logging: true,
            integrity_protection: true,
            real_time_monitoring: false,
            retention_days: 2555, // 7 years default
            tamper_detection: true,
            key_management: false,
        }
    }
}

#[cfg(test)]
#[allow(clippy::expect_used)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn test_audit_context_creation() {
        let context = AuditContext::new();

        assert!(context.operation_id.starts_with("audit-"));
        assert!(context.user.is_none());
        assert_eq!(context.compliance_profiles.len(), 0);
    }

    #[test]
    fn test_audit_context_builder_pattern() {
        let context = AuditContext::new()
            .with_operation_id("test-operation")
            .with_user("test_user")
            .with_compliance_profile(ComplianceProfile::SOX)
            .with_security_classification(SecurityClassification::Confidential);

        assert_eq!(context.operation_id, "test-operation");
        assert_eq!(context.user, Some("test_user".to_string()));
        assert!(context.requires_compliance(ComplianceProfile::SOX));
        assert_eq!(
            context.security.classification,
            SecurityClassification::Confidential
        );
    }

    #[test]
    fn test_child_context_creation() {
        let parent = AuditContext::new()
            .with_operation_id("parent-operation")
            .with_user("test_user");

        let child = parent.create_child_context("child-operation");

        assert_eq!(child.operation_id, "child-operation");
        assert_eq!(
            child.parent_operation_id,
            Some("parent-operation".to_string())
        );
        assert_eq!(child.user, Some("test_user".to_string()));
    }

    #[test]
    fn test_effective_security_level() {
        let low_security =
            AuditContext::new().with_security_classification(SecurityClassification::Public);
        assert_eq!(low_security.effective_security_level(), SecurityLevel::Low);

        let high_security = AuditContext::new()
            .with_security_classification(SecurityClassification::Confidential)
            .with_compliance_profile(ComplianceProfile::SOX);
        assert_eq!(
            high_security.effective_security_level(),
            SecurityLevel::High
        );

        let critical_security =
            AuditContext::new().with_security_classification(SecurityClassification::PHI);
        assert_eq!(
            critical_security.effective_security_level(),
            SecurityLevel::Critical
        );
    }

    #[test]
    fn test_environment_context_current() {
        let env_context = EnvironmentContext::current();

        assert!(!env_context.hostname.is_empty());
        assert!(env_context.process_id > 0);
        assert!(!env_context.system_arch.is_empty());
        assert!(!env_context.version.is_empty());
    }
}