ddex-builder 0.4.5

Deterministic DDEX XML builder with smart normalization
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
//! Error message sanitization system for preventing information disclosure
//!
//! This module provides a comprehensive error sanitization system that ensures
//! sensitive information is not leaked through error messages while maintaining
//! useful debugging capabilities for developers.

use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use tracing::error;
use uuid::Uuid;

/// Operating mode for error sanitization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ErrorMode {
    /// Production mode - maximum sanitization, minimal information disclosure
    Production,
    /// Development mode - balanced sanitization, more details for debugging
    Development,
    /// Testing mode - minimal sanitization, full details for test validation
    Testing,
}

/// Error classification levels for secure error handling
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorLevel {
    /// Safe for external users - no sensitive information
    Public,
    /// For internal logging only - may contain sensitive details
    Internal,
    /// Development only - full details, stripped in release builds
    Debug,
}

/// Context where error occurred
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorContext {
    /// File open operation
    FileOpen,
    /// File read operation
    FileRead,
    /// File write operation
    FileWrite,
    /// Network request
    NetworkRequest,
    /// XML parsing
    XmlParsing,
    /// XML building
    XmlBuilding,
    /// Security validation
    SecurityValidation,
    /// Entity classification
    EntityClassification,
    /// Path validation
    PathValidation,
    /// Memory allocation
    MemoryAllocation,
    /// Database connection
    DatabaseConnection,
    /// Authentication check
    Authentication,
    /// Authorization check
    Authorization,
}

/// Trait for secure error handling with multiple disclosure levels
pub trait SecureError: fmt::Display + fmt::Debug {
    /// Get the public-safe error message
    fn public_message(&self) -> String;

    /// Get the internal error message for logging
    fn internal_message(&self) -> String;

    /// Get the debug error message (development only)
    fn debug_message(&self) -> String;

    /// Get the error classification level
    fn error_level(&self) -> ErrorLevel;

    /// Get the error context
    fn error_context(&self) -> ErrorContext;

    /// Generate a unique error ID for correlation
    fn error_id(&self) -> String {
        Uuid::new_v4().to_string()
    }
}

/// Rule for redacting sensitive information from error messages
#[derive(Debug, Clone)]
pub struct RedactionRule {
    /// Name of the rule for identification
    pub name: String,
    /// Regex pattern to match sensitive data
    pub pattern: Regex,
    /// Replacement text (may include capture groups)
    pub replacement: String,
    /// Whether this rule applies in production mode
    pub production: bool,
    /// Whether this rule applies in development mode
    pub development: bool,
    /// Whether this rule applies in testing mode
    pub testing: bool,
}

impl RedactionRule {
    /// Create a new redaction rule
    pub fn new(
        name: &str,
        pattern: &str,
        replacement: &str,
        production: bool,
        development: bool,
        testing: bool,
    ) -> Result<Self, regex::Error> {
        Ok(RedactionRule {
            name: name.to_string(),
            pattern: Regex::new(pattern)?,
            replacement: replacement.to_string(),
            production,
            development,
            testing,
        })
    }

    /// Check if this rule applies in the given mode
    pub fn applies_to_mode(&self, mode: ErrorMode) -> bool {
        match mode {
            ErrorMode::Production => self.production,
            ErrorMode::Development => self.development,
            ErrorMode::Testing => self.testing,
        }
    }

    /// Apply this rule to a message
    pub fn apply(&self, message: &str) -> String {
        self.pattern
            .replace_all(message, self.replacement.as_str())
            .to_string()
    }
}

/// Configuration for error sanitization behavior
#[derive(Debug, Clone)]
pub struct SanitizerConfig {
    /// Operating mode
    pub mode: ErrorMode,
    /// Whether to generate correlation IDs
    pub generate_correlation_ids: bool,
    /// Whether to log internal details
    pub log_internal_details: bool,
    /// Maximum error message length
    pub max_message_length: usize,
    /// Whether to include error codes
    pub include_error_codes: bool,
}

impl Default for SanitizerConfig {
    fn default() -> Self {
        SanitizerConfig {
            mode: if cfg!(debug_assertions) {
                ErrorMode::Development
            } else {
                ErrorMode::Production
            },
            generate_correlation_ids: true,
            log_internal_details: true,
            max_message_length: 256,
            include_error_codes: true,
        }
    }
}

/// Main error sanitization engine
pub struct ErrorSanitizer {
    config: SanitizerConfig,
    redaction_rules: Vec<RedactionRule>,
    error_code_map: HashMap<ErrorContext, &'static str>,
    correlation_store: HashMap<String, String>,
}

/// Sanitized error result with correlation ID
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SanitizedError {
    /// Correlation ID for internal tracking
    pub correlation_id: String,
    /// Public-safe error message
    pub message: String,
    /// Error code for programmatic handling
    pub code: Option<String>,
    /// Additional context that's safe to expose
    pub context: Option<String>,
}

impl fmt::Display for SanitizedError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(code) = &self.code {
            write!(f, "[{}] {}", code, self.message)?;
        } else {
            write!(f, "{}", self.message)?;
        }

        if let Some(context) = &self.context {
            write!(f, " ({})", context)?;
        }

        write!(f, " [ID: {}]", &self.correlation_id[0..8])
    }
}

/// Pre-defined redaction rules for common sensitive data patterns
static DEFAULT_REDACTION_RULES: Lazy<Vec<RedactionRule>> = Lazy::new(|| {
    let mut rules = Vec::new();

    // File system paths - most aggressive in production
    if let Ok(rule) = RedactionRule::new(
        "filesystem_paths",
        r"(/[^/\s]+)+(/[^/\s]*\.[^/\s]+)?|([A-Z]:\\[^\\]+\\[^\\]*)",
        "<file path>",
        true,  // production
        false, // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // Development-friendly path redaction (keep filename)
    if let Ok(rule) = RedactionRule::new(
        "filesystem_paths_dev",
        r"(/[^/\s]+)+/([^/\s]*\.[^/\s]+)|([A-Z]:\\[^\\]+\\[^\\]*)\\([^\\]*)",
        "<path>/$2$4",
        false, // production
        true,  // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // IP addresses
    if let Ok(rule) = RedactionRule::new(
        "ip_addresses",
        r"\b(?:\d{1,3}\.){3}\d{1,3}\b|\b[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4}){7}\b",
        "<ip address>",
        true,  // production
        true,  // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // Hostnames and URLs
    if let Ok(rule) = RedactionRule::new(
        "hostnames",
        r"https?://[^\s/$.?#].[^\s]*|[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:[/\s]|$)",
        "<hostname>",
        true,  // production
        true,  // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // Memory addresses
    if let Ok(rule) = RedactionRule::new(
        "memory_addresses",
        r"0x[0-9a-fA-F]+|[0-9a-fA-F]{8,16}",
        "<memory address>",
        true,  // production
        true,  // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // Stack traces (line numbers and function names)
    if let Ok(rule) = RedactionRule::new(
        "stack_traces",
        r"at [^:]+:\d+:\d+|in `[^`]+`",
        "<stack trace>",
        true,  // production
        false, // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // API keys and tokens (basic patterns)
    if let Ok(rule) = RedactionRule::new(
        "api_keys",
        r#"(?i)(api_?key|token|secret|password|auth)[\s]*[:=][\s]*"?([a-zA-Z0-9\-_]{16,})"?"#,
        "$1=<redacted>",
        true, // production
        true, // development
        true, // testing (even in testing, don't leak real keys)
    ) {
        rules.push(rule);
    }

    // User-specific paths (home directories)
    if let Ok(rule) = RedactionRule::new(
        "user_paths",
        r"/Users/[^/\s]+|/home/[^/\s]+|C:\\Users\\[^\\\\]+",
        "<user directory>",
        true,  // production
        true,  // development
        false, // testing
    ) {
        rules.push(rule);
    }

    // Database connection strings
    if let Ok(rule) = RedactionRule::new(
        "db_connections",
        r"(?i)(mysql|postgres|mongodb)://[^@\s]+@[^/\s]+/[^\s]*",
        "$1://<connection>",
        true, // production
        true, // development
        true, // testing
    ) {
        rules.push(rule);
    }

    rules
});

impl ErrorSanitizer {
    /// Create a new error sanitizer with default configuration
    pub fn new() -> Self {
        Self::with_config(SanitizerConfig::default())
    }

    /// Create a new error sanitizer with custom configuration
    pub fn with_config(config: SanitizerConfig) -> Self {
        let error_code_map = Self::create_error_code_map();

        ErrorSanitizer {
            config,
            redaction_rules: DEFAULT_REDACTION_RULES.clone(),
            error_code_map,
            correlation_store: HashMap::new(),
        }
    }

    /// Add a custom redaction rule
    pub fn add_redaction_rule(&mut self, rule: RedactionRule) {
        self.redaction_rules.push(rule);
    }

    /// Sanitize an error message based on context and mode
    pub fn sanitize<E>(&mut self, error: E, context: ErrorContext) -> SanitizedError
    where
        E: std::error::Error + fmt::Display + fmt::Debug,
    {
        let correlation_id = if self.config.generate_correlation_ids {
            Uuid::new_v4().to_string()
        } else {
            "none".to_string()
        };

        // Get the raw error message
        let raw_message = error.to_string();
        let debug_message = format!("{:?}", error);

        // Log full details internally if enabled
        if self.config.log_internal_details {
            error!(
                correlation_id = %correlation_id,
                context = ?context,
                raw_message = %raw_message,
                debug_info = %debug_message,
                "Internal error details"
            );

            // Store full details for potential debugging
            if self.config.generate_correlation_ids {
                self.correlation_store.insert(
                    correlation_id.clone(),
                    format!(
                        "Context: {:?}, Error: {}, Debug: {}",
                        context, raw_message, debug_message
                    ),
                );
            }
        }

        // Apply sanitization based on mode and context
        let sanitized_message = self.apply_sanitization(&raw_message, context);

        // Truncate if too long
        let final_message = if sanitized_message.len() > self.config.max_message_length {
            format!(
                "{}...",
                &sanitized_message[0..self.config.max_message_length.saturating_sub(3)]
            )
        } else {
            sanitized_message
        };

        // Get error code
        let error_code = if self.config.include_error_codes {
            self.error_code_map.get(&context).map(|&s| s.to_string())
        } else {
            None
        };

        SanitizedError {
            correlation_id,
            message: final_message,
            code: error_code,
            context: Some(self.get_safe_context_description(context)),
        }
    }

    /// Apply sanitization rules to a message
    fn apply_sanitization(&self, message: &str, context: ErrorContext) -> String {
        let mut sanitized = message.to_string();

        // Apply context-specific sanitization first
        sanitized = self.apply_context_specific_sanitization(sanitized, context);

        // Apply general redaction rules
        for rule in &self.redaction_rules {
            if rule.applies_to_mode(self.config.mode) {
                sanitized = rule.apply(&sanitized);
            }
        }

        sanitized
    }

    /// Apply context-specific sanitization logic
    fn apply_context_specific_sanitization(
        &self,
        message: String,
        context: ErrorContext,
    ) -> String {
        match (context, self.config.mode) {
            (
                ErrorContext::FileOpen | ErrorContext::FileRead | ErrorContext::FileWrite,
                ErrorMode::Production,
            ) => "File operation failed".to_string(),
            (
                ErrorContext::FileOpen | ErrorContext::FileRead | ErrorContext::FileWrite,
                ErrorMode::Development,
            ) => {
                // Keep operation type but redact full paths
                let operation = match context {
                    ErrorContext::FileOpen => "open",
                    ErrorContext::FileRead => "read",
                    ErrorContext::FileWrite => "write",
                    _ => "access",
                };
                format!("Failed to {} file", operation)
            }
            (ErrorContext::NetworkRequest, ErrorMode::Production) => {
                "Network operation failed".to_string()
            }
            (ErrorContext::XmlParsing, ErrorMode::Production) => {
                "Invalid XML structure".to_string()
            }
            (ErrorContext::XmlBuilding, ErrorMode::Production) => {
                "XML generation failed".to_string()
            }
            (ErrorContext::SecurityValidation, ErrorMode::Production) => {
                "Security validation failed".to_string()
            }
            (ErrorContext::EntityClassification, ErrorMode::Production) => {
                "Entity validation failed".to_string()
            }
            (ErrorContext::PathValidation, ErrorMode::Production) => {
                "Path validation failed".to_string()
            }
            (ErrorContext::MemoryAllocation, ErrorMode::Production) => {
                "Memory allocation failed".to_string()
            }
            (ErrorContext::DatabaseConnection, ErrorMode::Production) => {
                "Database connection failed".to_string()
            }
            (ErrorContext::Authentication, ErrorMode::Production) => {
                "Authentication failed".to_string()
            }
            (ErrorContext::Authorization, ErrorMode::Production) => "Access denied".to_string(),
            // In development and testing modes, allow more detail
            _ => message,
        }
    }

    /// Create error code mapping
    fn create_error_code_map() -> HashMap<ErrorContext, &'static str> {
        let mut map = HashMap::new();
        map.insert(ErrorContext::FileOpen, "E1001");
        map.insert(ErrorContext::FileRead, "E1002");
        map.insert(ErrorContext::FileWrite, "E1003");
        map.insert(ErrorContext::NetworkRequest, "E2001");
        map.insert(ErrorContext::XmlParsing, "E3001");
        map.insert(ErrorContext::XmlBuilding, "E3002");
        map.insert(ErrorContext::SecurityValidation, "E4001");
        map.insert(ErrorContext::EntityClassification, "E4002");
        map.insert(ErrorContext::PathValidation, "E4003");
        map.insert(ErrorContext::MemoryAllocation, "E5001");
        map.insert(ErrorContext::DatabaseConnection, "E6001");
        map.insert(ErrorContext::Authentication, "E7001");
        map.insert(ErrorContext::Authorization, "E7002");
        map
    }

    /// Get a safe description of the error context
    fn get_safe_context_description(&self, context: ErrorContext) -> String {
        match context {
            ErrorContext::FileOpen => "file access".to_string(),
            ErrorContext::FileRead => "file reading".to_string(),
            ErrorContext::FileWrite => "file writing".to_string(),
            ErrorContext::NetworkRequest => "network operation".to_string(),
            ErrorContext::XmlParsing => "XML parsing".to_string(),
            ErrorContext::XmlBuilding => "XML generation".to_string(),
            ErrorContext::SecurityValidation => "security check".to_string(),
            ErrorContext::EntityClassification => "entity validation".to_string(),
            ErrorContext::PathValidation => "path validation".to_string(),
            ErrorContext::MemoryAllocation => "memory management".to_string(),
            ErrorContext::DatabaseConnection => "database access".to_string(),
            ErrorContext::Authentication => "authentication".to_string(),
            ErrorContext::Authorization => "authorization".to_string(),
        }
    }

    /// Retrieve stored error details by correlation ID (for debugging)
    pub fn get_error_details(&self, correlation_id: &str) -> Option<&String> {
        self.correlation_store.get(correlation_id)
    }

    /// Clear stored error details (for memory management)
    pub fn clear_error_store(&mut self) {
        self.correlation_store.clear();
    }

    /// Get statistics about sanitization
    pub fn get_statistics(&self) -> SanitizerStatistics {
        SanitizerStatistics {
            mode: self.config.mode,
            active_rules: self
                .redaction_rules
                .iter()
                .filter(|r| r.applies_to_mode(self.config.mode))
                .count(),
            stored_errors: self.correlation_store.len(),
        }
    }
}

/// Statistics about the error sanitizer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SanitizerStatistics {
    /// Current error handling mode
    pub mode: ErrorMode,
    /// Number of active sanitization rules
    pub active_rules: usize,
    /// Number of errors stored for analysis
    pub stored_errors: usize,
}

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

/// Convenience functions for common error types
impl ErrorSanitizer {
    /// Sanitize an I/O error
    pub fn sanitize_io_error<E>(&mut self, error: E, context: ErrorContext) -> SanitizedError
    where
        E: std::error::Error + fmt::Display + fmt::Debug,
    {
        self.sanitize(error, context)
    }

    /// Sanitize a parsing error
    pub fn sanitize_parse_error<E>(&mut self, error: E) -> SanitizedError
    where
        E: std::error::Error + fmt::Display + fmt::Debug,
    {
        self.sanitize(error, ErrorContext::XmlParsing)
    }

    /// Sanitize a build error
    pub fn sanitize_build_error<E>(&mut self, error: E) -> SanitizedError
    where
        E: std::error::Error + fmt::Display + fmt::Debug,
    {
        self.sanitize(error, ErrorContext::XmlBuilding)
    }

    /// Sanitize a security error
    pub fn sanitize_security_error<E>(&mut self, error: E) -> SanitizedError
    where
        E: std::error::Error + fmt::Display + fmt::Debug,
    {
        self.sanitize(error, ErrorContext::SecurityValidation)
    }
}

/// Global error sanitizer instance - thread-safe and no unsafe code required
static GLOBAL_SANITIZER: Lazy<Mutex<ErrorSanitizer>> =
    Lazy::new(|| Mutex::new(ErrorSanitizer::with_config(SanitizerConfig::default())));

/// Initialize the global error sanitizer with custom configuration
pub fn init_global_sanitizer(config: SanitizerConfig) {
    // Replace the default sanitizer with one using the provided config
    *GLOBAL_SANITIZER.lock().unwrap() = ErrorSanitizer::with_config(config);
}

/// Get access to the global error sanitizer
pub fn with_global_sanitizer<F, R>(f: F) -> R
where
    F: FnOnce(&mut ErrorSanitizer) -> R,
{
    let mut sanitizer = GLOBAL_SANITIZER.lock().unwrap();
    f(&mut *sanitizer)
}

/// Quick sanitization functions using global sanitizer
pub fn sanitize_error<E>(error: E, context: ErrorContext) -> SanitizedError
where
    E: std::error::Error + fmt::Display + fmt::Debug,
{
    with_global_sanitizer(|sanitizer| sanitizer.sanitize(error, context))
}

/// Sanitize IO error for safe external reporting
pub fn sanitize_io_error<E>(error: E, context: ErrorContext) -> SanitizedError
where
    E: std::error::Error + fmt::Display + fmt::Debug,
{
    with_global_sanitizer(|sanitizer| sanitizer.sanitize_io_error(error, context))
}

/// Sanitize parse error for safe external reporting
pub fn sanitize_parse_error<E>(error: E) -> SanitizedError
where
    E: std::error::Error + fmt::Display + fmt::Debug,
{
    with_global_sanitizer(|sanitizer| sanitizer.sanitize_parse_error(error))
}

/// Sanitize build error for safe external reporting
pub fn sanitize_build_error<E>(error: E) -> SanitizedError
where
    E: std::error::Error + fmt::Display + fmt::Debug,
{
    with_global_sanitizer(|sanitizer| sanitizer.sanitize_build_error(error))
}

/// Sanitize security error for safe external reporting
pub fn sanitize_security_error<E>(error: E) -> SanitizedError
where
    E: std::error::Error + fmt::Display + fmt::Debug,
{
    with_global_sanitizer(|sanitizer| sanitizer.sanitize_security_error(error))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Error, ErrorKind};

    #[test]
    fn test_secure_error_trait() {
        struct TestError {
            message: String,
            context: ErrorContext,
        }

        impl fmt::Display for TestError {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "{}", self.message)
            }
        }

        impl fmt::Debug for TestError {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(
                    f,
                    "TestError {{ message: {:?}, context: {:?} }}",
                    self.message, self.context
                )
            }
        }

        impl std::error::Error for TestError {}

        impl SecureError for TestError {
            fn public_message(&self) -> String {
                "Operation failed".to_string()
            }

            fn internal_message(&self) -> String {
                self.message.clone()
            }

            fn debug_message(&self) -> String {
                format!("{:?}", self)
            }

            fn error_level(&self) -> ErrorLevel {
                ErrorLevel::Internal
            }

            fn error_context(&self) -> ErrorContext {
                self.context
            }
        }

        let error = TestError {
            message: "Detailed error with /path/to/file.txt".to_string(),
            context: ErrorContext::FileRead,
        };

        assert_eq!(error.public_message(), "Operation failed");
        assert!(error.internal_message().contains("/path/to/file.txt"));
        assert_eq!(error.error_level(), ErrorLevel::Internal);
        assert_eq!(error.error_context(), ErrorContext::FileRead);
    }

    #[test]
    fn test_redaction_rules() {
        let rule = RedactionRule::new(
            "test_paths",
            r"/[^/\s]+/[^/\s]+",
            "<redacted path>",
            true,
            true,
            false,
        )
        .unwrap();

        let message = "Failed to open /home/user/secret.txt";
        let redacted = rule.apply(message);
        assert_eq!(redacted, "Failed to open <redacted path>/secret.txt");

        assert!(rule.applies_to_mode(ErrorMode::Production));
        assert!(rule.applies_to_mode(ErrorMode::Development));
        assert!(!rule.applies_to_mode(ErrorMode::Testing));
    }

    #[test]
    fn test_error_sanitizer_production_mode() {
        let config = SanitizerConfig {
            mode: ErrorMode::Production,
            generate_correlation_ids: true,
            log_internal_details: false, // Don't spam logs in tests
            max_message_length: 100,
            include_error_codes: true,
        };

        let mut sanitizer = ErrorSanitizer::with_config(config);
        let io_error = Error::new(
            ErrorKind::NotFound,
            "File not found: /home/user/secrets.txt",
        );

        let sanitized = sanitizer.sanitize_io_error(io_error, ErrorContext::FileOpen);

        assert_eq!(sanitized.message, "File operation failed");
        assert_eq!(sanitized.code, Some("E1001".to_string()));
        assert!(sanitized.context.is_some());
        assert!(!sanitized.correlation_id.is_empty());
    }

    #[test]
    fn test_error_sanitizer_development_mode() {
        let config = SanitizerConfig {
            mode: ErrorMode::Development,
            generate_correlation_ids: true,
            log_internal_details: false,
            max_message_length: 200,
            include_error_codes: true,
        };

        let mut sanitizer = ErrorSanitizer::with_config(config);
        let io_error = Error::new(
            ErrorKind::PermissionDenied,
            "Permission denied: /etc/shadow",
        );

        let sanitized = sanitizer.sanitize_io_error(io_error, ErrorContext::FileRead);

        // Should be more descriptive in development mode
        assert!(sanitized.message.contains("file"));
        assert_eq!(sanitized.code, Some("E1002".to_string()));
        assert!(sanitized.context.is_some());
    }

    #[test]
    fn test_path_redaction() {
        let mut sanitizer = ErrorSanitizer::with_config(SanitizerConfig {
            mode: ErrorMode::Production,
            ..SanitizerConfig::default()
        });

        let error = Error::new(
            ErrorKind::NotFound,
            "Cannot find /Users/john/Documents/secret.pdf",
        );
        let sanitized = sanitizer.sanitize_io_error(error, ErrorContext::FileOpen);

        // In production mode, should get generic message
        assert_eq!(sanitized.message, "File operation failed");
    }

    #[test]
    fn test_ip_address_redaction() {
        let rule = RedactionRule::new(
            "test_ips",
            r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
            "<ip>",
            true,
            true,
            true,
        )
        .unwrap();

        let message = "Connection failed to 192.168.1.1:8080";
        let redacted = rule.apply(message);
        assert_eq!(redacted, "Connection failed to <ip>:8080");
    }

    #[test]
    fn test_memory_address_redaction() {
        let rule = RedactionRule::new(
            "test_memory",
            r"0x[0-9a-fA-F]+",
            "<addr>",
            true,
            true,
            false,
        )
        .unwrap();

        let message = "Segfault at address 0x7fff5fbff000";
        let redacted = rule.apply(message);
        assert_eq!(redacted, "Segfault at address <addr>");
    }

    #[test]
    fn test_api_key_redaction() {
        let rule = RedactionRule::new(
            "test_keys",
            r#"(?i)(api_?key|token)[\s]*[:=][\s]*"?[a-zA-Z0-9\-_]{16,}"?"#,
            "$1=<redacted>",
            true,
            true,
            true,
        )
        .unwrap();

        let message = r#"Authentication failed: api_key="sk_test_123456789abcdefghij""#;
        let redacted = rule.apply(message);
        assert!(redacted.contains("api_key=<redacted>"));
        assert!(!redacted.contains("sk_test_123456789abcdefghij"));
    }

    #[test]
    fn test_context_specific_sanitization() {
        let mut sanitizer = ErrorSanitizer::with_config(SanitizerConfig {
            mode: ErrorMode::Production,
            ..SanitizerConfig::default()
        });

        // Test different contexts
        let contexts = vec![
            (ErrorContext::XmlParsing, "Invalid XML structure"),
            (ErrorContext::XmlBuilding, "XML generation failed"),
            (
                ErrorContext::SecurityValidation,
                "Security validation failed",
            ),
            (ErrorContext::Authentication, "Authentication failed"),
            (ErrorContext::Authorization, "Access denied"),
        ];

        for (context, expected) in contexts {
            let error = Error::new(
                ErrorKind::InvalidInput,
                "Detailed error message with /path/to/file.txt",
            );
            let sanitized = sanitizer.sanitize_io_error(error, context);
            assert_eq!(sanitized.message, expected);
        }
    }

    #[test]
    fn test_message_length_truncation() {
        let config = SanitizerConfig {
            mode: ErrorMode::Testing, // Allow full message to test truncation
            max_message_length: 20,
            ..SanitizerConfig::default()
        };

        let mut sanitizer = ErrorSanitizer::with_config(config);
        let long_error = Error::new(
            ErrorKind::Other,
            "This is a very long error message that should be truncated.",
        );

        let sanitized = sanitizer.sanitize_io_error(long_error, ErrorContext::FileRead);
        assert!(sanitized.message.len() <= 20);
        assert!(sanitized.message.ends_with("..."));
    }

    #[test]
    fn test_correlation_id_generation() {
        let mut sanitizer = ErrorSanitizer::with_config(SanitizerConfig {
            generate_correlation_ids: true,
            ..SanitizerConfig::default()
        });

        let error1 = Error::new(ErrorKind::NotFound, "Error 1");
        let error2 = Error::new(ErrorKind::NotFound, "Error 2");

        let sanitized1 = sanitizer.sanitize_io_error(error1, ErrorContext::FileOpen);
        let sanitized2 = sanitizer.sanitize_io_error(error2, ErrorContext::FileOpen);

        assert_ne!(sanitized1.correlation_id, sanitized2.correlation_id);
        assert!(!sanitized1.correlation_id.is_empty());
        assert!(!sanitized2.correlation_id.is_empty());
    }

    #[test]
    fn test_error_codes() {
        let sanitizer = ErrorSanitizer::new();
        let stats = sanitizer.get_statistics();

        assert_eq!(
            stats.mode,
            if cfg!(debug_assertions) {
                ErrorMode::Development
            } else {
                ErrorMode::Production
            }
        );
        assert!(stats.active_rules > 0);
        assert_eq!(stats.stored_errors, 0);
    }

    #[test]
    fn test_global_sanitizer() {
        let error = Error::new(
            ErrorKind::PermissionDenied,
            "Access denied to /secret/file.txt",
        );
        let sanitized = sanitize_io_error(error, ErrorContext::FileRead);

        assert!(!sanitized.correlation_id.is_empty());
        assert!(!sanitized.message.is_empty());
        assert!(sanitized.code.is_some());
    }
}