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
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! Security module for DDEX Builder
//!
//! This module provides comprehensive security measures including:
//! - XXE (XML External Entity) attack prevention
//! - Input validation and sanitization
//! - Cross-platform path traversal prevention
//! - Size limits and rate limiting
//! - Safe XML parsing configuration

pub mod entity_classifier;
pub mod error_sanitizer;
pub mod path_validator;

// Re-export entity classifier types for public use
pub use self::entity_classifier::{
    create_entity, create_external_entity, create_parameter_entity, AttackType, ClassifierConfig,
    Entity, EntityClass, EntityClassifier, EntityMetrics, ValidationResult,
};

// Re-export path validator types
pub use self::path_validator::{PathValidationConfig, PathValidator, ValidatedPath};

// Re-export error sanitizer types
pub use self::error_sanitizer::{
    sanitize_build_error, sanitize_error, sanitize_io_error, sanitize_parse_error,
    sanitize_security_error, ErrorContext, ErrorLevel, ErrorMode, ErrorSanitizer, RedactionRule,
    SanitizedError, SanitizerConfig, SanitizerStatistics, SecureError,
};

use crate::error::BuildError;
use once_cell::sync::Lazy;
use quick_xml::events::Event;
use quick_xml::Reader;
use regex::Regex;
use std::io::BufRead;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tracing::{debug, warn};
use url::Url;

/// Maximum allowed size for XML input (100MB)
const MAX_XML_SIZE: usize = 100 * 1024 * 1024;

/// Maximum allowed size for JSON input (50MB)
const MAX_JSON_SIZE: usize = 50 * 1024 * 1024;

/// Maximum allowed size for any string field (1MB)
const MAX_STRING_SIZE: usize = 1024 * 1024;

/// Maximum nesting depth for XML elements
const MAX_XML_DEPTH: usize = 100;

/// Maximum number of XML attributes per element
const MAX_ATTRIBUTES_PER_ELEMENT: usize = 100;

/// Maximum number of child elements
const MAX_CHILD_ELEMENTS: usize = 10000;

/// Rate limiting configuration
const MAX_REQUESTS_PER_MINUTE: u32 = 100;
const RATE_LIMIT_WINDOW: Duration = Duration::from_secs(60);

/// Dangerous XML entity patterns (ENTITY declarations only - let standard entities pass)
static DANGEROUS_ENTITY_REGEX: Lazy<Regex> = Lazy::new(|| {
    // Only match ENTITY declarations, not entity references (which are checked separately)
    Regex::new(r"<!ENTITY\s+[^>]*>").unwrap()
});

/// Check if string contains only safe standard XML entities
fn contains_only_safe_entities(input: &str) -> bool {
    // Find all entity references
    let re = Regex::new(r"&([a-zA-Z_][a-zA-Z0-9._-]*|#[0-9]+|#x[0-9a-fA-F]+);").unwrap();
    for cap in re.captures_iter(input) {
        let entity = &cap[1];
        // Check if it's one of the standard safe entities
        match entity {
            "lt" | "gt" | "amp" | "quot" | "apos" => continue,
            _ if entity.starts_with('#') => continue, // Numeric character references are safe
            _ => return false,                        // Custom entity found
        }
    }
    true
}

/// External reference patterns
static EXTERNAL_REF_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"(SYSTEM|PUBLIC)\s+['"][^'"]*['"]"#).unwrap());

/// Potentially dangerous file path patterns
#[allow(dead_code)]
static DANGEROUS_PATH_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\.\./|\\\.\\\|/etc/|/proc/|/sys/|/dev/|/tmp/|C:\\|\\\\").unwrap());

/// SQL injection patterns
static SQL_INJECTION_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?i)(union|select|insert|update|delete|drop|exec|script|javascript|vbscript|onload|onerror)").unwrap()
});

/// XML bomb pattern detection
static XML_BOMB_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r#"<!ENTITY\s+\w+\s+['"](&\w+;)+['"]"#).unwrap());

/// Security configuration for XML parsing
#[derive(Debug, Clone)]
pub struct SecurityConfig {
    /// Maximum XML input size
    pub max_xml_size: usize,
    /// Maximum JSON input size  
    pub max_json_size: usize,
    /// Maximum string field size
    pub max_string_size: usize,
    /// Maximum XML nesting depth
    pub max_xml_depth: usize,
    /// Maximum attributes per element
    pub max_attributes_per_element: usize,
    /// Maximum child elements
    pub max_child_elements: usize,
    /// Whether to allow external entities
    pub allow_external_entities: bool,
    /// Whether to allow DTD processing
    pub allow_dtd: bool,
    /// Rate limiting enabled
    pub rate_limiting_enabled: bool,
    /// Maximum requests per minute
    pub max_requests_per_minute: u32,
    /// Enable advanced entity classification
    pub enable_entity_classification: bool,
    /// Maximum allowed entity expansion ratio
    pub max_entity_expansion_ratio: f64,
    /// Maximum entity recursion depth
    pub max_entity_depth: usize,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            max_xml_size: MAX_XML_SIZE,
            max_json_size: MAX_JSON_SIZE,
            max_string_size: MAX_STRING_SIZE,
            max_xml_depth: MAX_XML_DEPTH,
            max_attributes_per_element: MAX_ATTRIBUTES_PER_ELEMENT,
            max_child_elements: MAX_CHILD_ELEMENTS,
            allow_external_entities: false, // CRITICAL: Never allow external entities
            allow_dtd: false,               // CRITICAL: Never allow DTD processing
            rate_limiting_enabled: true,
            max_requests_per_minute: MAX_REQUESTS_PER_MINUTE,
            enable_entity_classification: true, // Enable advanced entity analysis
            max_entity_expansion_ratio: 10.0,   // Max 10x expansion
            max_entity_depth: 3,                // Max 3 levels deep
        }
    }
}

/// Secure XML reader with XXE protection
pub struct SecureXmlReader<R: BufRead> {
    reader: Reader<R>,
    config: SecurityConfig,
    current_depth: usize,
    element_count: usize,
    start_time: Instant,
}

impl<R: BufRead> SecureXmlReader<R> {
    /// Create a new secure XML reader
    pub fn new(reader: R, config: SecurityConfig) -> Self {
        let mut xml_reader = Reader::from_reader(reader);

        // Configure reader for security
        xml_reader.config_mut().check_comments = false;
        xml_reader.config_mut().check_end_names = true;
        xml_reader.config_mut().trim_text_start = true;
        xml_reader.config_mut().trim_text_end = true;
        xml_reader.config_mut().expand_empty_elements = false;

        Self {
            reader: xml_reader,
            config,
            current_depth: 0,
            element_count: 0,
            start_time: Instant::now(),
        }
    }

    /// Read the next event with security checks
    pub fn read_event<'a>(&mut self, buf: &'a mut Vec<u8>) -> Result<Event<'a>, BuildError> {
        // Check for timeout to prevent DoS
        if self.start_time.elapsed() > Duration::from_secs(30) {
            return Err(BuildError::Security("XML processing timeout".to_string()));
        }

        let event = self
            .reader
            .read_event_into(buf)
            .map_err(|e| BuildError::Security(format!("XML parsing error: {}", e)))?;

        match &event {
            Event::Start(_) => {
                self.current_depth += 1;
                self.element_count += 1;

                // Check depth limit
                if self.current_depth > self.config.max_xml_depth {
                    return Err(BuildError::Security(format!(
                        "XML nesting too deep: {} > {}",
                        self.current_depth, self.config.max_xml_depth
                    )));
                }

                // Check element count limit
                if self.element_count > self.config.max_child_elements {
                    return Err(BuildError::Security(format!(
                        "Too many XML elements: {} > {}",
                        self.element_count, self.config.max_child_elements
                    )));
                }
            }
            Event::End(_) => {
                self.current_depth = self.current_depth.saturating_sub(1);
            }
            Event::DocType(dt) => {
                if !self.config.allow_dtd {
                    return Err(BuildError::Security(
                        "DTD processing not allowed".to_string(),
                    ));
                }

                // Check for dangerous DTD content
                let dtd_str = String::from_utf8_lossy(dt.as_ref());
                if DANGEROUS_ENTITY_REGEX.is_match(&dtd_str) {
                    return Err(BuildError::Security(
                        "Dangerous entity detected in DTD".to_string(),
                    ));
                }

                if EXTERNAL_REF_REGEX.is_match(&dtd_str) {
                    return Err(BuildError::Security(
                        "External reference detected in DTD".to_string(),
                    ));
                }

                if XML_BOMB_REGEX.is_match(&dtd_str) {
                    return Err(BuildError::Security(
                        "Potential XML bomb detected".to_string(),
                    ));
                }
            }
            _ => {}
        }

        Ok(event)
    }

    /// Get the underlying reader
    pub fn into_inner(self) -> Reader<R> {
        self.reader
    }
}

/// Input validator for various data types
pub struct InputValidator {
    config: SecurityConfig,
    entity_classifier: Option<EntityClassifier>,
}

impl InputValidator {
    /// Create a new input validator
    pub fn new(config: SecurityConfig) -> Self {
        let entity_classifier = if config.enable_entity_classification {
            let mut classifier_config = entity_classifier::ClassifierConfig::default();
            classifier_config.max_expansion_ratio = config.max_entity_expansion_ratio;
            classifier_config.max_depth = config.max_entity_depth;
            classifier_config.allow_external_entities = config.allow_external_entities;
            Some(EntityClassifier::with_config(classifier_config))
        } else {
            None
        };

        Self {
            config,
            entity_classifier,
        }
    }

    /// Validate and sanitize a string input
    pub fn validate_string(&self, input: &str, field_name: &str) -> Result<String, BuildError> {
        // Check size limit
        if input.len() > self.config.max_string_size {
            return Err(BuildError::InputSanitization(format!(
                "String too long for field '{}': {} > {}",
                field_name,
                input.len(),
                self.config.max_string_size
            )));
        }

        // Check for null bytes
        if input.contains('\0') {
            return Err(BuildError::InputSanitization(format!(
                "Null byte detected in field '{}'",
                field_name
            )));
        }

        // Check for potential injection attacks
        if SQL_INJECTION_REGEX.is_match(input) {
            return Err(BuildError::InputSanitization(format!(
                "Potential injection attack detected in field '{}'",
                field_name
            )));
        }

        // Check for dangerous entity references (custom entities only, not standard ones)
        if !contains_only_safe_entities(input) {
            return Err(BuildError::InputSanitization(format!(
                "Dangerous entity reference detected in field '{}'",
                field_name
            )));
        }

        // Check for path traversal patterns
        if input.contains("../")
            || input.contains("..\\")
            || input.contains("/etc/")
            || input.contains("C:\\")
        {
            return Err(BuildError::InputSanitization(format!(
                "Path traversal pattern detected in field '{}'",
                field_name
            )));
        }

        // Normalize whitespace and control characters
        let sanitized = input
            .chars()
            .filter(|&c| !c.is_control() || c == '\n' || c == '\r' || c == '\t')
            .collect::<String>()
            .trim()
            .to_string();

        Ok(sanitized)
    }

    /// Validate a file path for safety using the comprehensive cross-platform path validator
    pub fn validate_path(&self, path: &str) -> Result<PathBuf, BuildError> {
        // Create a configuration that allows relative paths but still blocks dangerous patterns
        let mut config = PathValidationConfig::default();
        config.allow_relative_outside_base = true; // Allow relative paths for flexibility
        config.check_existence = false; // Don't require files to exist for validation

        let path_validator = PathValidator::with_config(config);
        let validated_path = path_validator.validate(path)?;

        // Log warnings if any
        if !validated_path.warnings.is_empty() {
            tracing::debug!(
                "Path validation warnings for '{}': {:?}",
                path,
                validated_path.warnings
            );
        }

        Ok(validated_path.normalized)
    }

    /// Validate a file path with custom configuration
    pub fn validate_path_with_config(
        &self,
        path: &str,
        config: PathValidationConfig,
    ) -> Result<PathBuf, BuildError> {
        let path_validator = PathValidator::with_config(config);
        let validated_path = path_validator.validate(path)?;

        // Log warnings if any
        if !validated_path.warnings.is_empty() {
            tracing::debug!(
                "Path validation warnings for '{}': {:?}",
                path,
                validated_path.warnings
            );
        }

        Ok(validated_path.normalized)
    }

    /// Validate a URL for safety
    pub fn validate_url(&self, url_str: &str) -> Result<Url, BuildError> {
        // Parse URL
        let url = Url::parse(url_str)
            .map_err(|e| BuildError::InputSanitization(format!("Invalid URL: {}", e)))?;

        // Only allow safe schemes
        match url.scheme() {
            "http" | "https" => {}
            _ => {
                return Err(BuildError::InputSanitization(format!(
                    "Unsafe URL scheme: {}",
                    url.scheme()
                )));
            }
        }

        // Reject localhost and private IPs
        if let Some(host_str) = url.host_str() {
            if host_str == "localhost"
                || host_str == "127.0.0.1"
                || host_str == "::1"
                || host_str.starts_with("192.168.")
                || host_str.starts_with("10.")
                || host_str.starts_with("172.")
            {
                return Err(BuildError::InputSanitization(
                    "Private or local URLs not allowed".to_string(),
                ));
            }
        }

        Ok(url)
    }

    /// Validate XML content for security
    pub fn validate_xml_content(&self, xml: &str) -> Result<(), BuildError> {
        // Check size
        if xml.len() > self.config.max_xml_size {
            return Err(BuildError::InputSanitization(format!(
                "XML too large: {} > {}",
                xml.len(),
                self.config.max_xml_size
            )));
        }

        // Check for XXE patterns - ENTITY declarations and custom entities
        if DANGEROUS_ENTITY_REGEX.is_match(xml) {
            return Err(BuildError::Security(
                "XML entity declaration detected".to_string(),
            ));
        }

        // Check for custom (non-standard) entity references
        if !contains_only_safe_entities(xml) {
            return Err(BuildError::Security(
                "Custom entity reference detected".to_string(),
            ));
        }

        if EXTERNAL_REF_REGEX.is_match(xml) {
            return Err(BuildError::Security(
                "External reference detected".to_string(),
            ));
        }

        if XML_BOMB_REGEX.is_match(xml) {
            return Err(BuildError::Security(
                "Potential XML bomb detected".to_string(),
            ));
        }

        // Check for excessive entity expansion
        let entity_count = xml.matches("&").count();
        if entity_count > 1000 {
            return Err(BuildError::Security(
                "Excessive entity usage detected".to_string(),
            ));
        }

        Ok(())
    }

    /// Validate entities using advanced classification system
    pub fn validate_entities(&mut self, entities: &[Entity]) -> Result<(), BuildError> {
        if let Some(ref mut classifier) = self.entity_classifier {
            let result = classifier.validate_entity_chain(entities);

            if !result.is_safe {
                let error_msg = if !result.errors.is_empty() {
                    result.errors.join("; ")
                } else {
                    format!("Entity validation failed: {:?}", result.classification)
                };

                return Err(BuildError::Security(error_msg));
            }

            // Log warnings if any
            if !result.warnings.is_empty() {
                warn!("Entity validation warnings: {}", result.warnings.join("; "));
            }

            // Log metrics for monitoring
            debug!(
                "Entity validation metrics: {} entities, {:.2}x expansion, {}ms processing",
                result.metrics.entity_count,
                result.metrics.expansion_ratio,
                result.metrics.processing_time_ms
            );
        }

        Ok(())
    }

    /// Classify a single entity
    pub fn classify_entity(&mut self, name: &str, value: &str) -> EntityClass {
        if let Some(ref mut classifier) = self.entity_classifier {
            classifier.classify_entity(name, value)
        } else {
            // Fall back to basic classification
            if contains_only_safe_entities(&format!("&{};", name)) {
                EntityClass::SafeBuiltin
            } else {
                EntityClass::CustomLocal
            }
        }
    }

    /// Get entity classification metrics
    pub fn get_entity_metrics(&self) -> Option<Vec<EntityMetrics>> {
        self.entity_classifier
            .as_ref()
            .map(|classifier| classifier.get_metrics_history().iter().cloned().collect())
    }

    /// Validate JSON content for security
    pub fn validate_json_content(&self, json: &str) -> Result<(), BuildError> {
        // Check size
        if json.len() > self.config.max_json_size {
            return Err(BuildError::InputSanitization(format!(
                "JSON too large: {} > {}",
                json.len(),
                self.config.max_json_size
            )));
        }

        // Check for potential injection
        if SQL_INJECTION_REGEX.is_match(json) {
            return Err(BuildError::InputSanitization(
                "Potential injection in JSON".to_string(),
            ));
        }

        // Basic JSON structure validation
        let depth = json
            .chars()
            .fold((0i32, 0i32), |(max_depth, current_depth), c| match c {
                '{' | '[' => (max_depth.max(current_depth + 1), current_depth + 1),
                '}' | ']' => (max_depth, current_depth.saturating_sub(1)),
                _ => (max_depth, current_depth),
            })
            .0;

        if depth > self.config.max_xml_depth as i32 {
            return Err(BuildError::InputSanitization(format!(
                "JSON nesting too deep: {}",
                depth
            )));
        }

        Ok(())
    }
}

/// Rate limiter for API endpoints
#[derive(Debug)]
pub struct RateLimiter {
    requests: indexmap::IndexMap<String, Vec<Instant>>,
    config: SecurityConfig,
}

impl RateLimiter {
    /// Create a new rate limiter
    pub fn new(config: SecurityConfig) -> Self {
        Self {
            requests: indexmap::IndexMap::new(),
            config,
        }
    }

    /// Check if request is allowed for given identifier
    pub fn check_rate_limit(&mut self, identifier: &str) -> Result<(), BuildError> {
        if !self.config.rate_limiting_enabled {
            return Ok(());
        }

        let now = Instant::now();
        let requests = self.requests.entry(identifier.to_string()).or_default();

        // Remove old requests outside the window
        requests.retain(|&req_time| now.duration_since(req_time) <= RATE_LIMIT_WINDOW);

        // Check if limit exceeded
        if requests.len() >= self.config.max_requests_per_minute as usize {
            return Err(BuildError::Security(format!(
                "Rate limit exceeded for {}",
                identifier
            )));
        }

        // Add current request
        requests.push(now);

        Ok(())
    }

    /// Clean up old entries periodically
    pub fn cleanup(&mut self) {
        let now = Instant::now();

        self.requests.retain(|_, requests| {
            requests.retain(|&req_time| now.duration_since(req_time) <= RATE_LIMIT_WINDOW);
            !requests.is_empty()
        });
    }
}

/// Output safety and sanitization
#[derive(Debug)]
pub struct OutputSanitizer {
    #[allow(dead_code)]
    config: SecurityConfig,
}

impl OutputSanitizer {
    /// Create new output sanitizer
    pub fn new(config: SecurityConfig) -> Self {
        Self { config }
    }

    /// Sanitize XML output for safety
    pub fn sanitize_xml_output(&self, xml: &str) -> Result<String, BuildError> {
        // Check for potentially sensitive data patterns
        self.check_for_sensitive_data(xml)?;

        // Validate the XML structure first (before escaping)
        self.validate_xml_structure(xml)?;

        // Ensure proper XML escaping
        let sanitized = self.escape_xml_entities(xml);

        Ok(sanitized)
    }

    /// Check for sensitive data patterns in output
    fn check_for_sensitive_data(&self, content: &str) -> Result<(), BuildError> {
        // Check for common patterns that shouldn't be in output
        let sensitive_patterns = [
            r"<password[^>]*>[^<]+</password>",
            r"<secret[^>]*>[^<]+</secret>",
            r"<key[^>]*>[^<]+</key>",
            r"<token[^>]*>[^<]+</token>",
            r"password\s*[:=]\s*[^\s<]+",
            r"secret\s*[:=]\s*[^\s<]+",
            r"key\s*[:=]\s*[^\s<]+",
            r"token\s*[:=]\s*[^\s<]+",
            r"[A-Za-z0-9+/]{40,}={0,2}", // Base64 encoded data
        ];

        for pattern in &sensitive_patterns {
            if let Ok(regex) = regex::Regex::new(pattern) {
                if regex.is_match(content) {
                    return Err(BuildError::Security(
                        "Potential sensitive data detected in output".to_string(),
                    ));
                }
            }
        }

        Ok(())
    }

    /// Escape XML entities properly
    fn escape_xml_entities(&self, xml: &str) -> String {
        html_escape::encode_text(xml).to_string()
    }

    /// Validate XML structure is well-formed
    fn validate_xml_structure(&self, xml: &str) -> Result<(), BuildError> {
        let mut reader = quick_xml::Reader::from_str(xml);
        reader.config_mut().expand_empty_elements = false;
        reader.config_mut().trim_text(true);

        let mut buf = Vec::new();
        let mut depth = 0;

        loop {
            match reader.read_event_into(&mut buf) {
                Ok(quick_xml::events::Event::Start(_)) => {
                    depth += 1;
                    if depth > MAX_XML_DEPTH {
                        return Err(BuildError::Security(
                            "XML depth limit exceeded in output".to_string(),
                        ));
                    }
                }
                Ok(quick_xml::events::Event::End(_)) => {
                    depth = depth.saturating_sub(1);
                }
                Ok(quick_xml::events::Event::Eof) => break,
                Ok(_) => {}
                Err(e) => {
                    return Err(BuildError::Security(format!(
                        "Invalid XML structure in output: {}",
                        e
                    )));
                }
            }
            buf.clear();
        }

        Ok(())
    }

    /// Generate secure log messages (without sensitive details)
    pub fn create_secure_log_message(
        &self,
        operation: &str,
        success: bool,
        details: Option<&str>,
    ) -> String {
        let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
        let status = if success { "SUCCESS" } else { "FAILED" };

        match details {
            Some(detail) if detail.len() < 100 => {
                // Only include short, non-sensitive details
                let sanitized_detail = self.sanitize_log_detail(detail);
                format!(
                    "[{}] {} - {}: {}",
                    timestamp, operation, status, sanitized_detail
                )
            }
            _ => {
                format!("[{}] {} - {}", timestamp, operation, status)
            }
        }
    }

    /// Sanitize log details to remove sensitive information
    fn sanitize_log_detail(&self, detail: &str) -> String {
        // Remove potential sensitive patterns from log messages
        let sensitive_patterns = [
            (r"password\s*[:=]\s*[^\s]+", "password=[REDACTED]"),
            (r"secret\s*[:=]\s*[^\s]+", "secret=[REDACTED]"),
            (r"key\s*[:=]\s*[^\s]+", "key=[REDACTED]"),
            (r"token\s*[:=]\s*[^\s]+", "token=[REDACTED]"),
        ];

        let mut sanitized = detail.to_string();
        for (pattern, replacement) in &sensitive_patterns {
            if let Ok(regex) = regex::Regex::new(pattern) {
                sanitized = regex.replace_all(&sanitized, *replacement).to_string();
            }
        }

        // Truncate if too long
        if sanitized.len() > 200 {
            sanitized.truncate(197);
            sanitized.push_str("...");
        }

        sanitized
    }
}

/// Secure temporary file handling
pub struct SecureTempFile {
    path: PathBuf,
    file: std::fs::File,
}

impl SecureTempFile {
    /// Create a secure temporary file
    pub fn new() -> Result<Self, BuildError> {
        use std::fs::OpenOptions;
        #[cfg(unix)]
        use std::os::unix::fs::OpenOptionsExt;

        let temp_dir = std::env::temp_dir();
        let file_name = format!("ddex_builder_{}", uuid::Uuid::new_v4());
        let path = temp_dir.join(file_name);

        // Create file with restricted permissions (owner read/write only)
        #[cfg(unix)]
        let file = OpenOptions::new()
            .create_new(true)
            .write(true)
            .read(true)
            .mode(0o600) // Only owner can read/write
            .open(&path)
            .map_err(|e| BuildError::Io(format!("Failed to create secure temp file: {}", e)))?;

        #[cfg(not(unix))]
        let file = OpenOptions::new()
            .create_new(true)
            .write(true)
            .read(true)
            .open(&path)
            .map_err(|e| BuildError::Io(format!("Failed to create secure temp file: {}", e)))?;

        Ok(Self { path, file })
    }

    /// Get the file reference
    pub fn file(&mut self) -> &mut std::fs::File {
        &mut self.file
    }

    /// Get the path
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for SecureTempFile {
    fn drop(&mut self) {
        // Securely delete the file
        let _ = std::fs::remove_file(&self.path);
    }
}

/// Security utilities
pub mod utils {

    /// Sanitize filename for safe storage
    pub fn sanitize_filename(filename: &str) -> String {
        filename
            .chars()
            .filter(|c| c.is_alphanumeric() || *c == '.' || *c == '-' || *c == '_')
            .take(255) // Limit filename length
            .collect::<String>()
            .replace("..", "") // Remove path traversal attempts
    }

    /// Generate secure random ID
    pub fn generate_secure_id() -> String {
        uuid::Uuid::new_v4().to_string()
    }

    /// Constant-time string comparison to prevent timing attacks
    pub fn constant_time_compare(a: &str, b: &str) -> bool {
        if a.len() != b.len() {
            return false;
        }

        let mut result = 0u8;
        for (byte_a, byte_b) in a.bytes().zip(b.bytes()) {
            result |= byte_a ^ byte_b;
        }

        result == 0
    }

    /// Hash sensitive data for logging (truncated SHA-256)
    pub fn hash_for_logging(data: &str) -> String {
        use sha2::{Digest, Sha256};
        let hash = Sha256::digest(data.as_bytes());
        format!("{:.8}", hex::encode(hash))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn test_input_validation() {
        let config = SecurityConfig::default();
        let validator = InputValidator::new(config);

        // Test valid string
        assert!(validator.validate_string("Valid input", "test").is_ok());

        // Test string with null byte
        assert!(validator.validate_string("Invalid\0input", "test").is_err());

        // Test SQL injection attempt
        assert!(validator
            .validate_string("'; DROP TABLE users; --", "test")
            .is_err());

        // Test dangerous entity
        assert!(validator.validate_string("&dangerous;", "test").is_err());
    }

    #[test]
    fn test_path_validation() {
        let config = SecurityConfig::default();
        let validator = InputValidator::new(config);

        // Test valid path
        assert!(validator.validate_path("safe/path/file.xml").is_ok());

        // Test path traversal
        assert!(validator.validate_path("../../../etc/passwd").is_err());

        // Test absolute path
        assert!(validator.validate_path("/etc/passwd").is_err());
    }

    #[test]
    fn test_xml_security() {
        let config = SecurityConfig::default();
        let validator = InputValidator::new(config);

        // Test safe XML
        assert!(validator
            .validate_xml_content("<root><child>content</child></root>")
            .is_ok());

        // Test XXE attempt
        assert!(validator
            .validate_xml_content(
                "<!DOCTYPE test [<!ENTITY xxe SYSTEM 'file:///etc/passwd'>]><root>&xxe;</root>"
            )
            .is_err());

        // Test XML bomb
        assert!(validator.validate_xml_content(
            "<!DOCTYPE bomb [<!ENTITY a '&b;&b;'><!ENTITY b '&c;&c;'><!ENTITY c 'boom'>]><root>&a;</root>"
        ).is_err());
    }

    #[test]
    fn test_secure_xml_reader() {
        let config = SecurityConfig::default();
        let xml = b"<root><child>content</child></root>";
        let cursor = Cursor::new(xml);
        let mut reader = SecureXmlReader::new(cursor, config);

        // Should be able to read valid XML
        let mut buf = Vec::new();
        loop {
            match reader.read_event(&mut buf) {
                Ok(Event::Eof) => break,
                Ok(_) => {
                    buf.clear();
                    continue;
                }
                Err(e) => panic!("Unexpected error: {}", e),
            }
        }
    }

    #[test]
    fn test_rate_limiter() {
        let config = SecurityConfig {
            rate_limiting_enabled: true,
            max_requests_per_minute: 2,
            ..SecurityConfig::default()
        };
        let mut limiter = RateLimiter::new(config);

        // First two requests should succeed
        assert!(limiter.check_rate_limit("user1").is_ok());
        assert!(limiter.check_rate_limit("user1").is_ok());

        // Third request should fail
        assert!(limiter.check_rate_limit("user1").is_err());

        // Different user should work
        assert!(limiter.check_rate_limit("user2").is_ok());
    }

    #[test]
    fn test_url_validation() {
        let config = SecurityConfig::default();
        let validator = InputValidator::new(config);

        // Test valid URL
        assert!(validator.validate_url("https://example.com/path").is_ok());

        // Test private IP
        assert!(validator.validate_url("http://192.168.1.1/").is_err());

        // Test localhost
        assert!(validator.validate_url("http://localhost:8080/").is_err());

        // Test unsafe scheme
        assert!(validator.validate_url("file:///etc/passwd").is_err());
    }

    #[test]
    fn test_output_sanitizer() {
        let config = SecurityConfig::default();
        let sanitizer = OutputSanitizer::new(config);

        // Test safe XML output
        let safe_xml = "<root><child>content</child></root>";
        assert!(sanitizer.sanitize_xml_output(safe_xml).is_ok());

        // Test XML with potential sensitive data
        let sensitive_xml = "<root><password>secret123</password></root>";
        let result = sanitizer.sanitize_xml_output(sensitive_xml);
        assert!(
            result.is_err(),
            "Expected sensitive data to be detected, but got: {:?}",
            result
        );

        // Test malformed XML (should fail XML structure validation after escaping)
        let malformed_xml = "<root><child>content</child><"; // Incomplete tag
        let result = sanitizer.sanitize_xml_output(malformed_xml);
        assert!(
            result.is_err(),
            "Expected malformed XML to be rejected, but got: {:?}",
            result
        );
    }

    #[test]
    fn test_secure_logging() {
        let config = SecurityConfig::default();
        let sanitizer = OutputSanitizer::new(config);

        // Test secure log message creation
        let log_msg = sanitizer.create_secure_log_message("BUILD", true, Some("file.xml"));
        assert!(log_msg.contains("BUILD"));
        assert!(log_msg.contains("SUCCESS"));
        assert!(log_msg.contains("file.xml"));

        // Test sensitive data redaction
        let sensitive_detail = "password=secret123 key=abc";
        let log_msg = sanitizer.create_secure_log_message("LOGIN", false, Some(sensitive_detail));
        assert!(log_msg.contains("[REDACTED]"));
        assert!(!log_msg.contains("secret123"));
        assert!(!log_msg.contains("abc"));
    }

    #[test]
    fn test_security_utils() {
        // Test filename sanitization
        let clean_name = utils::sanitize_filename("../../../etc/passwd");
        assert!(!clean_name.contains(".."));
        assert!(!clean_name.contains("/"));

        // Test secure ID generation
        let id1 = utils::generate_secure_id();
        let id2 = utils::generate_secure_id();
        assert_ne!(id1, id2);
        assert_eq!(id1.len(), 36); // UUID length

        // Test constant-time comparison
        assert!(utils::constant_time_compare("test", "test"));
        assert!(!utils::constant_time_compare("test", "other"));
        assert!(!utils::constant_time_compare("test", "testing"));

        // Test hash for logging
        let hash = utils::hash_for_logging("sensitive_data");
        assert_eq!(hash.len(), 8);
        assert!(!hash.contains("sensitive"));
    }
}