lean_ctx_cloud/knowledge/
screening_exceptions.rs1use std::borrow::Cow;
22use std::sync::OnceLock;
23
24use regex::Regex;
25
26pub const STRIPE_TEST_CARDS: [&str; 17] = [
30 concat!("4242", "4242", "4242", "4242"), concat!("4000", "0566", "5566", "5556"), concat!("5555", "5555", "5555", "4444"), concat!("2223", "0031", "2200", "3222"), concat!("5200", "8282", "8282", "8210"), concat!("5105", "1051", "0510", "5100"), concat!("3782", "8224", "6310", "005"), concat!("3714", "4963", "5398", "431"), concat!("6011", "1111", "1111", "1117"), concat!("6011", "0009", "9013", "9424"), concat!("6011", "9811", "1111", "1113"), concat!("3056", "9300", "0902", "0004"), concat!("3622", "7206", "2716", "67"), concat!("3566", "0020", "2036", "0505"), concat!("6200", "0000", "0000", "0005"), concat!("6200", "0000", "0000", "0047"), concat!("6205", "5000", "0000", "0000", "004"), ];
48
49pub 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
64fn 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
78fn code_span_re() -> &'static Regex {
80 static RE: OnceLock<Regex> = OnceLock::new();
81 regex(&RE, r"`[^`\n]+`")
82}
83
84fn marker_re() -> &'static Regex {
86 static RE: OnceLock<Regex> = OnceLock::new();
87 regex(&RE, r"\[REDACTED[^\]\n]*\]")
88}
89
90fn 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 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
143fn is_value_char(c: char) -> bool {
146 c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '_' | '-')
147}
148
149pub 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 struct Case {
228 input: String,
229 detector: String,
230 hit: bool,
231 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 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 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}