Skip to main content

lean_ctx_cloud/knowledge/
screening_exceptions.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Narrow screening exceptions (owner decision 03.11.2026), identical in the
3//! LeanCTX instance and the Cloud server (`cloud-screen/src/exceptions.rs`). C0
4//! `vectors/screening_exceptions.vectors.json` is their single source; a test
5//! below asserts every case.
6//!
7//! [`neutralise`] replaces exactly four shapes with neutral words before the
8//! vendored scanners run, so those files stay byte for byte the engine's:
9//!
10//! - an `Authorization: Bearer|Basic` header whose value is only a
11//!   documentation placeholder (`…`, `...`, `<name>`, `[REDACTED…]`, a run of
12//!   3+ `x`/`X`, `$NAME`, `${…}`, `{name}`, or a lowercase token-type prefix
13//!   elided with `…`/`...`, e.g. `cloud_p_…`);
14//! - one of Stripe's documented test card numbers (digits compared exactly,
15//!   separators ignored, no prefix rule);
16//! - a whole token `ed25519-<32 lowercase hex>`, `sha256:`/`blake3:`/`sha256-`
17//!   followed by 64 lowercase hex (bounded by no secret-value character);
18//! - a redaction marker `[REDACTED…]` inside a one-line backtick code span,
19//!   where docs show the marker's format (it holds no secret either way).
20
21use std::borrow::Cow;
22use std::sync::OnceLock;
23
24use regex::Regex;
25
26/// Stripe's documented test card numbers (stripe.com/docs/testing, "Card
27/// numbers" by brand), digits only. Assembled from groups so the source
28/// never carries a contiguous card number.
29pub const STRIPE_TEST_CARDS: [&str; 17] = [
30    concat!("4242", "4242", "4242", "4242"),        // Visa
31    concat!("4000", "0566", "5566", "5556"),        // Visa (debit)
32    concat!("5555", "5555", "5555", "4444"),        // Mastercard
33    concat!("2223", "0031", "2200", "3222"),        // Mastercard (2-series)
34    concat!("5200", "8282", "8282", "8210"),        // Mastercard (debit)
35    concat!("5105", "1051", "0510", "5100"),        // Mastercard (prepaid)
36    concat!("3782", "8224", "6310", "005"),         // American Express
37    concat!("3714", "4963", "5398", "431"),         // American Express
38    concat!("6011", "1111", "1111", "1117"),        // Discover
39    concat!("6011", "0009", "9013", "9424"),        // Discover
40    concat!("6011", "9811", "1111", "1113"),        // Discover (debit)
41    concat!("3056", "9300", "0902", "0004"),        // Diners Club
42    concat!("3622", "7206", "2716", "67"),          // Diners Club (14-digit)
43    concat!("3566", "0020", "2036", "0505"),        // JCB
44    concat!("6200", "0000", "0000", "0005"),        // UnionPay
45    concat!("6200", "0000", "0000", "0047"),        // UnionPay (debit)
46    concat!("6205", "5000", "0000", "0000", "004"), // UnionPay (19-digit)
47];
48
49/// Whether `candidate` (any separators) is one of [`STRIPE_TEST_CARDS`].
50pub fn is_stripe_test_card(candidate: &str) -> bool {
51    let digits: String = candidate.chars().filter(char::is_ascii_digit).collect();
52    STRIPE_TEST_CARDS.contains(&digits.as_str())
53}
54
55fn regex(slot: &'static OnceLock<Regex>, pattern: &str) -> &'static Regex {
56    slot.get_or_init(|| Regex::new(pattern).expect("static exception pattern"))
57}
58
59fn authorization_prefix_re() -> &'static Regex {
60    static RE: OnceLock<Regex> = OnceLock::new();
61    regex(&RE, r"(?i)authorization[ \t]*:[ \t]*(?:bearer|basic)[ \t]+")
62}
63
64/// The card candidate of `pii.rs`.
65fn card_candidate_re() -> &'static Regex {
66    static RE: OnceLock<Regex> = OnceLock::new();
67    regex(&RE, r"(?-u:\b)\d(?:[ -]?\d){12,18}(?-u:\b)")
68}
69
70fn digest_re() -> &'static Regex {
71    static RE: OnceLock<Regex> = OnceLock::new();
72    regex(
73        &RE,
74        r"ed25519-[0-9a-f]{32}|(?:sha256|blake3):[0-9a-f]{64}|sha256-[0-9a-f]{64}",
75    )
76}
77
78/// A one-line backtick code span.
79fn code_span_re() -> &'static Regex {
80    static RE: OnceLock<Regex> = OnceLock::new();
81    regex(&RE, r"`[^`\n]+`")
82}
83
84/// A redaction marker up to its `]` on the same line.
85fn marker_re() -> &'static Regex {
86    static RE: OnceLock<Regex> = OnceLock::new();
87    regex(&RE, r"\[REDACTED[^\]\n]*\]")
88}
89
90/// The length of the placeholder at the start of `rest` (the text after
91/// `Authorization: Bearer `), or `None` for a real-looking value.
92fn placeholder_len(rest: &str) -> Option<usize> {
93    if rest.starts_with("[REDACTED") {
94        let line = rest.split('\n').next().unwrap_or("");
95        return line.find(']').map(|i| i + 1);
96    }
97    let token = rest
98        .split(|c: char| c.is_whitespace() || matches!(c, '`' | '"' | '\'' | ',' | ';' | ')'))
99        .next()
100        .unwrap_or("");
101    is_placeholder_token(token).then_some(token.len())
102}
103
104fn is_placeholder_token(token: &str) -> bool {
105    if matches!(token, "…" | "...") {
106        return true;
107    }
108    if token.len() >= 3 && token.bytes().all(|b| matches!(b, b'x' | b'X')) {
109        return true;
110    }
111    let wrapped = |open: &str, close: char, forbidden: &[char]| {
112        token
113            .strip_prefix(open)
114            .and_then(|t| t.strip_suffix(close))
115            .is_some_and(|inner| !inner.is_empty() && !inner.contains(forbidden))
116    };
117    if wrapped("<", '>', &['<', '>']) || wrapped("${", '}', &['{', '}']) {
118        return true;
119    }
120    if wrapped("{", '}', &['{', '}']) {
121        return true;
122    }
123    if let Some(name) = token.strip_prefix('$') {
124        let mut chars = name.chars();
125        return chars
126            .next()
127            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
128            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
129    }
130    // A token-type prefix without its body: `cloud_p_…`, `cloud_scim_...`.
131    // `sk_live_51H…` (digits, uppercase) is no such prefix and still hits.
132    if let Some(prefix) = token
133        .strip_suffix('…')
134        .or_else(|| token.strip_suffix("..."))
135    {
136        return prefix.ends_with('_')
137            && prefix.starts_with(|c: char| c.is_ascii_lowercase())
138            && prefix.bytes().all(|b| b.is_ascii_lowercase() || b == b'_');
139    }
140    false
141}
142
143/// A character a key/value secret value can contain: a digest bounded by
144/// one is not the whole token.
145fn is_value_char(c: char) -> bool {
146    c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '_' | '-')
147}
148
149/// `text` with every excepted span replaced by a neutral word; borrowed when
150/// there is none.
151pub fn neutralise(text: &str) -> Cow<'_, str> {
152    let mut spans: Vec<(usize, usize, &str)> = Vec::new();
153    for m in authorization_prefix_re().find_iter(text) {
154        if let Some(len) = placeholder_len(&text[m.end()..]) {
155            spans.push((m.start(), m.end() + len, "auth-placeholder"));
156        }
157    }
158    for m in card_candidate_re().find_iter(text) {
159        if is_stripe_test_card(m.as_str()) {
160            spans.push((m.start(), m.end(), "test-card"));
161        }
162    }
163    for m in digest_re().find_iter(text) {
164        let before = text[..m.start()].chars().next_back();
165        let after = text[m.end()..].chars().next();
166        if !before.is_some_and(is_value_char) && !after.is_some_and(is_value_char) {
167            spans.push((m.start(), m.end(), "digest"));
168        }
169    }
170    for span in code_span_re().find_iter(text) {
171        for m in marker_re().find_iter(span.as_str()) {
172            spans.push((
173                span.start() + m.start(),
174                span.start() + m.end(),
175                "redaction-marker",
176            ));
177        }
178    }
179    if spans.is_empty() {
180        return Cow::Borrowed(text);
181    }
182    spans.sort_unstable();
183    let mut out = String::with_capacity(text.len());
184    let mut at = 0;
185    for (start, end, word) in spans {
186        if start < at {
187            continue;
188        }
189        out.push_str(&text[at..start]);
190        out.push_str(word);
191        at = end;
192    }
193    out.push_str(&text[at..]);
194    Cow::Owned(out)
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    fn luhn_valid(digits: &str) -> bool {
202        let mut sum = 0u32;
203        for (i, d) in digits.bytes().rev().enumerate() {
204            let mut x = u32::from(d - b'0');
205            if i % 2 == 1 {
206                x *= 2;
207                if x > 9 {
208                    x -= 9;
209                }
210            }
211            sum += x;
212        }
213        sum.is_multiple_of(10)
214    }
215
216    #[test]
217    fn stripe_test_cards_are_real_luhn_valid_card_numbers() {
218        for card in STRIPE_TEST_CARDS {
219            assert!(card.bytes().all(|b| b.is_ascii_digit()), "{}", card.len());
220            assert!((14..=19).contains(&card.len()), "{}", card.len());
221            assert!(luhn_valid(card), "a Stripe test card fails Luhn");
222            assert!(is_stripe_test_card(card));
223        }
224    }
225
226    /// One case of the C0 vector file (one compact object per line).
227    struct Case {
228        input: String,
229        detector: String,
230        hit: bool,
231        /// Dogfood lines: the whole screen must pass them.
232        source: Option<String>,
233    }
234
235    fn unescape(s: &str) -> String {
236        let mut out = String::new();
237        let mut chars = s.chars();
238        while let Some(c) = chars.next() {
239            if c != '\\' {
240                out.push(c);
241                continue;
242            }
243            match chars.next() {
244                Some('n') => out.push('\n'),
245                Some('t') => out.push('\t'),
246                Some('u') => {
247                    let code: String = chars.by_ref().take(4).collect();
248                    let n = u32::from_str_radix(&code, 16).expect("\\u escape");
249                    out.push(char::from_u32(n).expect("BMP scalar"));
250                }
251                Some(other) => out.push(other),
252                None => panic!("dangling escape"),
253            }
254        }
255        out
256    }
257
258    fn cases() -> Vec<Case> {
259        let text = include_str!(concat!(
260            env!("CARGO_MANIFEST_DIR"),
261            "/../lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/screening_exceptions.vectors.json"
262        ));
263        let re = Regex::new(
264            r#"\{"input": "((?:[^"\\]|\\.)*)", "detector": "([a-z_]+)", "hit": (true|false)(?:, "source": "([^"]+)")?\}"#,
265        )
266        .unwrap();
267        let cases: Vec<Case> = re
268            .captures_iter(text)
269            .map(|c| Case {
270                input: unescape(&c[1]),
271                detector: c[2].to_string(),
272                hit: &c[3] == "true",
273                source: c.get(4).map(|s| s.as_str().to_string()),
274            })
275            .collect();
276        assert_eq!(
277            cases.len(),
278            text.matches("{\"input\":").count(),
279            "every case parses"
280        );
281        assert!(cases.len() > 30);
282        cases
283    }
284
285    /// Whether `detector` (or its redaction twin) fires on `input` after the
286    /// exceptions.
287    fn fires(detector: &str, input: &str) -> bool {
288        let text = neutralise(input);
289        let secrets = lean_ctx::core::secret_detection::detect_secrets(&text);
290        let named = |names: &[&str]| secrets.iter().any(|m| names.contains(&m.pattern_name));
291        let redacted = lean_ctx::core::redaction::redact_text(&text);
292        let masked = |labels: &[&str]| {
293            labels
294                .iter()
295                .any(|l| redacted.contains(&format!("[REDACTED:{l}]")))
296        };
297        match detector {
298            "authorization_header" => {
299                named(&["authorization_header"]) || masked(&["Authorization header"])
300            }
301            "card" => lean_ctx::core::input_filters::pii::detect(&text)
302                .iter()
303                .any(|(k, _)| *k == "card"),
304            "high_entropy_secret" => {
305                named(&[
306                    "generic_api_key",
307                    "high_entropy_secret",
308                    "url_encoded_secret",
309                ]) || masked(&["Generic long secret", "API key param", "URL-encoded secret"])
310            }
311            "redaction_marker" => text.contains("[REDACTED"),
312            other => panic!("unknown detector {other}"),
313        }
314    }
315
316    #[test]
317    fn screening_exception_vectors() {
318        let cases = cases();
319        // Indices only in messages: the inputs carry card numbers.
320        let mut failures = Vec::new();
321        for (i, case) in cases.iter().enumerate() {
322            if fires(&case.detector, &case.input) != case.hit {
323                failures.push(format!("case {i} ({}): hit != {}", case.detector, case.hit));
324            }
325            if let Some(source) = &case.source
326                && crate::knowledge::screening::Screen::with_rules(
327                    Vec::new(),
328                    std::sync::Arc::new(Vec::new()),
329                    Vec::new(),
330                )
331                .check(&case.input)
332                .is_err()
333            {
334                failures.push(format!("case {i} ({source}): the screen refuses it"));
335            }
336        }
337        assert!(failures.is_empty(), "{failures:#?}");
338        for card in STRIPE_TEST_CARDS {
339            assert!(
340                cases.iter().any(|c| c.detector == "card"
341                    && !c.hit
342                    && card_candidate_re().find_iter(&c.input).any(|m| {
343                        m.as_str()
344                            .chars()
345                            .filter(char::is_ascii_digit)
346                            .collect::<String>()
347                            == card
348                    })),
349                "a Stripe card ({} digits) has no vector",
350                card.len()
351            );
352        }
353        assert!(cases.iter().filter(|c| c.source.is_some()).count() >= 7);
354    }
355
356    #[test]
357    fn without_exceptions_the_dogfood_lines_were_refused() {
358        let refused = cases()
359            .iter()
360            .filter(|c| c.source.is_some())
361            .filter(|c| {
362                lean_ctx::core::secret_detection::detect_secrets(&c.input).len()
363                    + usize::from(lean_ctx::core::redaction::redact_text(&c.input) != c.input)
364                    + lean_ctx::core::input_filters::pii::detect(&c.input).len()
365                    > 0
366            })
367            .count();
368        assert!(refused >= 4, "{refused}");
369    }
370}