Skip to main content

macfly_core/
dlp.rs

1use std::collections::BTreeMap;
2use std::sync::LazyLock;
3
4use regex::Regex;
5
6use crate::config::DlpConfig;
7
8struct Rule {
9    name: &'static str,
10    label: &'static str,
11    regex: Regex,
12}
13
14static RULES: LazyLock<Vec<Rule>> = LazyLock::new(|| {
15    vec![
16        Rule {
17            name: "private_key",
18            label: "PRIVATE_KEY",
19            regex: Regex::new(
20                r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?-----END [A-Z0-9 ]*PRIVATE KEY-----",
21            )
22            .expect("valid private_key regex"),
23        },
24        Rule {
25            name: "api_key",
26            label: "API_KEY",
27            regex: Regex::new(
28                r"\b(?:sk-[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35}|xox[baprs]-[0-9A-Za-z-]{10,})\b",
29            )
30            .expect("valid api_key regex"),
31        },
32        Rule {
33            name: "iban",
34            label: "IBAN",
35            regex: Regex::new(r"\b[A-Z]{2}\d{2}(?:[ ]?[A-Z0-9]{4}){3,7}(?:[ ]?[A-Z0-9]{1,4})?\b")
36                .expect("valid iban regex"),
37        },
38        Rule {
39            name: "credit_card",
40            label: "CREDIT_CARD",
41            regex: Regex::new(r"\b(?:\d{4}[ -]){3}\d{4}\b").expect("valid credit_card regex"),
42        },
43        Rule {
44            name: "otp_code",
45            label: "OTP_CODE",
46            regex: Regex::new(
47                r"(?i)\b(?:otp|tan|2fa|verification code|sicherheitscode|bestätigungscode|code)\s*[:#-]?\s*\d{6}\b",
48            )
49            .expect("valid otp_code regex"),
50        },
51    ]
52});
53
54#[derive(Debug, Clone)]
55pub struct RedactionResult {
56    pub text: String,
57    pub counts: BTreeMap<String, usize>,
58    pub truncated: bool,
59}
60
61pub fn apply_dlp(input: &str, cfg: &DlpConfig) -> RedactionResult {
62    let mut text = input.to_string();
63    let mut counts = BTreeMap::new();
64
65    if cfg.enabled {
66        for rule in RULES.iter() {
67            if !cfg.redact.iter().any(|r| r.eq_ignore_ascii_case(rule.name)) {
68                continue;
69            }
70            let mut hit_count = 0usize;
71            let replaced = rule.regex.replace_all(&text, |_: &regex::Captures<'_>| {
72                hit_count += 1;
73                format!("[REDACTED:{}_{}]", rule.label, hit_count)
74            });
75            if hit_count > 0 {
76                text = replaced.into_owned();
77                counts.insert(rule.name.to_string(), hit_count);
78            }
79        }
80    }
81
82    let mut truncated = false;
83    if cfg.max_body_chars > 0 && text.chars().count() > cfg.max_body_chars {
84        text = text.chars().take(cfg.max_body_chars).collect::<String>();
85        text.push_str("\n… [gekürzt durch max_body_chars]");
86        truncated = true;
87    }
88
89    RedactionResult {
90        text,
91        counts,
92        truncated,
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn redacts_iban_api_key_and_otp() {
102        let cfg = DlpConfig::default();
103        let sample = "Überweise an DE89 3704 0044 0532 0130 00. Key: sk-proj1234567890abcdefghij. Sicherheitscode: 482910.";
104        let res = apply_dlp(sample, &cfg);
105        assert!(res.text.contains("[REDACTED:IBAN_1]"));
106        assert!(res.text.contains("[REDACTED:API_KEY_1]"));
107        assert!(res.text.contains("[REDACTED:OTP_CODE_1]"));
108        assert_eq!(res.counts.get("iban"), Some(&1));
109        assert_eq!(res.counts.get("api_key"), Some(&1));
110        assert_eq!(res.counts.get("otp_code"), Some(&1));
111        assert!(!res.truncated);
112    }
113
114    #[test]
115    fn respects_disabled_dlp() {
116        let cfg = DlpConfig {
117            enabled: false,
118            ..DlpConfig::default()
119        };
120        let sample = "DE89 3704 0044 0532 0130 00";
121        let res = apply_dlp(sample, &cfg);
122        assert_eq!(res.text, sample);
123        assert!(res.counts.is_empty());
124    }
125}