mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
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
//! Automatic encryption configuration and processing
//!
//! This module provides functionality for automatically encrypting sensitive data
//! in requests and responses, including configuration, pattern matching, and processing.

use crate::encryption::algorithms::{EncryptionEngine, EncryptionKey};
use crate::encryption::errors::{EncryptionError, EncryptionResult};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::warn;

/// Configuration for automatic encryption
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoEncryptionConfig {
    /// Whether auto-encryption is enabled
    pub enabled: bool,
    /// Encryption key ID to use for auto-encryption
    pub key_id: String,
    /// Patterns for fields to encrypt automatically
    pub field_patterns: Vec<FieldPattern>,
    /// Headers to encrypt automatically
    pub header_patterns: Vec<String>,
    /// Whether to encrypt environment variables
    pub encrypt_environment_variables: bool,
    /// Whether to encrypt request/response bodies
    pub encrypt_request_bodies: bool,
    /// Whether to encrypt response bodies
    pub encrypt_response_bodies: bool,
    /// Custom encryption rules
    pub custom_rules: Vec<EncryptionRule>,
}

impl Default for AutoEncryptionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            key_id: "default".to_string(),
            field_patterns: Vec::new(),
            header_patterns: Vec::new(),
            encrypt_environment_variables: false,
            encrypt_request_bodies: false,
            encrypt_response_bodies: false,
            custom_rules: Vec::new(),
        }
    }
}

/// Pattern for matching fields to encrypt
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldPattern {
    /// Pattern to match field names (regex)
    pub pattern: String,
    /// Whether this pattern is case-sensitive
    pub case_sensitive: bool,
    /// Encryption algorithm to use
    pub algorithm: Option<crate::encryption::algorithms::EncryptionAlgorithm>,
}

/// Request context for rule evaluation
#[derive(Debug, Clone)]
pub struct RequestContext {
    /// HTTP method (GET, POST, etc.)
    pub method: String,
    /// Request path
    pub path: String,
    /// Request headers
    pub headers: HashMap<String, String>,
    /// Content type from headers
    pub content_type: Option<String>,
}

impl RequestContext {
    /// Create a new request context
    pub fn new(method: String, path: String, headers: HashMap<String, String>) -> Self {
        let content_type =
            headers.get("content-type").or_else(|| headers.get("Content-Type")).cloned();

        Self {
            method,
            path,
            headers,
            content_type,
        }
    }
}

/// Custom encryption rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionRule {
    /// Name of the rule
    pub name: String,
    /// Conditions for applying the rule
    pub conditions: Vec<RuleCondition>,
    /// Actions to take when rule matches
    pub actions: Vec<RuleAction>,
}

/// Condition for encryption rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RuleCondition {
    /// Field name matches pattern
    FieldMatches { pattern: String },
    /// Header exists with value
    HeaderExists {
        name: String,
        value_pattern: Option<String>,
    },
    /// Request path matches pattern
    PathMatches { pattern: String },
    /// HTTP method matches
    MethodMatches { method: String },
    /// Content type matches
    ContentTypeMatches { pattern: String },
}

/// Action for encryption rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RuleAction {
    /// Encrypt the field
    EncryptField { field_path: String },
    /// Encrypt header value
    EncryptHeader { header_name: String },
    /// Skip encryption for this request
    SkipEncryption,
    /// Use specific algorithm
    UseAlgorithm {
        algorithm: crate::encryption::algorithms::EncryptionAlgorithm,
    },
}

/// Result of automatic encryption processing
#[derive(Debug, Clone)]
pub struct AutoEncryptionResult {
    /// Whether any data was encrypted
    pub encrypted: bool,
    /// Number of fields encrypted
    pub fields_encrypted: usize,
    /// Number of headers encrypted
    pub headers_encrypted: usize,
    /// Encryption metadata for decryption
    pub metadata: EncryptionMetadata,
}

/// Metadata for tracking encryption operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionMetadata {
    /// Map of encrypted field paths to encryption info
    pub encrypted_fields: HashMap<String, FieldEncryptionInfo>,
    /// Map of encrypted headers to encryption info
    pub encrypted_headers: HashMap<String, HeaderEncryptionInfo>,
    /// Timestamp of encryption
    pub encrypted_at: chrono::DateTime<chrono::Utc>,
}

/// Information about field encryption
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FieldEncryptionInfo {
    /// Original field path
    pub field_path: String,
    /// Encryption algorithm used
    pub algorithm: crate::encryption::algorithms::EncryptionAlgorithm,
    /// Whether encryption was successful
    pub success: bool,
    /// Error message if encryption failed
    pub error: Option<String>,
}

/// Information about header encryption
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeaderEncryptionInfo {
    /// Header name
    pub header_name: String,
    /// Encryption algorithm used
    pub algorithm: crate::encryption::algorithms::EncryptionAlgorithm,
    /// Whether encryption was successful
    pub success: bool,
    /// Error message if encryption failed
    pub error: Option<String>,
}

/// Automatic encryption processor
#[derive(Debug, Clone)]
pub struct AutoEncryptionProcessor {
    /// Configuration for auto-encryption
    config: AutoEncryptionConfig,
    /// Encryption key for operations
    encryption_key: Option<EncryptionKey>,
    /// Compiled regex patterns
    compiled_patterns: Vec<(Regex, FieldPattern)>,
}

impl AutoEncryptionProcessor {
    /// Create a new auto-encryption processor
    pub fn new(config: AutoEncryptionConfig) -> Self {
        let compiled_patterns = Self::compile_patterns(&config.field_patterns);

        Self {
            config,
            encryption_key: None,
            compiled_patterns,
        }
    }

    /// Set the encryption key
    pub fn set_encryption_key(&mut self, key: EncryptionKey) {
        self.encryption_key = Some(key);
    }

    /// Check if auto-encryption is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled && self.encryption_key.is_some()
    }

    /// Process a request for automatic encryption
    pub fn process_request(
        &self,
        request_data: &mut serde_json::Value,
        request_context: Option<&RequestContext>,
    ) -> EncryptionResult<AutoEncryptionResult> {
        if !self.is_enabled() {
            return Ok(AutoEncryptionResult {
                encrypted: false,
                fields_encrypted: 0,
                headers_encrypted: 0,
                metadata: EncryptionMetadata {
                    encrypted_fields: HashMap::new(),
                    encrypted_headers: HashMap::new(),
                    encrypted_at: chrono::Utc::now(),
                },
            });
        }

        let mut fields_encrypted = 0;
        let mut encrypted_fields = HashMap::new();

        // Encrypt fields in request body
        if self.config.encrypt_request_bodies {
            fields_encrypted += self.encrypt_fields_in_value(
                request_data,
                "",
                &mut encrypted_fields,
                request_context,
            )?;
        }

        Ok(AutoEncryptionResult {
            encrypted: fields_encrypted > 0,
            fields_encrypted,
            headers_encrypted: 0, // Headers handled separately
            metadata: EncryptionMetadata {
                encrypted_fields,
                encrypted_headers: HashMap::new(),
                encrypted_at: chrono::Utc::now(),
            },
        })
    }

    /// Process a response for automatic encryption
    pub fn process_response(
        &self,
        response_data: &mut serde_json::Value,
        request_context: Option<&RequestContext>,
    ) -> EncryptionResult<AutoEncryptionResult> {
        if !self.is_enabled() || !self.config.encrypt_response_bodies {
            return Ok(AutoEncryptionResult {
                encrypted: false,
                fields_encrypted: 0,
                headers_encrypted: 0,
                metadata: EncryptionMetadata {
                    encrypted_fields: HashMap::new(),
                    encrypted_headers: HashMap::new(),
                    encrypted_at: chrono::Utc::now(),
                },
            });
        }

        let mut fields_encrypted = 0;
        let mut encrypted_fields = HashMap::new();

        // Encrypt fields in response body
        fields_encrypted += self.encrypt_fields_in_value(
            response_data,
            "",
            &mut encrypted_fields,
            request_context,
        )?;

        Ok(AutoEncryptionResult {
            encrypted: fields_encrypted > 0,
            fields_encrypted,
            headers_encrypted: 0,
            metadata: EncryptionMetadata {
                encrypted_fields,
                encrypted_headers: HashMap::new(),
                encrypted_at: chrono::Utc::now(),
            },
        })
    }

    /// Encrypt fields in a JSON value based on patterns
    fn encrypt_fields_in_value(
        &self,
        value: &mut serde_json::Value,
        current_path: &str,
        encrypted_fields: &mut HashMap<String, FieldEncryptionInfo>,
        request_context: Option<&RequestContext>,
    ) -> EncryptionResult<usize> {
        let mut count = 0;

        match value {
            serde_json::Value::Object(map) => {
                let mut fields_to_encrypt = Vec::new();

                // Find fields that match patterns
                for (key, _) in map.iter() {
                    let field_path = if current_path.is_empty() {
                        key.clone()
                    } else {
                        format!("{}.{}", current_path, key)
                    };

                    if self.should_encrypt_field(key, &field_path, request_context) {
                        fields_to_encrypt.push(key.clone());
                    }
                }

                // Encrypt matching fields
                for field_name in fields_to_encrypt {
                    let field_path = if current_path.is_empty() {
                        field_name.clone()
                    } else {
                        format!("{}.{}", current_path, field_name)
                    };

                    if let Some(field_value) = map.get(&field_name) {
                        if let Some(string_value) = field_value.as_str() {
                            if let Some(encryption_key) = &self.encryption_key {
                                match EncryptionEngine::encrypt_string(encryption_key, string_value)
                                {
                                    Ok(encrypted) => {
                                        let encrypted_json = serde_json::to_value(&encrypted)
                                            .map_err(|e| {
                                                EncryptionError::serialization_error(e.to_string())
                                            })?;
                                        map.insert(field_name.clone(), encrypted_json);

                                        encrypted_fields.insert(
                                            field_path.clone(),
                                            FieldEncryptionInfo {
                                                field_path: field_path.clone(),
                                                algorithm: crate::encryption::algorithms::EncryptionAlgorithm::Aes256Gcm,
                                                success: true,
                                                error: None,
                                            },
                                        );
                                        count += 1;
                                    }
                                    Err(e) => {
                                        encrypted_fields.insert(
                                            field_path.clone(),
                                            FieldEncryptionInfo {
                                                field_path: field_path.clone(),
                                                algorithm: crate::encryption::algorithms::EncryptionAlgorithm::Aes256Gcm,
                                                success: false,
                                                error: Some(e.to_string()),
                                            },
                                        );
                                    }
                                }
                            }
                        }
                    }
                }

                // Recursively process nested objects
                for (_, v) in map.iter_mut() {
                    let nested_path = if current_path.is_empty() {
                        String::new()
                    } else {
                        current_path.to_string()
                    };
                    count += self.encrypt_fields_in_value(
                        v,
                        &nested_path,
                        encrypted_fields,
                        request_context,
                    )?;
                }
            }
            serde_json::Value::Array(arr) => {
                for (index, item) in arr.iter_mut().enumerate() {
                    let nested_path = if current_path.is_empty() {
                        format!("[{}]", index)
                    } else {
                        format!("{}.[{}]", current_path, index)
                    };
                    count += self.encrypt_fields_in_value(
                        item,
                        &nested_path,
                        encrypted_fields,
                        request_context,
                    )?;
                }
            }
            _ => {}
        }

        Ok(count)
    }

    /// Check if a field should be encrypted
    fn should_encrypt_field(
        &self,
        field_name: &str,
        field_path: &str,
        request_context: Option<&RequestContext>,
    ) -> bool {
        // Check custom rules first
        for rule in &self.config.custom_rules {
            if self.rule_matches(rule, field_name, field_path, request_context) {
                for action in &rule.actions {
                    match action {
                        RuleAction::EncryptField { .. } => return true,
                        RuleAction::SkipEncryption => return false,
                        _ => {}
                    }
                }
            }
        }

        // Check field patterns
        for (regex, pattern) in &self.compiled_patterns {
            let text_to_match = if pattern.case_sensitive {
                field_path.to_string()
            } else {
                field_path.to_lowercase()
            };

            if regex.is_match(&text_to_match) {
                return true;
            }
        }

        false
    }

    /// Check if a rule matches the current context
    fn rule_matches(
        &self,
        rule: &EncryptionRule,
        field_name: &str,
        field_path: &str,
        request_context: Option<&RequestContext>,
    ) -> bool {
        for condition in &rule.conditions {
            match condition {
                RuleCondition::FieldMatches { pattern } => {
                    if !Self::matches_pattern(field_name, pattern)
                        && !Self::matches_pattern(field_path, pattern)
                    {
                        return false;
                    }
                }
                RuleCondition::HeaderExists {
                    name,
                    value_pattern,
                } => {
                    if let Some(ctx) = request_context {
                        let header_exists = ctx.headers.contains_key(name);
                        if !header_exists {
                            return false;
                        }
                        if let Some(pattern) = value_pattern {
                            if let Some(header_value) = ctx.headers.get(name) {
                                if !Self::matches_pattern(header_value, pattern) {
                                    return false;
                                }
                            } else {
                                return false;
                            }
                        }
                    } else {
                        // If no request context, skip this condition
                        continue;
                    }
                }
                RuleCondition::PathMatches { pattern } => {
                    if let Some(ctx) = request_context {
                        if !Self::matches_pattern(&ctx.path, pattern) {
                            return false;
                        }
                    } else {
                        // If no request context, skip this condition
                        continue;
                    }
                }
                RuleCondition::MethodMatches { method } => {
                    if let Some(ctx) = request_context {
                        if !ctx.method.eq_ignore_ascii_case(method) {
                            return false;
                        }
                    } else {
                        // If no request context, skip this condition
                        continue;
                    }
                }
                RuleCondition::ContentTypeMatches { pattern } => {
                    if let Some(ctx) = request_context {
                        if let Some(content_type) = &ctx.content_type {
                            if !Self::matches_pattern(content_type, pattern) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    } else {
                        // If no request context available, rule cannot match
                        return false;
                    }
                }
            }
        }
        true
    }

    /// Helper function to check if text matches a pattern (supports regex)
    fn matches_pattern(text: &str, pattern: &str) -> bool {
        match Regex::new(pattern) {
            Ok(regex) => regex.is_match(text),
            Err(_) => {
                // If pattern is invalid regex, treat as literal string match
                text.contains(pattern)
            }
        }
    }

    /// Compile regex patterns from field patterns
    fn compile_patterns(field_patterns: &[FieldPattern]) -> Vec<(Regex, FieldPattern)> {
        let mut compiled = Vec::new();

        for pattern in field_patterns {
            match Regex::new(&pattern.pattern) {
                Ok(regex) => {
                    compiled.push((regex, pattern.clone()));
                }
                Err(e) => {
                    // Log error but continue with other patterns
                    warn!("Failed to compile regex pattern '{}': {}", pattern.pattern, e);
                }
            }
        }

        compiled
    }

    /// Get default field patterns for common sensitive data
    pub fn get_default_field_patterns() -> Vec<FieldPattern> {
        vec![
            FieldPattern {
                pattern: r"(?i)password".to_string(),
                case_sensitive: false,
                algorithm: None,
            },
            FieldPattern {
                pattern: r"(?i)secret".to_string(),
                case_sensitive: false,
                algorithm: None,
            },
            FieldPattern {
                pattern: r"(?i)token".to_string(),
                case_sensitive: false,
                algorithm: None,
            },
            FieldPattern {
                pattern: r"(?i)key".to_string(),
                case_sensitive: false,
                algorithm: None,
            },
            FieldPattern {
                pattern: r"(?i)auth".to_string(),
                case_sensitive: false,
                algorithm: None,
            },
        ]
    }

    /// Get default header patterns for sensitive headers
    pub fn get_default_header_patterns() -> Vec<String> {
        vec![
            "authorization".to_string(),
            "x-api-key".to_string(),
            "x-auth-token".to_string(),
            "cookie".to_string(),
        ]
    }

    /// Validate the auto-encryption configuration
    pub fn validate_config(&self) -> EncryptionResult<()> {
        if self.config.enabled && self.encryption_key.is_none() {
            return Err(EncryptionError::auto_encryption_config_error(
                "Auto-encryption enabled but no encryption key provided",
            ));
        }

        for pattern in &self.config.field_patterns {
            if pattern.pattern.is_empty() {
                return Err(EncryptionError::auto_encryption_config_error("Empty field pattern"));
            }

            if let Err(e) = Regex::new(&pattern.pattern) {
                return Err(EncryptionError::auto_encryption_config_error(format!(
                    "Invalid regex pattern '{}': {}",
                    pattern.pattern, e
                )));
            }
        }

        for rule in &self.config.custom_rules {
            if rule.name.is_empty() {
                return Err(EncryptionError::auto_encryption_config_error(
                    "Encryption rule name cannot be empty",
                ));
            }

            if rule.conditions.is_empty() {
                return Err(EncryptionError::auto_encryption_config_error(
                    "Encryption rule must have at least one condition",
                ));
            }

            if rule.actions.is_empty() {
                return Err(EncryptionError::auto_encryption_config_error(
                    "Encryption rule must have at least one action",
                ));
            }
        }

        Ok(())
    }

    /// Create a default configuration
    pub fn default_config() -> AutoEncryptionConfig {
        AutoEncryptionConfig {
            enabled: false,
            key_id: "auto_encryption_key".to_string(),
            field_patterns: Self::get_default_field_patterns(),
            header_patterns: Self::get_default_header_patterns(),
            encrypt_environment_variables: true,
            encrypt_request_bodies: true,
            encrypt_response_bodies: false,
            custom_rules: Vec::new(),
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encryption::algorithms::EncryptionAlgorithm;

    #[test]
    fn test_auto_encryption_config_default() {
        let config = AutoEncryptionConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.key_id, "default");
        assert!(config.field_patterns.is_empty());
        assert!(config.header_patterns.is_empty());
        assert!(!config.encrypt_environment_variables);
        assert!(!config.encrypt_request_bodies);
        assert!(!config.encrypt_response_bodies);
        assert!(config.custom_rules.is_empty());
    }

    #[test]
    fn test_auto_encryption_config_creation() {
        let config = AutoEncryptionConfig {
            enabled: true,
            key_id: "test-key".to_string(),
            field_patterns: vec![],
            header_patterns: vec!["Authorization".to_string()],
            encrypt_environment_variables: true,
            encrypt_request_bodies: true,
            encrypt_response_bodies: true,
            custom_rules: vec![],
        };

        assert!(config.enabled);
        assert_eq!(config.key_id, "test-key");
        assert_eq!(config.header_patterns.len(), 1);
    }

    #[test]
    fn test_auto_encryption_config_serialization() {
        let config = AutoEncryptionConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("enabled"));
        assert!(json.contains("default"));
    }

    #[test]
    fn test_field_pattern_creation() {
        let pattern = FieldPattern {
            pattern: "password".to_string(),
            case_sensitive: false,
            algorithm: Some(EncryptionAlgorithm::Aes256Gcm),
        };

        assert_eq!(pattern.pattern, "password");
        assert!(!pattern.case_sensitive);
        assert!(pattern.algorithm.is_some());
    }

    #[test]
    fn test_field_pattern_serialization() {
        let pattern = FieldPattern {
            pattern: ".*secret.*".to_string(),
            case_sensitive: true,
            algorithm: None,
        };

        let json = serde_json::to_string(&pattern).unwrap();
        assert!(json.contains(".*secret.*"));
    }

    #[test]
    fn test_request_context_new() {
        let mut headers = HashMap::new();
        headers.insert("Content-Type".to_string(), "application/json".to_string());
        let context =
            RequestContext::new("POST".to_string(), "/api/test".to_string(), headers.clone());

        assert_eq!(context.method, "POST");
        assert_eq!(context.path, "/api/test");
        assert_eq!(context.content_type, Some("application/json".to_string()));
    }

    #[test]
    fn test_request_context_content_type_lowercase() {
        let mut headers = HashMap::new();
        headers.insert("content-type".to_string(), "text/xml".to_string());
        let context = RequestContext::new("GET".to_string(), "/test".to_string(), headers);

        assert_eq!(context.content_type, Some("text/xml".to_string()));
    }

    #[test]
    fn test_request_context_no_content_type() {
        let headers = HashMap::new();
        let context = RequestContext::new("GET".to_string(), "/test".to_string(), headers);

        assert_eq!(context.content_type, None);
    }

    #[test]
    fn test_encryption_rule_creation() {
        let rule = EncryptionRule {
            name: "encrypt-passwords".to_string(),
            conditions: vec![RuleCondition::FieldMatches {
                pattern: "password".to_string(),
            }],
            actions: vec![RuleAction::EncryptField {
                field_path: "password".to_string(),
            }],
        };

        assert_eq!(rule.name, "encrypt-passwords");
        assert_eq!(rule.conditions.len(), 1);
        assert_eq!(rule.actions.len(), 1);
    }

    #[test]
    fn test_encryption_rule_serialization() {
        let rule = EncryptionRule {
            name: "test-rule".to_string(),
            conditions: vec![],
            actions: vec![],
        };

        let json = serde_json::to_string(&rule).unwrap();
        assert!(json.contains("test-rule"));
    }

    #[test]
    fn test_rule_condition_variants() {
        let field_match = RuleCondition::FieldMatches {
            pattern: "password".to_string(),
        };
        let header_exists = RuleCondition::HeaderExists {
            name: "Authorization".to_string(),
            value_pattern: None,
        };
        let path_matches = RuleCondition::PathMatches {
            pattern: "/api/.*".to_string(),
        };
        let method_matches = RuleCondition::MethodMatches {
            method: "POST".to_string(),
        };
        let content_type_matches = RuleCondition::ContentTypeMatches {
            pattern: "application/json".to_string(),
        };

        // Just verify they can be created
        match field_match {
            RuleCondition::FieldMatches { pattern } => assert_eq!(pattern, "password"),
            _ => panic!("Wrong variant"),
        }

        match header_exists {
            RuleCondition::HeaderExists {
                name,
                value_pattern,
            } => {
                assert_eq!(name, "Authorization");
                assert!(value_pattern.is_none());
            }
            _ => panic!("Wrong variant"),
        }

        match path_matches {
            RuleCondition::PathMatches { pattern } => assert_eq!(pattern, "/api/.*"),
            _ => panic!("Wrong variant"),
        }

        match method_matches {
            RuleCondition::MethodMatches { method } => assert_eq!(method, "POST"),
            _ => panic!("Wrong variant"),
        }

        match content_type_matches {
            RuleCondition::ContentTypeMatches { pattern } => {
                assert_eq!(pattern, "application/json")
            }
            _ => panic!("Wrong variant"),
        }
    }

    #[test]
    fn test_rule_action_variants() {
        let encrypt_field = RuleAction::EncryptField {
            field_path: "password".to_string(),
        };
        let encrypt_header = RuleAction::EncryptHeader {
            header_name: "Authorization".to_string(),
        };
        let skip = RuleAction::SkipEncryption;
        let use_algorithm = RuleAction::UseAlgorithm {
            algorithm: EncryptionAlgorithm::Aes256Gcm,
        };

        // Just verify they can be created
        match encrypt_field {
            RuleAction::EncryptField { field_path } => assert_eq!(field_path, "password"),
            _ => panic!("Wrong variant"),
        }

        match encrypt_header {
            RuleAction::EncryptHeader { header_name } => assert_eq!(header_name, "Authorization"),
            _ => panic!("Wrong variant"),
        }

        match skip {
            RuleAction::SkipEncryption => {}
            _ => panic!("Wrong variant"),
        }

        match use_algorithm {
            RuleAction::UseAlgorithm { algorithm } => {
                assert_eq!(algorithm, EncryptionAlgorithm::Aes256Gcm)
            }
            _ => panic!("Wrong variant"),
        }
    }

    #[test]
    fn test_auto_encryption_result_creation() {
        let result = AutoEncryptionResult {
            encrypted: true,
            fields_encrypted: 5,
            headers_encrypted: 2,
            metadata: EncryptionMetadata {
                encrypted_fields: HashMap::new(),
                encrypted_headers: HashMap::new(),
                encrypted_at: chrono::Utc::now(),
            },
        };

        assert!(result.encrypted);
        assert_eq!(result.fields_encrypted, 5);
        assert_eq!(result.headers_encrypted, 2);
    }

    #[test]
    fn test_encryption_metadata_creation() {
        let metadata = EncryptionMetadata {
            encrypted_fields: HashMap::new(),
            encrypted_headers: HashMap::new(),
            encrypted_at: chrono::Utc::now(),
        };

        assert!(metadata.encrypted_fields.is_empty());
        assert!(metadata.encrypted_headers.is_empty());
    }

    #[test]
    fn test_encryption_metadata_serialization() {
        let metadata = EncryptionMetadata {
            encrypted_fields: HashMap::new(),
            encrypted_headers: HashMap::new(),
            encrypted_at: chrono::Utc::now(),
        };

        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains("encrypted_fields"));
    }

    #[test]
    fn test_field_encryption_info_creation() {
        let info = FieldEncryptionInfo {
            field_path: "user.password".to_string(),
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            success: true,
            error: None,
        };

        assert_eq!(info.field_path, "user.password");
        assert!(info.success);
        assert!(info.error.is_none());
    }

    #[test]
    fn test_field_encryption_info_serialization() {
        let info = FieldEncryptionInfo {
            field_path: "test".to_string(),
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            success: false,
            error: Some("Encryption failed".to_string()),
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("test"));
        assert!(json.contains("Encryption failed"));
    }

    #[test]
    fn test_header_encryption_info_creation() {
        let info = HeaderEncryptionInfo {
            header_name: "Authorization".to_string(),
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            success: true,
            error: None,
        };

        assert_eq!(info.header_name, "Authorization");
        assert!(info.success);
    }

    #[test]
    fn test_header_encryption_info_serialization() {
        let info = HeaderEncryptionInfo {
            header_name: "X-API-Key".to_string(),
            algorithm: EncryptionAlgorithm::Aes256Gcm,
            success: true,
            error: None,
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("X-API-Key"));
    }

    #[test]
    fn test_auto_encryption_processor_new() {
        let config = AutoEncryptionConfig::default();
        let processor = AutoEncryptionProcessor::new(config.clone());

        assert_eq!(processor.config.enabled, config.enabled);
        assert!(processor.encryption_key.is_none());
    }

    #[test]
    fn test_auto_encryption_processor_default() {
        let processor = AutoEncryptionProcessor::default();
        assert!(!processor.config.enabled);
        assert!(processor.encryption_key.is_none());
    }

    #[test]
    fn test_auto_encryption_processor_set_encryption_key() {
        let config = AutoEncryptionConfig::default();
        let mut processor = AutoEncryptionProcessor::new(config);
        let key = EncryptionKey::generate(EncryptionAlgorithm::Aes256Gcm).unwrap();

        processor.set_encryption_key(key.clone());
        assert!(processor.encryption_key.is_some());
    }

    #[test]
    fn test_auto_encryption_processor_is_enabled() {
        let config = AutoEncryptionConfig {
            enabled: true,
            ..Default::default()
        };
        let mut processor = AutoEncryptionProcessor::new(config);

        // Should be false without key
        assert!(!processor.is_enabled());

        // Should be true with key
        let key = EncryptionKey::generate(EncryptionAlgorithm::Aes256Gcm).unwrap();
        processor.set_encryption_key(key);
        assert!(processor.is_enabled());
    }

    #[test]
    fn test_auto_encryption_processor_is_enabled_config_disabled() {
        let config = AutoEncryptionConfig::default();
        let mut processor = AutoEncryptionProcessor::new(config);
        let key = EncryptionKey::generate(EncryptionAlgorithm::Aes256Gcm).unwrap();

        processor.set_encryption_key(key);
        // Should still be false because config.enabled is false
        assert!(!processor.is_enabled());
    }
}