leaktor 0.4.1

A secrets scanner with pattern matching, entropy analysis, and live validation
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::Path;

/// Configuration for Leaktor
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Entropy threshold for high-entropy detection
    pub entropy_threshold: f64,

    /// Minimum confidence score to report
    pub min_confidence: f64,

    /// Enable validation of detected secrets
    pub enable_validation: bool,

    /// Scan git history
    pub scan_git_history: bool,

    /// Maximum depth for git history scan
    pub max_git_depth: Option<usize>,

    /// Respect .gitignore files
    pub respect_gitignore: bool,

    /// Maximum file size to scan (in bytes)
    pub max_file_size: u64,

    /// Exclude test files from scanning
    pub exclude_tests: bool,

    /// Exclude documentation from scanning
    pub exclude_docs: bool,

    /// Custom patterns to detect
    #[serde(default)]
    pub custom_patterns: Vec<CustomPattern>,

    /// Allowlist rules -- suppress findings that match any of these rules
    #[serde(default)]
    pub allowlist: Vec<AllowlistRule>,

    /// Severity levels to report
    #[serde(default = "default_severities")]
    pub report_severities: Vec<String>,

    /// Maximum number of concurrent API validation requests.
    /// Prevents hammering external APIs when scanning large repos.
    /// Set to 0 to disable API-based validation entirely.
    #[serde(default = "default_max_concurrent_validations")]
    pub max_concurrent_validations: usize,

    /// Minimum delay between API requests to the same host (in milliseconds).
    /// Spreads out requests to avoid triggering service rate limits.
    #[serde(default = "default_validation_delay_ms")]
    pub validation_delay_ms: u64,

    /// Maximum number of retries when an API returns 429 Too Many Requests.
    #[serde(default = "default_validation_max_retries")]
    pub validation_max_retries: u32,
}

fn default_max_concurrent_validations() -> usize {
    10
}

fn default_validation_delay_ms() -> u64 {
    100
}

fn default_validation_max_retries() -> u32 {
    3
}

/// A user-defined detection pattern.
///
/// Define custom patterns in `.leaktor.toml`:
///
/// ```toml
/// [[custom_patterns]]
/// name = "Internal API Key"
/// regex = "internal_api_[0-9a-f]{32}"
/// severity = "HIGH"
/// confidence = 0.85
/// description = "Internal API key for our backend services"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomPattern {
    /// Display name for this pattern (e.g. "Internal API Key")
    pub name: String,
    /// Regex to match (Rust regex syntax)
    pub regex: String,
    /// Severity: CRITICAL, HIGH, MEDIUM, or LOW
    pub severity: String,
    /// Base confidence score (0.0 - 1.0)
    pub confidence: f64,
    /// Optional description for documentation
    #[serde(default)]
    pub description: Option<String>,
}

/// A rule to suppress (allowlist) certain findings.
///
/// All fields are optional; a finding must match **every** specified field
/// to be suppressed.
///
/// ```toml
/// [[allowlist]]
/// description = "Test Sentry DSN"
/// secret_types = ["Sentry DSN"]
///
/// [[allowlist]]
/// description = "All findings in test fixtures"
/// paths = ["tests/fixtures/*", "*.test.*"]
///
/// [[allowlist]]
/// description = "Example AWS key from documentation"
/// value_regex = "AKIAIOSFODNN7EXAMPLE"
///
/// [[allowlist]]
/// description = "Low-risk public Mapbox tokens"
/// secret_types = ["Mapbox Token"]
/// severities = ["LOW", "MEDIUM"]
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AllowlistRule {
    /// Human-readable description of why this rule exists
    #[serde(default)]
    pub description: Option<String>,

    /// Match findings whose secret type name is in this list (case-sensitive).
    /// If empty/absent, matches any type.
    #[serde(default)]
    pub secret_types: Vec<String>,

    /// Match findings whose file path matches any of these glob patterns.
    /// If empty/absent, matches any path.
    #[serde(default)]
    pub paths: Vec<String>,

    /// Match findings whose secret value matches this regex.
    /// If absent, matches any value.
    #[serde(default)]
    pub value_regex: Option<String>,

    /// Match findings whose severity is in this list.
    /// If empty/absent, matches any severity.
    #[serde(default)]
    pub severities: Vec<String>,
}

impl AllowlistRule {
    /// Returns true if all filtering criteria are empty, meaning this rule
    /// has no constraints and would incorrectly suppress every finding.
    pub fn has_no_criteria(&self) -> bool {
        self.secret_types.is_empty()
            && self.paths.is_empty()
            && self.value_regex.is_none()
            && self.severities.is_empty()
    }

    /// Check whether a finding matches this rule.
    /// A finding must match **all** non-empty criteria to be suppressed.
    /// A rule with zero criteria never matches (defense against misconfiguration).
    pub fn matches(
        &self,
        secret_type_name: &str,
        file_path: &str,
        secret_value: &str,
        severity_name: &str,
    ) -> bool {
        // A rule with no criteria at all is a misconfiguration -- it should
        // never act as a wildcard that suppresses every finding.
        if self.has_no_criteria() {
            return false;
        }

        // Check secret_types (if specified)
        if !self.secret_types.is_empty() && !self.secret_types.iter().any(|t| t == secret_type_name)
        {
            return false;
        }

        // Check paths (if specified).
        // `glob_match` already handles:
        //   - Patterns without `/` are matched against the filename
        //   - Patterns with `/` are tried against every suffix of the path
        //   - `**/` anchoring
        if !self.paths.is_empty() {
            let matches_any = self.paths.iter().any(|p| glob_match(file_path, p));
            if !matches_any {
                return false;
            }
        }

        // Check value_regex (if specified)
        if let Some(ref re_str) = self.value_regex {
            match regex::Regex::new(re_str) {
                Ok(re) => {
                    if !re.is_match(secret_value) {
                        return false;
                    }
                }
                Err(_) => return false, // invalid regex never matches
            }
        }

        // Check severities (if specified)
        if !self.severities.is_empty()
            && !self
                .severities
                .iter()
                .any(|s| s.eq_ignore_ascii_case(severity_name))
        {
            return false;
        }

        true
    }
}

/// Glob matching for allowlist paths.
///
/// Supported syntax:
///   - `*`    matches any sequence of non-`/` characters (single segment)
///   - `**`   matches any sequence of characters including `/` (multiple segments)
///   - `?`    matches exactly one non-`/` character
///   - `!pat` negation — returns the inverse of matching `pat`
///   - All other characters match literally (case-sensitive)
///
/// Follows `.gitignore` conventions:
///   - A pattern *without* a `/` separator (e.g. `*.rs`) is matched against the
///     filename only (last path component), so `*.rs` matches `src/main.rs`.
///   - A pattern *with* a `/` (or starting with `**/`) is matched against the
///     full path, with `**/` anchoring allowed anywhere.
pub fn glob_match(text: &str, pattern: &str) -> bool {
    // Handle negation: !pattern
    if let Some(inner) = pattern.strip_prefix('!') {
        return !glob_match(text, inner);
    }

    // If pattern starts with **/, allow matching anywhere in the path
    if let Some(suffix) = pattern.strip_prefix("**/") {
        // Try matching against every possible tail of the path
        if glob_match_inner(text, suffix) {
            return true;
        }
        for (i, c) in text.char_indices() {
            if c == '/' && glob_match_inner(&text[i + 1..], suffix) {
                return true;
            }
        }
        return false;
    }

    // .gitignore convention: if the pattern contains no `/`, match it against
    // the filename (last component) rather than requiring a full-path match.
    // This means `*.rs` matches `src/main.rs` just like `.gitignore`.
    if !pattern.contains('/') {
        let filename = text.rsplit('/').next().unwrap_or(text);
        return glob_match_inner(filename, pattern);
    }

    // Pattern contains `/` — try full-path match first, then try matching
    // against any suffix of the path (handles absolute vs relative paths).
    if glob_match_inner(text, pattern) {
        return true;
    }
    for (i, c) in text.char_indices() {
        if c == '/' && glob_match_inner(&text[i + 1..], pattern) {
            return true;
        }
    }

    false
}

/// Core recursive glob matcher. Matches `text` against `pattern` where:
///   - `**` matches zero or more path segments (including separators)
///   - `*`  matches zero or more non-`/` characters
///   - `?`  matches exactly one non-`/` character
pub(crate) fn glob_match_inner(text: &str, pattern: &str) -> bool {
    // Use iterative approach with backtracking positions for `*` and `**`
    let text_bytes = text.as_bytes();
    let pat_bytes = pattern.as_bytes();
    let (tlen, plen) = (text_bytes.len(), pat_bytes.len());

    let mut ti = 0usize; // text index
    let mut pi = 0usize; // pattern index

    // Backtrack positions for single `*`
    let mut star_pi: Option<usize> = None;
    let mut star_ti: usize = 0;

    // Backtrack positions for `**`
    let mut dstar_pi: Option<usize> = None;
    let mut dstar_ti: usize = 0;

    while ti < tlen || pi < plen {
        if pi < plen {
            // Check for `**`
            if pi + 1 < plen && pat_bytes[pi] == b'*' && pat_bytes[pi + 1] == b'*' {
                // Skip all consecutive `*`
                let mut pp = pi;
                while pp < plen && pat_bytes[pp] == b'*' {
                    pp += 1;
                }
                // Skip optional trailing `/` after `**`
                if pp < plen && pat_bytes[pp] == b'/' {
                    pp += 1;
                }
                dstar_pi = Some(pp);
                dstar_ti = ti;
                pi = pp;
                // Reset single-star backtrack since ** is more powerful
                star_pi = None;
                continue;
            }

            // Check for single `*`
            if pat_bytes[pi] == b'*' {
                star_pi = Some(pi + 1);
                star_ti = ti;
                pi += 1;
                continue;
            }

            if ti < tlen {
                // `?` matches any single char except `/`
                if pat_bytes[pi] == b'?' && text_bytes[ti] != b'/' {
                    ti += 1;
                    pi += 1;
                    continue;
                }

                // Literal match
                if pat_bytes[pi] == text_bytes[ti] {
                    ti += 1;
                    pi += 1;
                    continue;
                }
            }
        }

        // Mismatch — try backtracking to single `*` (no `/` crossing)
        if let Some(sp) = star_pi {
            if star_ti < tlen && text_bytes[star_ti] != b'/' {
                star_ti += 1;
                ti = star_ti;
                pi = sp;
                continue;
            }
        }

        // Mismatch — try backtracking to `**` (crosses `/`)
        if let Some(dp) = dstar_pi {
            dstar_ti += 1;
            if dstar_ti <= tlen {
                ti = dstar_ti;
                pi = dp;
                star_pi = None; // reset single-star
                continue;
            }
        }

        return false;
    }

    true
}

fn default_severities() -> Vec<String> {
    vec![
        "CRITICAL".to_string(),
        "HIGH".to_string(),
        "MEDIUM".to_string(),
        "LOW".to_string(),
    ]
}

impl Default for Config {
    fn default() -> Self {
        Self {
            entropy_threshold: 3.5,
            min_confidence: 0.6,
            enable_validation: false,
            scan_git_history: true,
            max_git_depth: None,
            respect_gitignore: true,
            max_file_size: 1024 * 1024, // 1MB
            exclude_tests: false,
            exclude_docs: false,
            custom_patterns: Vec::new(),
            allowlist: Vec::new(),
            report_severities: default_severities(),
            max_concurrent_validations: default_max_concurrent_validations(),
            validation_delay_ms: default_validation_delay_ms(),
            validation_max_retries: default_validation_max_retries(),
        }
    }
}

impl Config {
    /// Load configuration from a TOML file
    pub fn from_toml_file(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        let config: Config = toml::from_str(&content)?;
        config.warn_empty_allowlist_rules();
        Ok(config)
    }

    /// Load configuration from a YAML file
    pub fn from_yaml_file(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)?;
        let config: Config = serde_yaml::from_str(&content)?;
        config.warn_empty_allowlist_rules();
        Ok(config)
    }

    /// Emit a warning for any allowlist rule that has no filtering criteria.
    /// Such rules are ignored at match time to prevent silent suppression of
    /// all findings (a common misconfiguration).
    fn warn_empty_allowlist_rules(&self) {
        for (i, rule) in self.allowlist.iter().enumerate() {
            if rule.has_no_criteria() {
                let desc = rule
                    .description
                    .as_deref()
                    .unwrap_or("<no description>");
                eprintln!(
                    "warning: allowlist rule #{} ({}) has no criteria (secret_types, paths, \
                     value_regex, severities are all empty) -- this rule will be ignored. \
                     Specify at least one criterion.",
                    i + 1,
                    desc,
                );
            }
        }
    }

    /// Save configuration to a TOML file.
    ///
    /// Uses a custom serialization order that places all scalar/simple keys
    /// before `[[custom_patterns]]` and `[[allowlist]]` table arrays.  This
    /// avoids the TOML "section absorption" trap where keys written *after*
    /// a `[[table_array]]` header get silently absorbed into that section,
    /// triggering `deny_unknown_fields` errors.
    pub fn to_toml_file(&self, path: &Path) -> Result<()> {
        let mut content = String::new();
        content.push_str("# Leaktor configuration\n");
        content.push_str("# https://github.com/reschjonas/leaktor\n");
        content.push_str("#\n");
        content.push_str(
            "# IMPORTANT: All top-level keys (like entropy_threshold, report_severities)\n",
        );
        content.push_str(
            "# must appear BEFORE any [[custom_patterns]] or [[allowlist]] sections.\n",
        );
        content.push_str(
            "# TOML treats keys after [[section]] headers as part of that section.\n\n",
        );

        // Scalar / simple keys first
        content.push_str(&format!("entropy_threshold = {}\n", self.entropy_threshold));
        content.push_str(&format!("min_confidence = {}\n", self.min_confidence));
        content.push_str(&format!(
            "enable_validation = {}\n",
            self.enable_validation
        ));
        content.push_str(&format!("scan_git_history = {}\n", self.scan_git_history));
        if let Some(depth) = self.max_git_depth {
            content.push_str(&format!("max_git_depth = {}\n", depth));
        }
        content.push_str(&format!("respect_gitignore = {}\n", self.respect_gitignore));
        content.push_str(&format!("max_file_size = {}\n", self.max_file_size));
        content.push_str(&format!("exclude_tests = {}\n", self.exclude_tests));
        content.push_str(&format!("exclude_docs = {}\n", self.exclude_docs));

        // report_severities as inline array
        let sevs: Vec<String> = self.report_severities.iter().map(|s| format!("\"{}\"", s)).collect();
        content.push_str(&format!("report_severities = [{}]\n", sevs.join(", ")));

        content.push_str(&format!(
            "max_concurrent_validations = {}\n",
            self.max_concurrent_validations
        ));
        content.push_str(&format!(
            "validation_delay_ms = {}\n",
            self.validation_delay_ms
        ));
        content.push_str(&format!(
            "validation_max_retries = {}\n",
            self.validation_max_retries
        ));

        // Table arrays last
        content.push('\n');
        if self.custom_patterns.is_empty() {
            content.push_str("# [[custom_patterns]]\n");
            content.push_str("# name = \"Internal API Key\"\n");
            content.push_str("# regex = \"int_key_[0-9a-f]{32}\"\n");
            content.push_str("# severity = \"HIGH\"\n");
            content.push_str("# confidence = 0.85\n");
            content.push_str("# description = \"Internal API key\"\n\n");
        } else {
            for cp in &self.custom_patterns {
                content.push_str("[[custom_patterns]]\n");
                content.push_str(&format!("name = \"{}\"\n", cp.name));
                content.push_str(&format!("regex = \"{}\"\n", cp.regex));
                content.push_str(&format!("severity = \"{}\"\n", cp.severity));
                content.push_str(&format!("confidence = {}\n", cp.confidence));
                if let Some(ref desc) = cp.description {
                    content.push_str(&format!("description = \"{}\"\n", desc));
                }
                content.push('\n');
            }
        }

        if self.allowlist.is_empty() {
            content.push_str("# [[allowlist]]\n");
            content.push_str("# description = \"Suppress Sentry DSNs\"\n");
            content.push_str("# secret_types = [\"Sentry DSN\"]\n");
        } else {
            for rule in &self.allowlist {
                content.push_str("[[allowlist]]\n");
                if let Some(ref desc) = rule.description {
                    content.push_str(&format!("description = \"{}\"\n", desc));
                }
                if !rule.secret_types.is_empty() {
                    let types: Vec<String> =
                        rule.secret_types.iter().map(|t| format!("\"{}\"", t)).collect();
                    content.push_str(&format!("secret_types = [{}]\n", types.join(", ")));
                }
                if !rule.paths.is_empty() {
                    let paths: Vec<String> =
                        rule.paths.iter().map(|p| format!("\"{}\"", p)).collect();
                    content.push_str(&format!("paths = [{}]\n", paths.join(", ")));
                }
                if let Some(ref re) = rule.value_regex {
                    content.push_str(&format!("value_regex = \"{}\"\n", re));
                }
                if !rule.severities.is_empty() {
                    let sevs: Vec<String> =
                        rule.severities.iter().map(|s| format!("\"{}\"", s)).collect();
                    content.push_str(&format!("severities = [{}]\n", sevs.join(", ")));
                }
                content.push('\n');
            }
        }

        fs::write(path, content)?;
        Ok(())
    }

    /// Save configuration to a YAML file
    pub fn to_yaml_file(&self, path: &Path) -> Result<()> {
        let content = serde_yaml::to_string(self)?;
        fs::write(path, content)?;
        Ok(())
    }

    /// Try to load config from current directory or parent directories
    pub fn load_from_current_dir() -> Result<Self> {
        let config_names = [".leaktor.toml", ".leaktor.yaml", ".leaktor.yml"];

        for name in &config_names {
            let path = Path::new(name);
            if path.exists() {
                if name.ends_with(".toml") {
                    return Self::from_toml_file(path);
                } else {
                    return Self::from_yaml_file(path);
                }
            }
        }

        // No config file found, use defaults
        Ok(Self::default())
    }

    /// Compile the allowlist rules into a list for efficient matching.
    /// Returns the list of rules (cheap -- just borrows).
    pub fn compiled_allowlist(&self) -> &[AllowlistRule] {
        &self.allowlist
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.entropy_threshold, 3.5);
        assert_eq!(config.min_confidence, 0.6);
        assert!(config.scan_git_history);
        assert!(config.allowlist.is_empty());
        assert!(config.custom_patterns.is_empty());
    }

    #[test]
    fn test_config_serialization() -> Result<()> {
        let config = Config::default();
        let toml_str = toml::to_string(&config)?;
        assert!(toml_str.contains("entropy_threshold"));
        Ok(())
    }

    #[test]
    fn test_config_save_and_load() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let config_path = temp_dir.path().join("test.toml");

        let config = Config::default();
        config.to_toml_file(&config_path)?;

        let loaded = Config::from_toml_file(&config_path)?;
        assert_eq!(loaded.entropy_threshold, config.entropy_threshold);

        Ok(())
    }

    #[test]
    fn test_custom_patterns_round_trip() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let config_path = temp_dir.path().join("test.toml");

        let mut config = Config::default();
        config.custom_patterns.push(CustomPattern {
            name: "Internal Key".to_string(),
            regex: "int_key_[a-f0-9]{32}".to_string(),
            severity: "HIGH".to_string(),
            confidence: 0.85,
            description: Some("Company internal key".to_string()),
        });
        config.to_toml_file(&config_path)?;

        let loaded = Config::from_toml_file(&config_path)?;
        assert_eq!(loaded.custom_patterns.len(), 1);
        assert_eq!(loaded.custom_patterns[0].name, "Internal Key");
        assert_eq!(loaded.custom_patterns[0].confidence, 0.85);
        Ok(())
    }

    #[test]
    fn test_allowlist_round_trip() -> Result<()> {
        let temp_dir = TempDir::new()?;
        let config_path = temp_dir.path().join("test.toml");

        let mut config = Config::default();
        config.allowlist.push(AllowlistRule {
            description: Some("Skip Sentry DSN".to_string()),
            secret_types: vec!["Sentry DSN".to_string()],
            paths: vec![],
            value_regex: None,
            severities: vec![],
        });
        config.to_toml_file(&config_path)?;

        let loaded = Config::from_toml_file(&config_path)?;
        assert_eq!(loaded.allowlist.len(), 1);
        assert_eq!(loaded.allowlist[0].secret_types, vec!["Sentry DSN"]);
        Ok(())
    }

    #[test]
    fn test_allowlist_rule_matches_type() {
        let rule = AllowlistRule {
            description: None,
            secret_types: vec!["Sentry DSN".to_string()],
            paths: vec![],
            value_regex: None,
            severities: vec![],
        };

        assert!(rule.matches("Sentry DSN", "any/path", "any_value", "MEDIUM"));
        assert!(!rule.matches("GitHub PAT", "any/path", "any_value", "CRITICAL"));
    }

    #[test]
    fn test_allowlist_rule_matches_path() {
        let rule = AllowlistRule {
            description: None,
            secret_types: vec![],
            paths: vec!["tests/fixtures/*".to_string()],
            value_regex: None,
            severities: vec![],
        };

        assert!(rule.matches("Any", "tests/fixtures/secrets.env", "val", "HIGH"));
        assert!(!rule.matches("Any", "src/main.rs", "val", "HIGH"));
    }

    #[test]
    fn test_allowlist_rule_matches_value_regex() {
        let rule = AllowlistRule {
            description: None,
            secret_types: vec![],
            paths: vec![],
            value_regex: Some("AKIAIOSFODNN7EXAMPLE".to_string()),
            severities: vec![],
        };

        assert!(rule.matches("AWS", "file.env", "AKIAIOSFODNN7EXAMPLE", "CRITICAL"));
        assert!(!rule.matches("AWS", "file.env", "AKIAREALKEY12345678", "CRITICAL"));
    }

    #[test]
    fn test_allowlist_rule_matches_severity() {
        let rule = AllowlistRule {
            description: None,
            secret_types: vec![],
            paths: vec![],
            value_regex: None,
            severities: vec!["LOW".to_string(), "MEDIUM".to_string()],
        };

        assert!(rule.matches("Any", "any", "val", "LOW"));
        assert!(rule.matches("Any", "any", "val", "MEDIUM"));
        assert!(!rule.matches("Any", "any", "val", "CRITICAL"));
    }

    #[test]
    fn test_allowlist_rule_multi_criteria() {
        let rule = AllowlistRule {
            description: None,
            secret_types: vec!["Sentry DSN".to_string()],
            paths: vec!["tests/**/*".to_string()],
            value_regex: None,
            severities: vec![],
        };

        // Both criteria must match
        assert!(rule.matches("Sentry DSN", "tests/fixtures/env", "val", "MEDIUM"));
        // Only type matches, path doesn't
        assert!(!rule.matches("Sentry DSN", "src/main.rs", "val", "MEDIUM"));
        // Only path matches, type doesn't
        assert!(!rule.matches("GitHub PAT", "tests/foo", "val", "CRITICAL"));
    }

    #[test]
    fn test_glob_match_single_star() {
        // Single `*` matches within one segment (no `/`)
        assert!(glob_match("tests/fixtures/secret.env", "tests/fixtures/*.env"));
        assert!(glob_match("secret.env", "*.env"));
        assert!(!glob_match("tests/fixtures/secret.env", "tests/*.env")); // * doesn't cross /
        assert!(!glob_match("src/main.rs", "*.py"));
    }

    #[test]
    fn test_glob_match_double_star() {
        // `**` matches across directory boundaries
        assert!(glob_match("foo/bar/baz.js", "**/baz.js"));
        assert!(glob_match("baz.js", "**/baz.js"));
        assert!(glob_match("a/b/c/d/e.txt", "a/**/e.txt"));
        assert!(glob_match("a/e.txt", "a/**/e.txt"));
        assert!(glob_match("tests/fixtures/secret.env", "tests/**/*.env"));
        assert!(glob_match("tests/deep/nested/secret.env", "tests/**/*.env"));
    }

    #[test]
    fn test_glob_match_question_mark() {
        assert!(glob_match("test.rs", "test.?s"));
        assert!(glob_match("test.js", "test.?s"));
        assert!(!glob_match("test.rs", "test.??s"));
    }

    #[test]
    fn test_glob_match_negation() {
        assert!(!glob_match("secret.env", "!*.env"));
        assert!(glob_match("secret.txt", "!*.env"));
    }

    #[test]
    fn test_glob_match_exact() {
        // Full path matches exactly
        assert!(glob_match("src/main.rs", "src/main.rs"));
        // Pattern without `/` matches the filename (gitignore convention)
        assert!(glob_match("src/main.rs", "main.rs"));
        // Pattern with `/` requires path match
        assert!(!glob_match("src/main.rs", "lib/main.rs"));
    }

    #[test]
    fn test_allowlist_empty_rule_never_matches() {
        // A rule with no criteria at all should never suppress anything.
        // This prevents misconfigured rules from acting as wildcards.
        let rule = AllowlistRule {
            description: None,
            secret_types: vec![],
            paths: vec![],
            value_regex: None,
            severities: vec![],
        };
        assert!(rule.has_no_criteria());
        assert!(!rule.matches("AWS Access Key", "src/config.rs", "AKIAIOSFODNN7REAL", "CRITICAL"));
        assert!(!rule.matches("GitHub PAT", "any/path", "any_value", "HIGH"));
    }

    #[test]
    fn test_deny_unknown_fields_rejects_typos() {
        // If a user writes `secret_type` (singular) instead of `secret_types`,
        // deserialization must fail rather than silently ignoring the field.
        let bad_toml = r#"
            [[allowlist]]
            secret_type = "Generic High Entropy"
            file_path = "*.lock"
        "#;
        let result: std::result::Result<Config, _> = toml::from_str(bad_toml);
        assert!(
            result.is_err(),
            "Config with unknown fields should fail to parse"
        );
    }
}