sz-orm-masking 5.1.0

Data masking: Unicode-safe masking for phone/email/IdCard/bankCard/name/address with custom prefix-suffix rules
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
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
//! # SZ-ORM Masking — Data Masking
//!
//! Provides masking for sensitive fields such as phone number, email, ID card, bank card, name, address, and supports custom
//! prefix/suffix retention rules. Unicode safe, with reasonable fallback for short input, does not panic.
//!
//! ## Main Types
//!
//! - [`MaskingRule`] — Masking rule enum
//! - [`DataMasker`] — Masking executor

use serde::{Deserialize, Serialize};

pub mod audit;
pub mod config;
pub mod maskers;
pub mod strategy;

// 重导出新模块的主要类型
pub use audit::{
    rule_name, FieldReport, MaskingAuditEntry as DetailedAuditEntry,
    MaskingAuditLog as DetailedAuditLog, MaskingReport, RuleReport,
};
pub use config::{FieldPattern, MaskingConfigManager, MaskingProfile, SensitiveFieldDetector};
pub use maskers::{wildcard_match, HashAlgorithm, HashMasker, PartialDisplayMasker, PatternMasker};
pub use strategy::{
    FieldMaskingRule, MaskingCondition, MaskingPipeline, MaskingStrategyEngine, MaskingValidator,
    PipelineStage,
};

/// Masking rules supported by [`DataMasker`].
///
/// `Custom(String)` expects a configuration of the form `"prefix,suffix"`
/// where `prefix` and `suffix` are the number of characters (Unicode scalar
/// values) to retain from the start and end of the input. Example:
/// `Custom("3,2".to_string())` keeps the first 3 and last 2 characters and
/// replaces everything in between with `*`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MaskingRule {
    Phone,
    Email,
    IdCard,
    BankCard,
    Name,
    Address,
    Ip,
    Imei,
    Plate,
    Custom(String),
    Password,
    ApiKey,
}

pub struct DataMasker;

impl DataMasker {
    /// Applies the given masking `rule` to `value`. The implementation is
    /// Unicode-safe (works on `char` boundaries rather than byte slices) and
    /// never panics: inputs shorter than the rule's required visible prefix
    /// return a sensible fallback (the original value, or `"***"` when even
    /// the original cannot be safely revealed).
    pub fn apply(rule: &MaskingRule, value: &str) -> String {
        match rule {
            MaskingRule::Phone => mask_prefix_suffix(value, 3, 4),
            MaskingRule::Email => mask_email(value),
            MaskingRule::IdCard => mask_prefix_suffix(value, 4, 4),
            MaskingRule::BankCard => mask_prefix_suffix(value, 4, 4),
            MaskingRule::Name => mask_name(value),
            MaskingRule::Address => mask_address(value, 6),
            MaskingRule::Ip => mask_ip(value),
            MaskingRule::Imei => mask_imei(value),
            MaskingRule::Plate => mask_plate(value),
            MaskingRule::Custom(spec) => mask_custom(value, spec),
            MaskingRule::Password => "***".to_string(),
            MaskingRule::ApiKey => mask_api_key(value),
        }
    }

    /// Applies a sequence of rules to the same value, in order.
    ///
    /// Useful for stacked masking (e.g. first mask the whole phone, then
    /// apply a custom prefix/suffix rule). Each rule is applied to the
    /// output of the previous one.
    pub fn apply_many(rules: &[MaskingRule], value: &str) -> String {
        let mut out = value.to_string();
        for rule in rules {
            out = Self::apply(rule, &out);
        }
        out
    }

    /// Masks specific fields of a `HashMap<String, String>` in place,
    /// returning a new map with only the masked fields replaced.
    ///
    /// Fields whose rule is `None` are copied through unchanged. Fields not
    /// present in `rules` are also copied through, so callers can pass a
    /// partial rule set without losing data.
    pub fn mask_map(
        rules: &std::collections::HashMap<String, MaskingRule>,
        data: &std::collections::HashMap<String, String>,
    ) -> std::collections::HashMap<String, String> {
        data.iter()
            .map(|(k, v)| match rules.get(k) {
                Some(rule) => (k.clone(), Self::apply(rule, v)),
                None => (k.clone(), v.clone()),
            })
            .collect()
    }

    /// Masks a JSON object string by field name.
    ///
    /// `rules` maps field names to masking rules. Only top-level fields are
    /// matched (nested objects are left untouched); non-JSON input is
    /// returned unchanged so callers can rely on this being lossless for
    /// malformed payloads.
    pub fn mask_json(rules: &std::collections::HashMap<String, MaskingRule>, json: &str) -> String {
        let Ok(mut value) = serde_json::from_str::<serde_json::Value>(json) else {
            return json.to_string();
        };
        let Some(obj) = value.as_object_mut() else {
            return json.to_string();
        };
        for (field, rule) in rules {
            if let Some(serde_json::Value::String(s)) = obj.get_mut(field) {
                *s = Self::apply(rule, s);
            }
        }
        serde_json::to_string(&value).unwrap_or_else(|_| json.to_string())
    }
}

/// Masks the middle of the input, keeping the first `prefix` and last
/// `suffix` characters visible. Returns `"***"` when the input is too short
/// to reveal `prefix + suffix` characters (or when `prefix`/`suffix` are
/// zero, the rule degrades gracefully).
fn mask_prefix_suffix(value: &str, prefix: usize, suffix: usize) -> String {
    let chars: Vec<char> = value.chars().collect();
    let len = chars.len();
    if len == 0 {
        return "***".to_string();
    }
    // Need at least one extra char beyond prefix+suffix to mask; otherwise
    // the value has nothing to hide and we return the original.
    if len <= prefix + suffix {
        // Too short to safely mask without revealing the structure; return "***".
        return "***".to_string();
    }
    let hidden = len - prefix - suffix;
    let mut out = String::with_capacity(len);
    for &c in &chars[..prefix] {
        out.push(c);
    }
    for _ in 0..hidden {
        out.push('*');
    }
    for &c in &chars[len - suffix..] {
        out.push(c);
    }
    out
}

/// Masks an API key by keeping the first 4 and last 4 characters visible
/// and replacing everything in between with `*`. Returns `"***"` for inputs
/// too short to safely mask (≤ 8 characters).
fn mask_api_key(value: &str) -> String {
    mask_prefix_suffix(value, 4, 4)
}

fn mask_email(value: &str) -> String {
    let parts: Vec<&str> = value.splitn(2, '@').collect();
    if parts.len() != 2 {
        // Not a valid email; do not attempt to mask structurally.
        return "***".to_string();
    }
    let local = parts[0];
    let domain = parts[1];
    let local_chars: Vec<char> = local.chars().collect();
    if local_chars.is_empty() {
        return "***".to_string();
    }
    let mut out = String::with_capacity(value.len());
    out.push(local_chars[0]);
    // Hide the rest of the local part with one `*` per hidden character.
    for _ in 1..local_chars.len() {
        out.push('*');
    }
    out.push('@');
    out.push_str(domain);
    out
}

fn mask_name(value: &str) -> String {
    let chars: Vec<char> = value.chars().collect();
    if chars.is_empty() {
        return String::new();
    }
    let mut out = String::with_capacity(chars.len());
    out.push(chars[0]);
    for _ in 1..chars.len() {
        out.push('*');
    }
    out
}

fn mask_address(value: &str, keep: usize) -> String {
    let chars: Vec<char> = value.chars().collect();
    if chars.is_empty() {
        return String::new();
    }
    if chars.len() <= keep {
        // Nothing meaningful to mask: hide everything to avoid leaking
        // the structure of very short addresses.
        return "*".repeat(chars.len());
    }
    let hidden = chars.len() - keep;
    let mut out = String::with_capacity(chars.len());
    for &c in &chars[..keep] {
        out.push(c);
    }
    for _ in 0..hidden {
        out.push('*');
    }
    out
}

/// IP address masking: 192.168.1.100 → 192.168.1.*
///
/// IPv4: Hide last segment (content after last `.`).
/// IPv6: Hide last `:` group (content after last colon).
/// Returns as-is if unrecognized. `.` and `:` are ASCII single bytes, `rfind` returns byte position
/// that is always a character boundary, slice is safe.
fn mask_ip(ip: &str) -> String {
    if let Some(last_dot) = ip.rfind('.') {
        format!("{}.*", &ip[..last_dot])
    } else if let Some(last_colon) = ip.rfind(':') {
        format!("{}:*", &ip[..last_colon])
    } else {
        ip.to_string()
    }
}

/// IMEI masking: Keep first 6 digits and last 1 digit, replace middle with `****`
///
/// IMEI is 15 digits (3GPP TS 23.003), processed by Unicode characters for safety.
fn mask_imei(imei: &str) -> String {
    let chars: Vec<char> = imei.chars().collect();
    if chars.len() < 7 {
        return "*".repeat(chars.len());
    }
    let mut out = String::with_capacity(chars.len() + 4);
    for &c in &chars[..6] {
        out.push(c);
    }
    out.push_str("****");
    out.push(chars[chars.len() - 1]);
    out
}

/// License plate masking: 京A12345 → 京A12**45
///
/// Keep first (len-2) characters and last 2 characters, replace middle with `**`.
/// Processed by Unicode characters, supports Chinese license plates (e.g. "京A12345").
fn mask_plate(plate: &str) -> String {
    let chars: Vec<char> = plate.chars().collect();
    let len = chars.len();
    if len < 4 {
        return "*".repeat(len);
    }
    let mut out = String::with_capacity(len + 2);
    for &c in &chars[..len - 2] {
        out.push(c);
    }
    out.push_str("**");
    for &c in &chars[len - 2..] {
        out.push(c);
    }
    out
}

fn mask_custom(value: &str, spec: &str) -> String {
    let (prefix, suffix) = match parse_custom_spec(spec) {
        Some(parsed) => parsed,
        None => return "***".to_string(),
    };
    mask_prefix_suffix(value, prefix, suffix)
}

/// Parses a `"prefix,suffix"` spec into `(prefix, suffix)`. Returns `None`
/// on malformed input or negative/overflowing values.
fn parse_custom_spec(spec: &str) -> Option<(usize, usize)> {
    let parts: Vec<&str> = spec.split(',').collect();
    if parts.len() != 2 {
        return None;
    }
    let prefix: usize = parts[0].trim().parse().ok()?;
    let suffix: usize = parts[1].trim().parse().ok()?;
    Some((prefix, suffix))
}

// ---------------------------------------------------------------------------
// 脱敏策略与审计工具
// ---------------------------------------------------------------------------

/// Masking strategy: define masking rules for multiple fields, applied in batch
#[derive(Debug, Clone, Default)]
pub struct MaskingPolicy {
    rules: std::collections::HashMap<String, MaskingRule>,
}

impl MaskingPolicy {
    /// Create empty strategy
    pub fn new() -> Self {
        Self::default()
    }

    /// Add field masking rule (chainable)
    pub fn add_rule(&mut self, field: &str, rule: MaskingRule) -> &mut Self {
        self.rules.insert(field.to_string(), rule);
        self
    }

    /// Get masking rule for a field
    pub fn get_rule(&self, field: &str) -> Option<&MaskingRule> {
        self.rules.get(field)
    }

    /// Remove masking rule for a field
    pub fn remove_rule(&mut self, field: &str) -> Option<MaskingRule> {
        self.rules.remove(field)
    }

    /// Number of registered fields
    pub fn field_count(&self) -> usize {
        self.rules.len()
    }

    /// Get all rule references
    pub fn rules(&self) -> &std::collections::HashMap<String, MaskingRule> {
        &self.rules
    }

    /// Apply masking to HashMap data
    pub fn apply_to_map(
        &self,
        data: &std::collections::HashMap<String, String>,
    ) -> std::collections::HashMap<String, String> {
        DataMasker::mask_map(&self.rules, data)
    }

    /// Apply masking to JSON string
    pub fn apply_to_json(&self, json: &str) -> String {
        DataMasker::mask_json(&self.rules, json)
    }
}

/// Masking audit entry: records a single masking operation
#[derive(Debug, Clone)]
pub struct MaskAuditEntry {
    field: String,
    original_len: usize,
    masked_len: usize,
}

impl MaskAuditEntry {
    /// Field name
    pub fn field(&self) -> &str {
        &self.field
    }

    /// Original value length
    pub fn original_len(&self) -> usize {
        self.original_len
    }

    /// Masked length
    pub fn masked_len(&self) -> usize {
        self.masked_len
    }

    /// Whether truncated (masked is shorter than original)
    pub fn was_truncated(&self) -> bool {
        self.masked_len < self.original_len
    }
}

/// Masking audit log: records all masking operations
#[derive(Debug, Clone, Default)]
pub struct MaskAuditLog {
    entries: Vec<MaskAuditEntry>,
}

impl MaskAuditLog {
    /// Create empty audit log
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a masking operation
    pub fn log(&mut self, field: &str, original_len: usize, masked_len: usize) {
        self.entries.push(MaskAuditEntry {
            field: field.to_string(),
            original_len,
            masked_len,
        });
    }

    /// All audit entries
    pub fn entries(&self) -> &[MaskAuditEntry] {
        &self.entries
    }

    /// Entry count
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Total masked characters (sum of original_len - masked_len)
    pub fn total_masked_chars(&self) -> usize {
        self.entries
            .iter()
            .map(|e| e.original_len.saturating_sub(e.masked_len))
            .sum()
    }

    /// Clear log
    pub fn clear(&mut self) {
        self.entries.clear();
    }
}

/// Masking config: custom mask character, minimum mask length, fallback value
#[derive(Debug, Clone)]
pub struct MaskingConfig {
    mask_char: char,
    min_mask_length: usize,
    fallback: String,
}

impl Default for MaskingConfig {
    fn default() -> Self {
        Self {
            mask_char: '*',
            min_mask_length: 3,
            fallback: "***".to_string(),
        }
    }
}

impl MaskingConfig {
    /// Create default config
    pub fn new() -> Self {
        Self::default()
    }

    /// Mask character
    pub fn mask_char(&self) -> char {
        self.mask_char
    }

    /// Set mask character (chainable)
    pub fn with_mask_char(mut self, c: char) -> Self {
        self.mask_char = c;
        self
    }

    /// Minimum mask length
    pub fn min_mask_length(&self) -> usize {
        self.min_mask_length
    }

    /// Set minimum mask length (chainable)
    pub fn with_min_mask_length(mut self, min: usize) -> Self {
        self.min_mask_length = min;
        self
    }

    /// Fallback value
    pub fn fallback_value(&self) -> &str {
        &self.fallback
    }

    /// Set fallback value (chainable)
    pub fn with_fallback_value(mut self, value: &str) -> Self {
        self.fallback = value.to_string();
        self
    }
}

/// Masking statistics: tracks masking operation count per field
#[derive(Debug, Clone, Default)]
pub struct MaskingStats {
    counts: std::collections::HashMap<String, u64>,
}

impl MaskingStats {
    /// Create empty statistics
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a masking operation
    pub fn record(&mut self, field: &str) {
        *self.counts.entry(field.to_string()).or_insert(0) += 1;
    }

    /// Total operation count
    pub fn total_operations(&self) -> u64 {
        self.counts.values().sum()
    }

    /// Operation count for a field
    pub fn field_operations(&self, field: &str) -> u64 {
        self.counts.get(field).copied().unwrap_or(0)
    }

    /// Field with most operations
    pub fn most_masked_field(&self) -> Option<&str> {
        self.counts
            .iter()
            .max_by_key(|(_, v)| *v)
            .map(|(k, _)| k.as_str())
    }
}

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

    // ----- Phone -----
    #[test]
    fn test_phone_standard() {
        let result = DataMasker::apply(&MaskingRule::Phone, "13812345678");
        assert_eq!(result, "138****5678");
    }

    #[test]
    fn test_phone_too_short() {
        // Less than 3+4 chars -> cannot safely reveal structure -> "***"
        assert_eq!(DataMasker::apply(&MaskingRule::Phone, "12345"), "***");
        assert_eq!(DataMasker::apply(&MaskingRule::Phone, "1234567"), "***");
    }

    #[test]
    fn test_phone_boundary_seven_plus_one() {
        // 8 chars: prefix=3, suffix=4, hidden=1
        assert_eq!(
            DataMasker::apply(&MaskingRule::Phone, "12345678"),
            "123*5678"
        );
    }

    #[test]
    fn test_phone_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Phone, ""), "***");
    }

    // ----- Email -----
    #[test]
    fn test_email_standard() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Email, "test@example.com"),
            "t***@example.com"
        );
    }

    #[test]
    fn test_email_single_char_local() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Email, "a@example.com"),
            "a@example.com"
        );
    }

    #[test]
    fn test_email_no_at() {
        assert_eq!(DataMasker::apply(&MaskingRule::Email, "notanemail"), "***");
    }

    #[test]
    fn test_email_empty_local() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Email, "@example.com"),
            "***"
        );
    }

    // ----- IdCard -----
    #[test]
    fn test_idcard_standard_18() {
        let id = "110101199001012345";
        let masked = DataMasker::apply(&MaskingRule::IdCard, id);
        // First 4 + 10 stars + last 4 ("2345").
        assert_eq!(masked, "1101**********2345");
        assert_eq!(masked.len(), id.len());
    }

    #[test]
    fn test_idcard_too_short() {
        assert_eq!(DataMasker::apply(&MaskingRule::IdCard, "1234567"), "***");
        assert_eq!(DataMasker::apply(&MaskingRule::IdCard, "12345678"), "***");
    }

    #[test]
    fn test_idcard_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::IdCard, ""), "***");
    }

    // ----- BankCard -----
    #[test]
    fn test_bankcard_standard_16() {
        let card = "6222020200112345";
        let masked = DataMasker::apply(&MaskingRule::BankCard, card);
        assert_eq!(masked, "6222********2345");
    }

    #[test]
    fn test_bankcard_too_short() {
        assert_eq!(DataMasker::apply(&MaskingRule::BankCard, "1234567"), "***");
    }

    #[test]
    fn test_bankcard_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::BankCard, ""), "***");
    }

    // ----- Name -----
    #[test]
    fn test_name_chinese_two_chars() {
        assert_eq!(DataMasker::apply(&MaskingRule::Name, "张三"), "张*");
    }

    #[test]
    fn test_name_chinese_three_chars() {
        assert_eq!(DataMasker::apply(&MaskingRule::Name, "诸葛亮"), "诸**");
    }

    #[test]
    fn test_name_single_char() {
        assert_eq!(DataMasker::apply(&MaskingRule::Name, ""), "");
    }

    #[test]
    fn test_name_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Name, ""), "");
    }

    #[test]
    fn test_name_english() {
        assert_eq!(DataMasker::apply(&MaskingRule::Name, "Alice"), "A****");
    }

    // ----- Address -----
    #[test]
    fn test_address_standard() {
        let addr = "北京市海淀区中关村大街1号";
        let masked = DataMasker::apply(&MaskingRule::Address, addr);
        // First 6 chars kept ("北京市海淀区"), the rest replaced with one `*` per char.
        let expected = "北京市海淀区*******";
        assert_eq!(masked, expected);
        assert_eq!(masked.chars().count(), addr.chars().count());
    }

    #[test]
    fn test_address_exactly_six_chars() {
        let addr = "北京市海淀区";
        assert_eq!(DataMasker::apply(&MaskingRule::Address, addr), "******");
    }

    #[test]
    fn test_address_short() {
        assert_eq!(DataMasker::apply(&MaskingRule::Address, "北京"), "**");
    }

    #[test]
    fn test_address_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Address, ""), "");
    }

    // ----- Custom -----
    #[test]
    fn test_custom_prefix_suffix() {
        let rule = MaskingRule::Custom("3,2".to_string());
        assert_eq!(DataMasker::apply(&rule, "ABCDEFGHIJ"), "ABC*****IJ");
    }

    #[test]
    fn test_custom_too_short() {
        let rule = MaskingRule::Custom("4,4".to_string());
        assert_eq!(DataMasker::apply(&rule, "ABC"), "***");
    }

    #[test]
    fn test_custom_invalid_spec() {
        let rule = MaskingRule::Custom("not_a_number".to_string());
        assert_eq!(DataMasker::apply(&rule, "ABCDEF"), "***");
    }

    #[test]
    fn test_custom_invalid_spec_two_parts() {
        let rule = MaskingRule::Custom("1,2,3".to_string());
        assert_eq!(DataMasker::apply(&rule, "ABCDEF"), "***");
    }

    #[test]
    fn test_custom_empty_value() {
        let rule = MaskingRule::Custom("2,2".to_string());
        assert_eq!(DataMasker::apply(&rule, ""), "***");
    }

    // ----- Unicode safety -----
    #[test]
    fn test_unicode_no_panic() {
        // Mixing CJK + emoji + ascii - just verify no panic and contains stars.
        let value = "你好🌍世界AB";
        let masked = DataMasker::apply(&MaskingRule::Address, value);
        assert!(masked.contains('*'));
    }

    #[test]
    fn test_long_string() {
        let value = "1".repeat(10000);
        let masked = DataMasker::apply(&MaskingRule::Phone, &value);
        // Should start with first 3, end with last 4, all stars in between.
        assert!(masked.starts_with("111"));
        assert!(masked.ends_with("1111"));
        assert_eq!(masked.matches('*').count(), 10000 - 7);
    }

    #[test]
    fn test_single_char_inputs() {
        assert_eq!(DataMasker::apply(&MaskingRule::Phone, "1"), "***");
        assert_eq!(DataMasker::apply(&MaskingRule::IdCard, "1"), "***");
        assert_eq!(DataMasker::apply(&MaskingRule::BankCard, "1"), "***");
        assert_eq!(DataMasker::apply(&MaskingRule::Name, ""), "");
        assert_eq!(DataMasker::apply(&MaskingRule::Address, ""), "*");
    }

    // ----- IP -----
    #[test]
    fn test_ip_v4_standard() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Ip, "192.168.1.100"),
            "192.168.1.*"
        );
    }

    #[test]
    fn test_ip_v4_loopback() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Ip, "127.0.0.1"),
            "127.0.0.*"
        );
    }

    #[test]
    fn test_ip_v6_standard() {
        // IPv6:隐藏最后一个冒号后的内容
        assert_eq!(
            DataMasker::apply(&MaskingRule::Ip, "2001:db8::1"),
            "2001:db8::*"
        );
    }

    #[test]
    fn test_ip_no_separator() {
        assert_eq!(
            DataMasker::apply(&MaskingRule::Ip, "localhost"),
            "localhost"
        );
    }

    #[test]
    fn test_ip_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Ip, ""), "");
    }

    // ----- IMEI -----
    #[test]
    fn test_imei_standard_15() {
        // 15 位 IMEI:保留前 6 + **** + 最后 1 位
        assert_eq!(
            DataMasker::apply(&MaskingRule::Imei, "123456789012345"),
            "123456****5"
        );
    }

    #[test]
    fn test_imei_too_short() {
        assert_eq!(DataMasker::apply(&MaskingRule::Imei, "123456"), "******");
        assert_eq!(DataMasker::apply(&MaskingRule::Imei, "123"), "***");
    }

    #[test]
    fn test_imei_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Imei, ""), "");
    }

    // ----- Plate -----
    #[test]
    fn test_plate_chinese_standard() {
        // 京A12345(7 字符):前 5 + ** + 后 2
        assert_eq!(
            DataMasker::apply(&MaskingRule::Plate, "京A12345"),
            "京A123**45"
        );
    }

    #[test]
    fn test_plate_with_separator() {
        // 京A·12345(8 字符):前 6 + ** + 后 2
        assert_eq!(
            DataMasker::apply(&MaskingRule::Plate, "京A·12345"),
            "京A·123**45"
        );
    }

    #[test]
    fn test_plate_too_short() {
        assert_eq!(DataMasker::apply(&MaskingRule::Plate, "京A"), "**");
        assert_eq!(DataMasker::apply(&MaskingRule::Plate, ""), "*");
        assert_eq!(DataMasker::apply(&MaskingRule::Plate, "京A1"), "***");
    }

    #[test]
    fn test_plate_empty() {
        assert_eq!(DataMasker::apply(&MaskingRule::Plate, ""), "");
    }

    #[test]
    fn test_plate_boundary_four_chars() {
        // 4 字符:前 2 + ** + 后 2
        assert_eq!(DataMasker::apply(&MaskingRule::Plate, "ABCD"), "AB**CD");
    }
}

#[cfg(test)]
mod api_tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_apply_many_stacked_rules() {
        // 先手机号脱敏,再自定义前缀后缀
        let rules = vec![MaskingRule::Phone, MaskingRule::Custom("1,2".to_string())];
        let out = DataMasker::apply_many(&rules, "13812345678");
        assert!(
            out.contains('*'),
            "stacked masking should keep stars: {out}"
        );
    }

    #[test]
    fn test_mask_map_partial_rules() {
        let mut rules = HashMap::new();
        rules.insert("phone".to_string(), MaskingRule::Phone);
        let mut data = HashMap::new();
        data.insert("phone".to_string(), "13812345678".to_string());
        data.insert("name".to_string(), "Alice".to_string());

        let out = DataMasker::mask_map(&rules, &data);
        assert!(
            out["phone"].contains('*'),
            "phone should be masked: {}",
            out["phone"]
        );
        assert_eq!(out["name"], "Alice", "unlisted field passes through");
    }

    #[test]
    fn test_mask_json_top_level_fields() {
        let mut rules = HashMap::new();
        rules.insert("phone".to_string(), MaskingRule::Phone);
        rules.insert("password".to_string(), MaskingRule::Password);

        let json = r#"{"id":1,"phone":"13812345678","password":"secret","name":"Bob"}"#;
        let out = DataMasker::mask_json(&rules, json);
        assert!(out.contains('*'), "masked json should contain stars: {out}");
        assert!(!out.contains("13812345678"), "phone value must not leak");
        assert!(!out.contains("secret"), "password value must not leak");
        assert!(out.contains("Bob"), "unlisted field passes through");
    }

    #[test]
    fn test_mask_json_invalid_input_unchanged() {
        let rules = HashMap::new();
        assert_eq!(DataMasker::mask_json(&rules, "not-json"), "not-json");
    }

    #[test]
    fn test_mask_json_non_object_unchanged() {
        let rules = HashMap::new();
        assert_eq!(DataMasker::mask_json(&rules, "[1,2,3]"), "[1,2,3]");
    }

    #[test]
    fn test_mask_map_empty_rules() {
        let data = HashMap::new();
        let out = DataMasker::mask_map(&HashMap::new(), &data);
        assert!(out.is_empty());
    }

    #[test]
    fn test_apply_many_empty_rules_identity() {
        assert_eq!(DataMasker::apply_many(&[], "hello"), "hello");
    }
}

#[cfg(test)]
mod policy_tests {
    use super::*;
    use std::collections::HashMap;

    // --- MaskingPolicy tests ---

    #[test]
    fn policy_new_empty() {
        let p = MaskingPolicy::new();
        assert_eq!(p.field_count(), 0);
    }

    #[test]
    fn policy_add_and_get_rule() {
        let mut p = MaskingPolicy::new();
        p.add_rule("phone", MaskingRule::Phone);
        assert_eq!(p.field_count(), 1);
        assert!(p.get_rule("phone").is_some());
        assert!(p.get_rule("email").is_none());
    }

    #[test]
    fn policy_remove_rule() {
        let mut p = MaskingPolicy::new();
        p.add_rule("phone", MaskingRule::Phone);
        let removed = p.remove_rule("phone");
        assert!(removed.is_some());
        assert_eq!(p.field_count(), 0);
    }

    #[test]
    fn policy_apply_to_map() {
        let mut p = MaskingPolicy::new();
        p.add_rule("phone", MaskingRule::Phone);
        let mut data = HashMap::new();
        data.insert("phone".to_string(), "13812345678".to_string());
        data.insert("name".to_string(), "Alice".to_string());
        let out = p.apply_to_map(&data);
        assert!(out["phone"].contains('*'));
        assert_eq!(out["name"], "Alice");
    }

    #[test]
    fn policy_apply_to_json() {
        let mut p = MaskingPolicy::new();
        p.add_rule("phone", MaskingRule::Phone);
        let json = r#"{"phone":"13812345678","name":"Bob"}"#;
        let out = p.apply_to_json(json);
        assert!(out.contains('*'));
        assert!(!out.contains("13812345678"));
    }

    #[test]
    fn policy_rules_ref() {
        let mut p = MaskingPolicy::new();
        p.add_rule("a", MaskingRule::Name);
        assert_eq!(p.rules().len(), 1);
    }

    // --- MaskAuditLog tests ---

    #[test]
    fn audit_log_new_empty() {
        let log = MaskAuditLog::new();
        assert_eq!(log.entry_count(), 0);
        assert!(log.entries().is_empty());
    }

    #[test]
    fn audit_log_record() {
        let mut log = MaskAuditLog::new();
        log.log("phone", 11, 11);
        log.log("name", 5, 5);
        assert_eq!(log.entry_count(), 2);
    }

    #[test]
    fn audit_log_total_masked_chars() {
        let mut log = MaskAuditLog::new();
        log.log("phone", 11, 7);
        log.log("name", 5, 3);
        assert_eq!(log.total_masked_chars(), 6);
    }

    #[test]
    fn audit_log_clear() {
        let mut log = MaskAuditLog::new();
        log.log("a", 1, 1);
        log.clear();
        assert_eq!(log.entry_count(), 0);
    }

    #[test]
    fn audit_entry_was_truncated() {
        let mut log = MaskAuditLog::new();
        log.log("short", 10, 5);
        log.log("same", 5, 5);
        assert!(log.entries()[0].was_truncated());
        assert!(!log.entries()[1].was_truncated());
    }

    // --- MaskingConfig tests ---

    #[test]
    fn config_defaults() {
        let c = MaskingConfig::new();
        assert_eq!(c.mask_char(), '*');
        assert_eq!(c.min_mask_length(), 3);
        assert_eq!(c.fallback_value(), "***");
    }

    #[test]
    fn config_builder() {
        let c = MaskingConfig::new()
            .with_mask_char('#')
            .with_min_mask_length(5)
            .with_fallback_value("UNK");
        assert_eq!(c.mask_char(), '#');
        assert_eq!(c.min_mask_length(), 5);
        assert_eq!(c.fallback_value(), "UNK");
    }

    // --- MaskingStats tests ---

    #[test]
    fn stats_new_empty() {
        let s = MaskingStats::new();
        assert_eq!(s.total_operations(), 0);
        assert_eq!(s.most_masked_field(), None);
    }

    #[test]
    fn stats_record_and_total() {
        let mut s = MaskingStats::new();
        s.record("phone");
        s.record("phone");
        s.record("name");
        assert_eq!(s.total_operations(), 3);
        assert_eq!(s.field_operations("phone"), 2);
        assert_eq!(s.field_operations("name"), 1);
    }

    #[test]
    fn stats_most_masked_field() {
        let mut s = MaskingStats::new();
        s.record("a");
        s.record("b");
        s.record("b");
        assert_eq!(s.most_masked_field(), Some("b"));
    }

    #[test]
    fn stats_field_operations_zero_for_unknown() {
        let s = MaskingStats::new();
        assert_eq!(s.field_operations("nonexistent"), 0);
    }
}