dd-sensitive-data-scanner 0.0.0

Core Sensitive Data Scanner library for detecting and redacting sensitive information.
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
use crate::proximity_keywords::compile_keywords_proximity_config;
use crate::scanner::config::RuleConfig;
use crate::scanner::metrics::RuleMetrics;
use crate::scanner::regex_rule::compiled::RegexCompiledRule;
use crate::scanner::regex_rule::regex_store::get_memoized_regex;
use crate::validation::{
    RegexPatternCaptureGroupsValidationError, validate_and_create_regex,
    validate_named_capture_group_minimum_length,
};
use crate::{CompiledRule, CreateScannerError, Labels};
use regex_automata::util::captures::GroupInfo;
use serde::{Deserialize, Serialize};
use serde_with::DefaultOnNull;
use serde_with::serde_as;
use std::sync::Arc;
use strum::{AsRefStr, EnumIter};

pub const DEFAULT_KEYWORD_LOOKAHEAD: usize = 30;

#[serde_as]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct RegexRuleConfig {
    pub pattern: String,
    pub proximity_keywords: Option<ProximityKeywordsConfig>,
    pub validator: Option<SecondaryValidator>,
    #[serde_as(deserialize_as = "DefaultOnNull")]
    #[serde(default)]
    pub labels: Labels,
    pub pattern_capture_groups: Option<Vec<String>>,
}

impl RegexRuleConfig {
    pub fn new(pattern: &str) -> Self {
        #[allow(deprecated)]
        Self {
            pattern: pattern.to_owned(),
            proximity_keywords: None,
            validator: None,
            labels: Labels::default(),
            pattern_capture_groups: None,
        }
    }

    pub fn with_pattern(&self, pattern: &str) -> Self {
        self.mutate_clone(|x| x.pattern = pattern.to_string())
    }

    pub fn with_proximity_keywords(&self, proximity_keywords: ProximityKeywordsConfig) -> Self {
        self.mutate_clone(|x| x.proximity_keywords = Some(proximity_keywords))
    }

    pub fn with_labels(&self, labels: Labels) -> Self {
        self.mutate_clone(|x| x.labels = labels)
    }

    pub fn with_pattern_capture_groups(&self, pattern_capture_groups: Vec<String>) -> Self {
        self.mutate_clone(|x| x.pattern_capture_groups = Some(pattern_capture_groups))
    }

    pub fn with_pattern_capture_group(&self, pattern_capture_group: &str) -> Self {
        self.mutate_clone(|x| match x.pattern_capture_groups {
            Some(ref mut pattern_capture_groups) => {
                pattern_capture_groups.push(pattern_capture_group.to_string());
            }
            None => {
                x.pattern_capture_groups = Some(vec![pattern_capture_group.to_string()]);
            }
        })
    }

    pub fn build(&self) -> Arc<dyn RuleConfig> {
        Arc::new(self.clone())
    }

    fn mutate_clone(&self, modify: impl FnOnce(&mut Self)) -> Self {
        let mut clone = self.clone();
        modify(&mut clone);
        clone
    }

    pub fn with_included_keywords(
        &self,
        keywords: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Self {
        let mut this = self.clone();
        let mut config = self.get_or_create_proximity_keywords_config();
        config.included_keywords = keywords
            .into_iter()
            .map(|x| x.as_ref().to_string())
            .collect::<Vec<_>>();
        this.proximity_keywords = Some(config);
        this
    }

    pub fn with_excluded_keywords(
        &self,
        keywords: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Self {
        let mut this = self.clone();
        let mut config = self.get_or_create_proximity_keywords_config();
        config.excluded_keywords = keywords
            .into_iter()
            .map(|x| x.as_ref().to_string())
            .collect::<Vec<_>>();
        this.proximity_keywords = Some(config);
        this
    }

    pub fn with_validator(&self, validator: Option<SecondaryValidator>) -> Self {
        let mut this = self.clone();
        this.validator = validator;
        this
    }

    fn get_or_create_proximity_keywords_config(&self) -> ProximityKeywordsConfig {
        self.proximity_keywords
            .clone()
            .unwrap_or_else(|| ProximityKeywordsConfig {
                look_ahead_character_count: DEFAULT_KEYWORD_LOOKAHEAD,
                included_keywords: vec![],
                excluded_keywords: vec![],
            })
    }
}

fn is_pattern_capture_groups_valid(
    pattern: &str,
    pattern_capture_groups: &Option<Vec<String>>,
    group_info: &GroupInfo,
) -> Result<(), RegexPatternCaptureGroupsValidationError> {
    if pattern_capture_groups.is_none() {
        return Ok(());
    }
    let pattern_capture_groups = pattern_capture_groups.as_ref().unwrap();
    if pattern_capture_groups.len() != 1 {
        // We currently only allow one capture group
        return Err(
            RegexPatternCaptureGroupsValidationError::TooManyCaptureGroups(
                pattern_capture_groups.len(),
            ),
        );
    }
    let pattern_capture_group = pattern_capture_groups.first().unwrap();
    if !group_info
        .all_names()
        .filter(|(_, _, name)| name.is_some())
        .map(|(_, _, name)| name.unwrap())
        .any(|name| name == pattern_capture_group)
    {
        return Err(
            RegexPatternCaptureGroupsValidationError::CaptureGroupNotPresent(
                pattern_capture_group.clone(),
            ),
        );
    }
    // At this point, the capture group is in the regex, and there is exactly one.
    // Currently, it must be called `sds_match`.
    if pattern_capture_group != "sds_match" {
        return Err(RegexPatternCaptureGroupsValidationError::TargetedCaptureGroupMustBeSdsMatch);
    }
    validate_named_capture_group_minimum_length(pattern, pattern_capture_group)?;
    Ok(())
}

impl RuleConfig for RegexRuleConfig {
    fn convert_to_compiled_rule(
        &self,
        rule_index: usize,
        scanner_labels: Labels,
    ) -> Result<Box<dyn CompiledRule>, CreateScannerError> {
        let regex = get_memoized_regex(&self.pattern, validate_and_create_regex)?;

        let rule_labels = scanner_labels.clone_with_labels(self.labels.clone());

        let (included_keywords, excluded_keywords) = self
            .proximity_keywords
            .as_ref()
            .map(|config| compile_keywords_proximity_config(config, &rule_labels))
            .unwrap_or(Ok((None, None)))?;

        is_pattern_capture_groups_valid(
            &self.pattern,
            &self.pattern_capture_groups,
            regex.group_info(),
        )?;

        Ok(Box::new(RegexCompiledRule {
            rule_index,
            regex,
            included_keywords,
            excluded_keywords,
            validator: self.validator.clone().map(|x| x.compile()),
            metrics: RuleMetrics::new(&rule_labels),
            pattern_capture_groups: self.pattern_capture_groups.clone(),
        }))
    }

    fn as_regex_rule(&self) -> Option<&RegexRuleConfig> {
        Some(self)
    }
}

#[serde_as]
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct ProximityKeywordsConfig {
    pub look_ahead_character_count: usize,

    #[serde_as(deserialize_as = "DefaultOnNull")]
    #[serde(default)]
    pub included_keywords: Vec<String>,

    #[serde_as(deserialize_as = "DefaultOnNull")]
    #[serde(default)]
    pub excluded_keywords: Vec<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, EnumIter, AsRefStr)]
#[serde(tag = "type")]
pub enum SecondaryValidator {
    AbaRtnChecksum,
    AtlassianTokenChecksum,
    AustralianMedicareChecksum,
    AustralianTfnChecksum,
    AustrianSSNChecksum,
    BelgiumNationalRegisterChecksum,
    BrazilianCnpjChecksum,
    BrazilianCpfChecksum,
    BtcChecksum,
    BulgarianEGNChecksum,
    ChineseIdChecksum,
    CoordinationNumberChecksum,
    CzechPersonalIdentificationNumberChecksum,
    CzechTaxIdentificationNumberChecksum,
    DutchBsnChecksum,
    DutchPassportChecksum,
    EntropyCheck,
    EstoniaPersonalCodeChecksum,
    EthereumChecksum,
    FinnishHetuChecksum,
    FranceNifChecksum,
    FranceSsnChecksum,
    GermanIdsChecksum,
    GermanSvnrChecksum,
    GithubTokenChecksum,
    GreeceAmkaChecksum,
    GreekTinChecksum,
    HungarianTinChecksum,
    IbanChecker,
    IrishPpsChecksum,
    ItalianNationalIdChecksum,
    JwtClaimsValidator { config: JwtClaimsValidatorConfig },
    JwtExpirationChecker,
    LatviaNationalIdChecksum,
    LithuanianPersonalIdentificationNumberChecksum,
    LuhnChecksum,
    LuxembourgIndividualNINChecksum,
    Mod11_10checksum,
    Mod11_2checksum,
    Mod1271_36Checksum,
    Mod27_26checksum,
    Mod37_2checksum,
    Mod37_36checksum,
    Mod661_26checksum,
    Mod97_10checksum,
    MoneroAddress,
    NhsCheckDigit,
    NirChecksum,
    NonHexChecker,
    PolishNationalIdChecksum,
    PolishNipChecksum,
    PortugueseTaxIdChecksum,
    RodneCisloNumberChecksum,
    RomanianPersonalNumericCode,
    SingaporeNricChecksum,
    SloveniaTinChecksum,
    SlovenianPINChecksum,
    SpanishDniChecksum,
    SpanishNussChecksum,
    SwedenPINChecksum,
    UkNinoFormatCheck,
    UkTrnChecksum,
    UsDeaChecksum,
    UsNpiChecksum,
    VerhoeffChecksum,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
#[serde(tag = "type", content = "config")]
pub enum ClaimRequirement {
    /// Just check that the claim exists
    Present,
    /// Check that the claim exists and is not expired
    NotExpired,
    /// Check that the claim exists and has an exact value
    ExactValue(String),
    /// Check that the claim exists and matches a regex pattern
    RegexMatch(String),
}

#[derive(Serialize, Deserialize, Default, Clone, Debug, PartialEq)]
pub struct JwtClaimsValidatorConfig {
    #[serde(default)]
    pub required_headers: std::collections::BTreeMap<String, ClaimRequirement>,
    #[serde(default)]
    pub required_claims: std::collections::BTreeMap<String, ClaimRequirement>,
}

#[cfg(test)]
mod test {
    use crate::{AwsType, CustomHttpConfig, MatchValidationType, RootRuleConfig};
    use std::collections::BTreeMap;
    use strum::IntoEnumIterator;

    use super::*;

    #[test]
    fn should_override_pattern() {
        let rule_config = RegexRuleConfig::new("123").with_pattern("456");
        assert_eq!(rule_config.pattern, "456");
    }

    #[test]
    #[allow(deprecated)]
    fn should_have_default() {
        let rule_config = RegexRuleConfig::new("123");
        assert_eq!(
            rule_config,
            RegexRuleConfig {
                pattern: "123".to_string(),
                proximity_keywords: None,
                validator: None,
                labels: Labels::empty(),
                pattern_capture_groups: None,
            }
        );
    }

    #[test]
    fn should_use_capture_group() {
        let rule_config = RegexRuleConfig::new("hey (?<capture_group>world)")
            .with_pattern_capture_groups(vec!["capture_group".to_string()]);
        assert_eq!(
            rule_config,
            RegexRuleConfig {
                pattern: "hey (?<capture_group>world)".to_string(),
                proximity_keywords: None,
                validator: None,
                labels: Labels::empty(),
                pattern_capture_groups: Some(vec!["capture_group".to_string()]),
            }
        );
    }

    #[test]
    fn proximity_keywords_should_have_default() {
        let json_config = r#"{"look_ahead_character_count": 0}"#;
        let test: ProximityKeywordsConfig = serde_json::from_str(json_config).unwrap();
        assert_eq!(
            test,
            ProximityKeywordsConfig {
                look_ahead_character_count: 0,
                included_keywords: vec![],
                excluded_keywords: vec![]
            }
        );

        let json_config = r#"{"look_ahead_character_count": 0, "excluded_keywords": null, "included_keywords": null}"#;
        let test: ProximityKeywordsConfig = serde_json::from_str(json_config).unwrap();
        assert_eq!(
            test,
            ProximityKeywordsConfig {
                look_ahead_character_count: 0,
                included_keywords: vec![],
                excluded_keywords: vec![]
            }
        );
    }

    #[test]
    #[allow(deprecated)]
    fn test_third_party_active_checker() {
        // Test setting only the new field
        let http_config = CustomHttpConfig::default().with_endpoint("http://test.com".to_string());
        let validation_type = MatchValidationType::CustomHttp(http_config.clone());
        let rule_config = RootRuleConfig::new(RegexRuleConfig::new("123"))
            .third_party_active_checker(validation_type.clone());

        assert_eq!(
            rule_config.third_party_active_checker,
            Some(validation_type.clone())
        );
        assert_eq!(rule_config.match_validation_type, None);
        assert_eq!(
            rule_config.get_third_party_active_checker(),
            Some(&validation_type)
        );

        // Test setting via deprecated field updates both
        let aws_type = AwsType::AwsId;
        let validation_type2 = MatchValidationType::Aws(aws_type);
        let rule_config = RootRuleConfig::new(RegexRuleConfig::new("123"))
            .third_party_active_checker(validation_type2.clone());

        assert_eq!(
            rule_config.third_party_active_checker,
            Some(validation_type2.clone())
        );
        assert_eq!(
            rule_config.get_third_party_active_checker(),
            Some(&validation_type2)
        );

        // Test that get_match_validation_type prioritizes third_party_active_checker
        let rule_config = RootRuleConfig::new(RegexRuleConfig::new("123"))
            .third_party_active_checker(MatchValidationType::CustomHttp(http_config.clone()));

        assert_eq!(
            rule_config.get_third_party_active_checker(),
            Some(&MatchValidationType::CustomHttp(http_config.clone()))
        );
    }

    #[test]
    fn test_secondary_validator_enum_iter() {
        // Test that we can iterate over all SecondaryValidator variants
        let validators: Vec<SecondaryValidator> = SecondaryValidator::iter().collect();
        // Verify some variants
        assert!(validators.contains(&SecondaryValidator::GithubTokenChecksum));
        assert!(validators.contains(&SecondaryValidator::JwtExpirationChecker));
    }

    #[test]
    fn test_secondary_validator_are_sorted() {
        let validator_names: Vec<String> = SecondaryValidator::iter()
            .map(|a| a.as_ref().to_string())
            .collect();
        let mut sorted_validator_names = validator_names.clone();
        sorted_validator_names.sort();
        assert_eq!(
            sorted_validator_names, validator_names,
            "Secondary validators should be sorted by alphabetical order, but it's not the case, expected order:"
        );
    }

    // The order has to be stable to pass linter checks. Otherwise, each instantiation will change the file
    #[test]
    fn test_jwt_claims_validator_config_serialization_order() {
        // Create a config with claims in non-alphabetical order
        let mut required_claims = BTreeMap::new();
        required_claims.insert("zzz".to_string(), ClaimRequirement::Present);
        required_claims.insert("exp".to_string(), ClaimRequirement::NotExpired);
        required_claims.insert(
            "aaa".to_string(),
            ClaimRequirement::ExactValue("test".to_string()),
        );
        required_claims.insert(
            "mmm".to_string(),
            ClaimRequirement::RegexMatch(r"^test.*".to_string()),
        );

        let config = JwtClaimsValidatorConfig {
            required_claims,
            required_headers: std::collections::BTreeMap::new(),
        };

        // Serialize multiple times to ensure stable order
        let serialized1 = serde_json::to_string(&config).unwrap();
        let serialized2 = serde_json::to_string(&config).unwrap();

        // Both serializations should be identical
        assert_eq!(serialized1, serialized2, "Serialization should be stable");

        // Keys should be in alphabetical order
        assert!(serialized1.find("aaa").unwrap() < serialized1.find("exp").unwrap());
        assert!(serialized1.find("exp").unwrap() < serialized1.find("mmm").unwrap());
        assert!(serialized1.find("mmm").unwrap() < serialized1.find("zzz").unwrap());
    }

    #[test]
    fn test_capture_groups_validation() {
        let test_cases: Vec<(
            &str,
            Vec<String>,
            Result<(), RegexPatternCaptureGroupsValidationError>,
        )> = vec![
            (
                "hello (?<sds_match>world)",
                vec!["sds_match".to_string()],
                Ok(()),
            ),
            (
                "hello (?<capture_group>world)",
                vec!["capture_group".to_string()],
                Err(RegexPatternCaptureGroupsValidationError::TargetedCaptureGroupMustBeSdsMatch),
            ),
            (
                "hello (?<sds_match>world) and (?<another_group>world)",
                vec!["sds_match".to_string()],
                Ok(()),
            ),
            (
                "hello (?<capture_grou>world)",
                vec!["capture_group".to_string()],
                Err(
                    RegexPatternCaptureGroupsValidationError::CaptureGroupNotPresent(
                        "capture_group".to_string(),
                    ),
                ),
            ),
            (
                "hello (?<sds_match>d*)",
                vec!["sds_match".to_string()],
                Err(RegexPatternCaptureGroupsValidationError::CaptureGroupMatchesEmptyString),
            ),
            (
                "hello (?<sds_match>world)",
                vec!["sds_match".to_string(), "sds_match2".to_string()],
                Err(RegexPatternCaptureGroupsValidationError::TooManyCaptureGroups(2)),
            ),
        ];
        for (pattern, capture_groups, expected_result) in test_cases {
            let rule_config =
                RegexRuleConfig::new(pattern).with_pattern_capture_groups(capture_groups);
            assert_eq!(
                is_pattern_capture_groups_valid(
                    &rule_config.pattern,
                    &rule_config.pattern_capture_groups,
                    &get_memoized_regex(pattern, validate_and_create_regex)
                        .unwrap()
                        .group_info()
                ),
                expected_result
            );
        }
    }
}