Skip to main content

lean_ctx/core/sensitivity/
classify.rs

1//! Classification + redaction helpers for the sensitivity model.
2//!
3//! Only high-precision signals raise a level, to avoid false positives:
4//! - secret-like paths ([`is_secret_like`]) and detected secrets → `Secret`
5//! - Luhn-validated card numbers and mod-97-validated IBANs → `Confidential`
6
7use std::path::Path;
8use std::sync::OnceLock;
9
10use regex::Regex;
11
12use super::SensitivityLevel;
13use crate::core::{io_boundary, secret_detection};
14
15/// Classify a source path. Secret-like paths (keys, `.env`, `.ssh/…`) → `Secret`.
16/// Everything else stays `Public` — path alone is not enough to infer lower
17/// confidential levels without guessing.
18pub fn classify_path(path: &Path) -> SensitivityLevel {
19    if io_boundary::is_secret_like(path).is_some() {
20        SensitivityLevel::Secret
21    } else {
22        SensitivityLevel::Public
23    }
24}
25
26/// Classify free text by content.
27pub fn classify_content(content: &str) -> SensitivityLevel {
28    if !secret_detection::detect_secrets(content).is_empty() {
29        return SensitivityLevel::Secret;
30    }
31    if has_credit_card(content) || has_iban(content) {
32        return SensitivityLevel::Confidential;
33    }
34    SensitivityLevel::Public
35}
36
37/// Combined classification: the maximum of path- and content-derived levels.
38pub fn classify(path: Option<&Path>, content: &str) -> SensitivityLevel {
39    let from_path = path.map(classify_path).unwrap_or_default();
40    from_path.max(classify_content(content))
41}
42
43/// Redact the spans that raise sensitivity: known secrets (via the config-driven
44/// scanner) plus PII (card numbers, IBANs) the secret scanner does not cover.
45pub(super) fn redact_sensitive(text: &str) -> String {
46    // Force redaction on regardless of the global `secret_detection` toggle: a
47    // sensitivity floor must always mask, not merely detect.
48    let forced = crate::core::config::SecretDetectionConfig {
49        enabled: true,
50        redact: true,
51        ..Default::default()
52    };
53    let (secrets_masked, _) = secret_detection::scan_and_redact(text, &forced);
54    let cards_masked = redact_credit_cards(&secrets_masked);
55    redact_ibans(&cards_masked)
56}
57
58// ---- Card numbers (Luhn) ---------------------------------------------------
59
60fn card_re() -> &'static Regex {
61    static RE: OnceLock<Regex> = OnceLock::new();
62    RE.get_or_init(|| Regex::new(r"\b\d(?:[ -]?\d){12,18}\b").expect("valid card regex"))
63}
64
65/// Luhn checksum over decimal digits. Length 13–19 (standard PAN range).
66fn luhn_valid(digits: &[u8]) -> bool {
67    if digits.len() < 13 || digits.len() > 19 {
68        return false;
69    }
70    let mut sum = 0u32;
71    let mut double = false;
72    for &d in digits.iter().rev() {
73        if d > 9 {
74            return false;
75        }
76        let mut v = d as u32;
77        if double {
78            v *= 2;
79            if v > 9 {
80                v -= 9;
81            }
82        }
83        sum += v;
84        double = !double;
85    }
86    sum.is_multiple_of(10)
87}
88
89fn digits_of(s: &str) -> Vec<u8> {
90    s.chars()
91        .filter(char::is_ascii_digit)
92        .map(|c| c as u8 - b'0')
93        .collect()
94}
95
96/// A card-shaped (see `card_layout_plausible`), Luhn-valid candidate.
97fn is_card(candidate: &str) -> bool {
98    crate::core::input_filters::pii::card_layout_plausible(candidate)
99        && luhn_valid(&digits_of(candidate))
100}
101
102fn has_credit_card(content: &str) -> bool {
103    card_re().find_iter(content).any(|m| is_card(m.as_str()))
104}
105
106fn redact_credit_cards(text: &str) -> String {
107    card_re()
108        .replace_all(text, |caps: &regex::Captures| {
109            let m = caps.get(0).map(|x| x.as_str()).unwrap_or_default();
110            if is_card(m) {
111                "[REDACTED:card]".to_string()
112            } else {
113                m.to_string()
114            }
115        })
116        .into_owned()
117}
118
119// ---- IBANs (ISO 7064 mod-97) ----------------------------------------------
120
121fn iban_re() -> &'static Regex {
122    static RE: OnceLock<Regex> = OnceLock::new();
123    RE.get_or_init(|| {
124        Regex::new(r"\b[A-Za-z]{2}\d{2}[A-Za-z0-9]{11,30}\b").expect("valid iban regex")
125    })
126}
127
128/// Validate an IBAN candidate via the ISO 7064 mod-97 checksum.
129fn iban_valid(candidate: &str) -> bool {
130    let s: String = candidate.chars().filter(|c| !c.is_whitespace()).collect();
131    if s.len() < 15 || s.len() > 34 {
132        return false;
133    }
134    if !s.is_char_boundary(4) {
135        return false;
136    }
137    // Move the first four characters to the end, then map letters A..Z -> 10..35.
138    let rearranged = format!("{}{}", &s[4..], &s[..4]);
139    let mut rem: u32 = 0;
140    for c in rearranged.chars() {
141        if let Some(d) = c.to_digit(10) {
142            rem = (rem * 10 + d) % 97;
143        } else if c.is_ascii_alphabetic() {
144            let val = (c.to_ascii_uppercase() as u8 - b'A' + 10) as u32;
145            rem = (rem * 100 + val) % 97;
146        } else {
147            return false;
148        }
149    }
150    rem == 1
151}
152
153fn has_iban(content: &str) -> bool {
154    iban_re().find_iter(content).any(|m| iban_valid(m.as_str()))
155}
156
157fn redact_ibans(text: &str) -> String {
158    iban_re()
159        .replace_all(text, |caps: &regex::Captures| {
160            let m = caps.get(0).map(|x| x.as_str()).unwrap_or_default();
161            if iban_valid(m) {
162                "[REDACTED:iban]".to_string()
163            } else {
164                m.to_string()
165            }
166        })
167        .into_owned()
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn secret_content_is_secret() {
176        // GitHub token shape is detected by secret_detection.
177        let t = concat!("export TOKEN=gh", "p_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
178        assert_eq!(classify_content(t), SensitivityLevel::Secret);
179    }
180
181    #[test]
182    fn benign_content_is_public() {
183        assert_eq!(
184            classify_content("the quick brown fox jumps over 12 lazy dogs"),
185            SensitivityLevel::Public
186        );
187    }
188
189    #[test]
190    fn luhn_valid_card_is_confidential() {
191        // 4111 1111 1111 1111 is the canonical Visa test number (Luhn-valid).
192        assert_eq!(
193            classify_content("card: 4111 1111 1111 1111 on file"),
194            SensitivityLevel::Confidential
195        );
196    }
197
198    #[test]
199    fn random_16_digits_not_flagged_unless_luhn() {
200        // 1234567890123456 is NOT Luhn-valid → must stay public.
201        assert_eq!(
202            classify_content("order id 1234567890123456"),
203            SensitivityLevel::Public
204        );
205    }
206
207    #[test]
208    fn valid_iban_is_confidential() {
209        // DE89 3704 0044 0532 0130 00 is a well-known valid test IBAN.
210        assert_eq!(
211            classify_content("pay to DE89370400440532013000 now"),
212            SensitivityLevel::Confidential
213        );
214    }
215
216    #[test]
217    fn invalid_iban_not_flagged() {
218        assert_eq!(
219            classify_content("ref DE00370400440532013000"),
220            SensitivityLevel::Public
221        );
222    }
223
224    #[test]
225    fn redact_masks_card_and_iban_keeps_text() {
226        let red = redact_sensitive("card 4111 1111 1111 1111 iban DE89370400440532013000 end");
227        assert!(red.contains("[REDACTED:card]"));
228        assert!(red.contains("[REDACTED:iban]"));
229        assert!(red.contains("end"));
230        assert!(!red.contains("4111 1111 1111 1111"));
231    }
232
233    #[test]
234    fn timestamped_names_are_not_cards_even_when_luhn_valid() {
235        let stamp = (0..10)
236            .map(|d| format!("20261006-16153{d}"))
237            .find(|s| luhn_valid(&digits_of(s)))
238            .expect("one check digit makes the stamp Luhn-valid");
239        let text = format!("session {stamp} archived");
240        assert!(!has_credit_card(&text));
241        assert_eq!(redact_credit_cards(&text), text);
242    }
243
244    #[test]
245    fn secret_like_path_is_secret() {
246        assert_eq!(
247            classify_path(Path::new("/home/u/.ssh/id_rsa")),
248            SensitivityLevel::Secret
249        );
250        assert_eq!(
251            classify_path(Path::new("src/main.rs")),
252            SensitivityLevel::Public
253        );
254    }
255
256    #[test]
257    fn classify_takes_max_of_path_and_content() {
258        // Benign content but secret path → Secret.
259        assert_eq!(
260            classify(Some(Path::new("/x/.env")), "PORT=8080"),
261            SensitivityLevel::Secret
262        );
263    }
264}