返回 CodeWhale
sanitize.rs
根目录 / crates / sanitize / src / sanitize.rs
1 //! Pure output-sanitization primitives shared by portable command helpers
2 //! (FEAT-025 D4).
3 //!
4 //! These helpers previously lived in the TUI command, client, and OSC8
5 //! modules. Relocating the pure algorithms here gives `/export` and
6 //! `/structcopy` exactly one implementation with no TUI, client, or
7 //! configuration dependency. TUI callers delegate back to these functions so
8 //! behavior cannot drift.
9
10 use std::sync::OnceLock;
11
12 use icu_properties::CodePointSetData;
13 use icu_properties::props::{
14 BidiControl, DefaultIgnorableCodePoint, EmojiModifier, ExtendedPictographic, VariationSelector,
15 };
16 use regex::Regex;
17 use serde_json::Value;
18
19 use crate::redact::redact_secrets;
20
21 /// Strip ANSI/OSC/control sequences from `s` into `out`.
22 ///
23 /// Handles CSI (`ESC [ … final`), OSC (`ESC ] … BEL` or `ESC \`), DCS, SOS,
24 /// PM, APC, and standalone two-byte ESC sequences. OSC 8 hyperlink wrappers
25 /// (`ESC ] 8 ; … BEL` / `ESC \`) are stripped along with the rest.
26 pub fn strip_ansi_into(s: &str, out: &mut String) {
27 strip_ansi_impl(s, &mut |text| out.push_str(text), false);
28 }
29
30 /// Drop control bytes from a streaming text chunk, keeping printable
31 /// characters, `\n` and `\t`. The terminal UI applies it to every streamed
32 /// chunk before rendering; notification payloads apply it after stripping
33 /// whole escape sequences.
34 #[must_use]
35 pub fn sanitize_stream_chunk(chunk: &str) -> String {
36 chunk
37 .chars()
38 .filter(|c| *c == '\n' || *c == '\t' || !c.is_control())
39 .collect()
40 }
41
42 /// Unicode Bidi_Control: the marks, embeddings, overrides and isolates that reorder how a line is displayed.
43 #[must_use]
44 pub fn is_bidi_control(ch: char) -> bool {
45 !ch.is_ascii() && CodePointSetData::new::<BidiControl>().contains(ch)
46 }
47
48 /// `(char index, char)` for each character a reader cannot see: controls other than tab, newline and carriage return, U+2028/U+2029, Bidi_Control and Default_Ignorable code points, except a zero-width joiner inside an emoji sequence, one variation selector after a visible non-ASCII base or in a keycap, and tag characters forming an emoji subdivision flag; visible lookalikes and the non-ignorable format characters U+FFF9-U+FFFB and U+13430-U+1343F are not reported.
49 #[must_use]
50 pub fn hidden_chars(text: &str) -> Vec<(usize, char)> {
51 let pictographic = CodePointSetData::new::<ExtendedPictographic>();
52 let modifier = CodePointSetData::new::<EmojiModifier>();
53 let selector = CodePointSetData::new::<VariationSelector>();
54 let ignorable = CodePointSetData::new::<DefaultIgnorableCodePoint>();
55 let is_tag = |ch: char| matches!(ch, '\u{e0020}'..='\u{e007f}');
56 let chars: Vec<char> = text.chars().collect();
57 let mut hidden = Vec::new();
58 let mut index = 0;
59 while index < chars.len() {
60 let ch = chars[index];
61 if matches!(ch, '\t' | '\n' | '\r' | ' '..='~') {
62 index += 1;
63 continue;
64 }
65 let previous = index.checked_sub(1).map(|at| chars[at]);
66 let next = chars.get(index + 1).copied();
67 if is_tag(ch) {
68 let end = chars[index..]
69 .iter()
70 .position(|&ch| !is_tag(ch))
71 .map_or(chars.len(), |len| index + len);
72 let run = &chars[index..end];
73 let flag = previous == Some('\u{1f3f4}')
74 && run.len() > 1
75 && run.last() == Some(&'\u{e007f}')
76 && run[..run.len() - 1]
77 .iter()
78 .all(|ch| matches!(ch, '\u{e0030}'..='\u{e0039}' | '\u{e0061}'..='\u{e007a}'));
79 if !flag {
80 hidden.extend((index..end).map(|at| (at, chars[at])));
81 }
82 index = end;
83 continue;
84 }
85 let visible = if ch == '\u{200d}' {
86 previous.is_some_and(|p| {
87 pictographic.contains(p) || modifier.contains(p) || p == '\u{fe0f}'
88 }) && next.is_some_and(|n| pictographic.contains(n))
89 } else if selector.contains(ch) {
90 previous.is_some_and(|p| {
91 !p.is_ascii() && !p.is_whitespace() && !p.is_control() && !ignorable.contains(p)
92 }) || (ch == '\u{fe0f}'
93 && previous.is_some_and(|p| matches!(p, '0'..='9' | '#' | '*'))
94 && next == Some('\u{20e3}'))
95 } else {
96 !(ch.is_control()
97 || matches!(ch, '\u{2028}' | '\u{2029}')
98 || is_bidi_control(ch)
99 || ignorable.contains(ch))
100 };
101 if !visible {
102 hidden.push((index, ch));
103 }
104 index += 1;
105 }
106 hidden
107 }
108
109 /// Like [`strip_ansi_into`], but SGR sequences (`ESC [ … m`: colour, bold,
110 /// underline, reset) pass through untouched so a renderer that understands
111 /// them can paint the output as the tool emitted it. Everything else — OSC
112 /// (including OSC 8 hyperlink wrappers), cursor movement, DCS, lone control
113 /// bytes — is still removed; only the styling survives.
114 pub fn strip_ansi_keep_sgr_into(s: &str, out: &mut String) {
115 strip_ansi_impl(s, &mut |text| out.push_str(text), true);
116 }
117
118 /// Length in bytes of the UTF-8 sequence that starts with `lead`. Falls back
119 /// to `1` for continuation bytes / invalid leads so callers always make
120 /// forward progress.
121 pub fn utf8_seq_len(lead: u8) -> usize {
122 if lead < 0xc0 {
123 1
124 } else if lead < 0xe0 {
125 2
126 } else if lead < 0xf0 {
127 3
128 } else {
129 4
130 }
131 }
132
133 #[expect(
134 missing_docs,
135 reason = "Callback form of the existing documented ANSI scanner"
136 )]
137 pub fn visit_ansi_text(s: &str, mut emit: impl FnMut(&str)) {
138 strip_ansi_impl(s, &mut emit, false);
139 }
140
141 fn strip_ansi_impl(s: &str, out: &mut impl FnMut(&str), keep_sgr: bool) {
142 let bytes = s.as_bytes();
143 let mut i = 0;
144 while i < bytes.len() {
145 if bytes[i] == 0x1b && i + 1 < bytes.len() {
146 let next = bytes[i + 1];
147 match next {
148 // CSI: ESC [ ... <final byte 0x40..=0x7E>
149 b'[' => {
150 let mut j = i + 2;
151 let mut final_byte = 0u8;
152 while j < bytes.len() {
153 let b = bytes[j];
154 if (0x40..=0x7e).contains(&b) {
155 final_byte = b;
156 j += 1;
157 break;
158 }
159 if !(0x20..=0x3f).contains(&b) {
160 break;
161 }
162 j += 1;
163 }
164 if keep_sgr
165 && final_byte == b'm'
166 && let Ok(seq) = std::str::from_utf8(&bytes[i..j])
167 {
168 out(seq);
169 }
170 i = j;
171 continue;
172 }
173 // OSC / DCS / SOS / PM / APC: ESC ] | P | X | ^ | _ ... ST(ESC \) or BEL
174 b']' | b'P' | b'X' | b'^' | b'_' => {
175 let mut j = i + 2;
176 while j < bytes.len() {
177 if bytes[j] == 0x07 {
178 j += 1;
179 break;
180 }
181 if bytes[j] == 0x1b && j + 1 < bytes.len() && bytes[j + 1] == b'\\' {
182 j += 2;
183 break;
184 }
185 j += 1;
186 }
187 i = j;
188 continue;
189 }
190 // Other ESC sequences: intermediates, then a final byte (RIS, charset selection)
191 _ => {
192 let mut j = i + 1;
193 while j < bytes.len() && (0x20..=0x2f).contains(&bytes[j]) {
194 j += 1;
195 }
196 if j < bytes.len() && (0x30..=0x7e).contains(&bytes[j]) {
197 j += 1;
198 }
199 i = j;
200 continue;
201 }
202 }
203 }
204 let b = bytes[i];
205 if b < 0x20 && b != b'\n' && b != b'\r' && b != b'\t' {
206 i += 1;
207 continue;
208 }
209 let run_start = i;
210 while i < bytes.len() {
211 let b = bytes[i];
212 if b == 0x1b || (b < 0x20 && b != b'\n' && b != b'\r' && b != b'\t') {
213 break;
214 }
215 i += if b < 0x80 { 1 } else { utf8_seq_len(b) };
216 }
217 if i > run_start {
218 out(&s[run_start..i]);
219 }
220 }
221 }
222
223 /// Mask credentials in a URL so it can appear in output or a report.
224 ///
225 /// Userinfo is replaced with `***` and query values under sensitive keys are
226 /// masked. Malformed URL-shaped strings fall back to a deterministic scrubber
227 /// so invalid percent-encoding or syntax cannot bypass redaction.
228 pub fn redact_url_for_display(url: &str) -> String {
229 let Ok(mut parsed) = url::Url::parse(url) else {
230 return redact_malformed_url_for_display(url);
231 };
232 if !parsed.username().is_empty() || parsed.password().is_some() {
233 let _ = parsed.set_username("***");
234 let _ = parsed.set_password(Some("***"));
235 }
236 if parsed.query().is_none() {
237 return parsed.to_string();
238 }
239 let pairs: Vec<(String, String)> = parsed
240 .query_pairs()
241 .map(|(key, value)| {
242 let value = if is_sensitive_url_query_key(&key) {
243 "***".to_string()
244 } else {
245 value.into_owned()
246 };
247 (key.into_owned(), value)
248 })
249 .collect();
250 parsed.set_query(None);
251 let mut query = parsed.query_pairs_mut();
252 for (key, value) in pairs {
253 query.append_pair(&key, &value);
254 }
255 drop(query);
256 parsed.to_string()
257 }
258
259 fn redact_malformed_url_for_display(url: &str) -> String {
260 let Some(scheme_end) = url.find("://") else {
261 return url.to_string();
262 };
263 let scheme = &url[..scheme_end + 3];
264 let after_scheme = &url[scheme_end + 3..];
265 let authority_end = after_scheme
266 .find(['/', '?', '#'])
267 .unwrap_or(after_scheme.len());
268 let (authority, suffix) = after_scheme.split_at(authority_end);
269 let masked_authority = match authority.rfind('@') {
270 Some(at_pos) => format!("***:***@{}", &authority[at_pos + 1..]),
271 None => authority.to_string(),
272 };
273 let (before_fragment, fragment) = match suffix.find('#') {
274 Some(pos) => (&suffix[..pos], Some(&suffix[pos..])),
275 None => (suffix, None),
276 };
277 let (path, query) = match before_fragment.find('?') {
278 Some(pos) => (&before_fragment[..pos], Some(&before_fragment[pos + 1..])),
279 None => (before_fragment, None),
280 };
281 let mut out = String::with_capacity(url.len());
282 out.push_str(scheme);
283 out.push_str(&masked_authority);
284 out.push_str(path);
285 if let Some(raw_query) = query {
286 out.push('?');
287 for (idx, pair) in raw_query.split('&').enumerate() {
288 if idx > 0 {
289 out.push('&');
290 }
291 if let Some((key, _)) = pair.split_once('=')
292 && is_sensitive_url_query_key(key)
293 {
294 out.push_str(key);
295 out.push_str("=***");
296 } else {
297 out.push_str(pair);
298 }
299 }
300 }
301 if let Some(frag) = fragment {
302 out.push_str(frag);
303 }
304 out
305 }
306
307 fn malformed_url_has_credentials(url: &str) -> bool {
308 let Some(scheme_end) = url.find("://") else {
309 return false;
310 };
311 let after_scheme = &url[scheme_end + 3..];
312 let authority_end = after_scheme
313 .find(['/', '?', '#'])
314 .unwrap_or(after_scheme.len());
315 let (authority, suffix) = after_scheme.split_at(authority_end);
316 if authority.contains('@') {
317 return true;
318 }
319 let before_fragment = suffix.split('#').next().unwrap_or("");
320 let Some((_, raw_query)) = before_fragment.split_once('?') else {
321 return false;
322 };
323 raw_query.split('&').any(|pair| {
324 pair.split_once('=')
325 .is_some_and(|(key, _)| is_sensitive_url_query_key(key))
326 })
327 }
328
329 fn is_sensitive_url_query_key(key: &str) -> bool {
330 is_sensitive_key_name(key)
331 }
332
333 /// True when `role` names an internal, non-user-visible message role.
334 pub fn is_internal_role(role: &str) -> bool {
335 matches!(
336 role.trim().to_ascii_lowercase().as_str(),
337 "system" | "developer" | "internal"
338 )
339 }
340
341 /// Credential names shared by config, URL and JSON output checks.
342 const SENSITIVE_KEY_NAMES: &[&str] = &[
343 "access_key",
344 "access_token",
345 "api_key",
346 "api_keys",
347 "apikey",
348 "auth_token",
349 "authorization",
350 "bearer",
351 "client_secret",
352 "cookie",
353 "credential",
354 "credentials",
355 "id_token",
356 "passwd",
357 "password",
358 "passwords",
359 "private_key",
360 "proxy_authorization",
361 "refresh_token",
362 "secret",
363 "secrets",
364 "session_key",
365 "set_cookie",
366 "sas",
367 "token",
368 "tokens",
369 ];
370
371 /// Use the existing text redactor's identifier normalization, including
372 /// camelCase and acronym boundaries, instead of maintaining another parser.
373 #[must_use]
374 pub fn normalize_key(key: &str) -> String {
375 crate::redact::normalize_sensitive_key(key)
376 }
377
378 fn key_spellings(key: &str) -> [String; 2] {
379 [normalize_key(key), normalize_key(&key.to_ascii_lowercase())]
380 }
381
382 /// Precise credential check for settings, headers and flags. Usage settings
383 /// such as max_tokens and token_budget remain visible.
384 #[must_use]
385 pub fn is_sensitive_key_name(key: &str) -> bool {
386 key_spellings(key).iter().any(|normalized| {
387 SENSITIVE_KEY_NAMES.contains(&normalized.as_str())
388 || ["_authorization", "_cookie", "_passwd", "_password", "_secret", "_token"]
389 .iter().any(|suffix| normalized.ends_with(suffix))
390 // Retain config's subscription-key and custom key protection.
391 || (normalized.ends_with("_key")
392 && !matches!(normalized.as_str(), "public_key" | "endpoint_key"))
393 })
394 }
395
396 /// Broad export check; model-bound text keeps its existing credential-shaped
397 /// policy in redact.rs. One shared normalization handles every spelling.
398 #[must_use]
399 pub fn is_sensitive_key(key: &str) -> bool {
400 is_sensitive_key_name(key)
401 || key_spellings(key).iter().any(|normalized| {
402 [
403 "api_key",
404 "apikey",
405 "secret",
406 "token",
407 "password",
408 "passwd",
409 "authorization",
410 "access_key",
411 "client_secret",
412 "private_key",
413 "cookie",
414 "session_key",
415 ]
416 .iter()
417 .any(|hint| normalized.contains(hint))
418 })
419 }
420
421 /// Sanitize arbitrary text for safe export output.
422 ///
423 /// Strips ANSI/control bytes, normalizes newlines, then applies private-key,
424 /// bearer-token, JWT, URL-credential, and keyed-secret redaction in the exact
425 /// established order.
426 pub fn sanitize_text(input: &str) -> String {
427 let mut visible = String::with_capacity(input.len());
428 strip_ansi_into(input, &mut visible);
429 let visible = if visible.as_bytes().contains(&b'\r') {
430 visible.replace("\r\n", "\n").replace('\r', "\n")
431 } else {
432 visible
433 };
434 let visible = if visible
435 .chars()
436 .any(|ch| ch != '\n' && ch != '\t' && ch.is_control())
437 {
438 visible
439 .chars()
440 .filter(|ch| *ch == '\n' || *ch == '\t' || !ch.is_control())
441 .collect()
442 } else {
443 visible
444 };
445 let private_keys = private_key_regex().replace_all(&visible, "[redacted private key]");
446 let bearer = bearer_regex().replace_all(&private_keys, "Bearer [redacted]");
447 let jwt = jwt_regex().replace_all(&bearer, "[redacted token]");
448 let urls = url_regex().replace_all(&jwt, |captures: &regex::Captures<'_>| {
449 redact_url_match(captures.get(0).map_or("", |value| value.as_str()))
450 });
451 redact_secrets(&urls)
452 }
453
454 /// Whether an arbitrary value carries material the shared redactor masks.
455 /// Formatting-only changes (URL canonicalization, newlines, ANSI) do not make
456 /// a harmless config value a credential.
457 #[must_use]
458 pub fn contains_secret(input: &str) -> bool {
459 let mut visible = String::with_capacity(input.len());
460 strip_ansi_into(input, &mut visible);
461 private_key_regex().is_match(&visible)
462 || bearer_regex().is_match(&visible)
463 || jwt_regex().is_match(&visible)
464 || redact_secrets(&visible) != visible
465 || url_regex().find_iter(&visible).any(|matched| {
466 let raw = matched.as_str().trim_end_matches(['.', ',', ';', '!']);
467 match url::Url::parse(raw) {
468 Ok(url) => {
469 !url.username().is_empty()
470 || url.password().is_some()
471 || url
472 .query_pairs()
473 .any(|(key, _)| is_sensitive_url_query_key(&key))
474 }
475 Err(_) => malformed_url_has_credentials(raw),
476 }
477 })
478 }
479
480 /// Recursively redact a JSON value.
481 ///
482 /// A value under a sensitive key is replaced wholesale; other strings pass
483 /// through [`sanitize_text`], and arrays/objects are traversed in place.
484 pub fn redact_json(value: &mut Value, key: Option<&str>) {
485 if key.is_some_and(is_sensitive_key) {
486 *value = Value::String("[redacted]".to_string());
487 return;
488 }
489 match value {
490 Value::String(text) => *text = sanitize_text(text),
491 Value::Array(items) => {
492 for item in items {
493 redact_json(item, None);
494 }
495 }
496 Value::Object(map) => {
497 for (key, value) in map {
498 redact_json(value, Some(key));
499 }
500 }
501 Value::Null | Value::Bool(_) | Value::Number(_) => {}
502 }
503 }
504
505 /// Collapse whitespace and neutralize inline backticks for a single-line
506 /// export field.
507 pub fn inline_text(input: &str) -> String {
508 sanitize_text(input)
509 .split_whitespace()
510 .collect::<Vec<_>>()
511 .join(" ")
512 .replace('`', "'")
513 }
514
515 fn redact_url_match(raw: &str) -> String {
516 let trimmed = raw.trim_end_matches(['.', ',', ';', '!']);
517 let suffix = &raw[trimmed.len()..];
518 format!("{}{}", redact_url_for_display(trimmed), suffix)
519 }
520
521 fn private_key_regex() -> &'static Regex {
522 static RE: OnceLock<Regex> = OnceLock::new();
523 RE.get_or_init(|| {
524 Regex::new(
525 r"(?is)-----BEGIN [^-\r\n]*PRIVATE KEY-----.*?-----END [^-\r\n]*PRIVATE KEY-----",
526 )
527 .expect("private-key redaction regex")
528 })
529 }
530
531 fn bearer_regex() -> &'static Regex {
532 static RE: OnceLock<Regex> = OnceLock::new();
533 RE.get_or_init(|| {
534 Regex::new(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{6,}").expect("bearer redaction regex")
535 })
536 }
537
538 fn jwt_regex() -> &'static Regex {
539 static RE: OnceLock<Regex> = OnceLock::new();
540 RE.get_or_init(|| {
541 Regex::new(r"\beyJ[a-zA-Z0-9_-]{5,}\.[a-zA-Z0-9_-]{5,}(?:\.[a-zA-Z0-9_-]{5,})?\b")
542 .expect("JWT redaction regex")
543 })
544 }
545
546 fn url_regex() -> &'static Regex {
547 static RE: OnceLock<Regex> = OnceLock::new();
548 RE.get_or_init(|| {
549 Regex::new(r#"https?://[^\s<>\"'`\]\[\)\(\}\{]+"#).expect("URL redaction regex")
550 })
551 }
552
553 #[cfg(test)]
554 mod tests {
555 use super::*;
556
557 #[test]
558 fn shared_vocabulary_redacts_camel_case_and_keeps_safe_key_names() {
559 for key in [
560 "accessToken",
561 "clientSecret",
562 "privateKey",
563 "refreshToken",
564 "APIKey",
565 "X-API-Key",
566 "sessionKey",
567 "oauth2Token",
568 "aUtHoRiZaTiOn",
569 "Ocp-Apim-Subscription-Key",
570 "Set-Cookie",
571 "sas",
572 ] {
573 assert!(is_sensitive_key_name(key), "{key}");
574 let mut value = serde_json::json!({key: "s10-synthetic-value"});
575 redact_json(&mut value, None);
576 assert!(!value.to_string().contains("s10-synthetic-value"), "{key}");
577 }
578 for key in [
579 "max_tokens",
580 "token_budget",
581 "maxTokens",
582 "api_key_source",
583 "authMode",
584 "publicKey",
585 "endpoint_key",
586 "monkey",
587 ] {
588 assert!(!is_sensitive_key_name(key), "{key}");
589 }
590 assert_eq!(normalize_key("APIKey"), "api_key");
591 }
592
593 #[test]
594 fn shared_secret_detection_preserves_formatting_only_config_values() {
595 for safe in [
596 "https://api.example.com",
597 "https://api.example.com/v1?team=core",
598 "https://api.example.com/?tokenBudget=5",
599 "normal text",
600 "max tokens = 8192",
601 "tokenCount = 4",
602 ] {
603 assert!(!contains_secret(safe), "safe value classified as secret");
604 }
605 for secret in [
606 "clientSecret=opaque-value",
607 "https://alice:opaque-value@example.com",
608 "https://example.com/?privateKey=opaque-value",
609 "https://example.com/?sas=opaque-value",
610 ] {
611 assert!(contains_secret(secret), "credential not classified");
612 }
613 assert_ne!(
614 sanitize_text("https://api.example.com"),
615 "https://api.example.com"
616 );
617 }
618
619 #[test]
620 fn strip_ansi_removes_control_sequences_but_keeps_text() {
621 let mut out = String::new();
622 strip_ansi_into("a\u{1b}[31mred\u{1b}[0m b", &mut out);
623 assert_eq!(out, "ared b");
624 }
625
626 #[test]
627 fn strip_ansi_consumes_whole_escape_sequences_and_keeps_following_text() {
628 for (input, expected) in [
629 ("\u{1b}(Bok\u{1b}[m", "ok"),
630 ("\u{1b}#8x", "x"),
631 ("a\u{1b}\u{1b}[31mb", "ab"),
632 ("\u{1b}[中文", "中文"),
633 ("\u{1b}中", "中"),
634 ] {
635 let mut out = String::new();
636 strip_ansi_into(input, &mut out);
637 assert_eq!(out, expected, "{input:?}");
638 }
639 let mut kept = String::new();
640 strip_ansi_keep_sgr_into("\u{1b}[\u{1b}(0m\u{1b}[1mx", &mut kept);
641 assert_eq!(kept, "m\u{1b}[1mx");
642 }
643
644 #[test]
645 fn url_redaction_masks_userinfo_and_sensitive_query_values() {
646 assert_eq!(
647 redact_url_for_display(
648 "https://alice:password@example.com/path?token=very-secret&ok=1"
649 ),
650 "https://***:***@example.com/path?token=***&ok=1"
651 );
652 }
653
654 #[test]
655 fn url_redaction_masks_malformed_url_userinfo_and_query_values() {
656 let malformed = "https://alice:pass%zz@example.com:notaport/x?token=very-secret&ok=1#frag";
657 assert!(url::Url::parse(malformed).is_err());
658 assert_eq!(
659 redact_url_for_display(malformed),
660 "https://***:***@example.com:notaport/x?token=***&ok=1#frag"
661 );
662 let sanitized = sanitize_text(&format!("see {malformed}"));
663 assert!(!sanitized.contains("alice"), "{sanitized}");
664 assert!(!sanitized.contains("pass%zz"), "{sanitized}");
665 assert!(!sanitized.contains("very-secret"), "{sanitized}");
666 assert!(sanitized.contains("ok=1"), "{sanitized}");
667 assert!(contains_secret(malformed));
668 }
669
670 #[test]
671 fn sensitive_keys_normalize_separators_and_quotes() {
672 assert!(is_sensitive_key("API-KEY"));
673 assert!(is_sensitive_key("\"client secret\""));
674 assert!(!is_sensitive_key("monkey"));
675 }
676
677 #[test]
678 fn sanitize_text_redacts_private_keys_bearer_and_jwt() {
679 // Assemble the PEM markers and the provider-token prefix at runtime so
680 // this source file never contains a literal private-key header (or a
681 // literal token) for a secret scanner to match. The runtime strings are
682 // identical to the real shapes, and this mirrors the convention the
683 // pre-move test used in `config::persistence` - moving that test into
684 // this crate silently dropped it, which is what GitGuardian caught.
685 let begin = ["-----BEGIN RSA", " PRIVATE KEY-----"].concat();
686 let end = ["-----END RSA", " PRIVATE KEY-----"].concat();
687 let bearer = format!("{} abcdefghijklmnop", "Bearer");
688 let opaque = ["sk-", "abcdef1234567890"].concat();
689 let text = format!("{begin}\nMII\n{end}\nAuthorization: {bearer}\n{opaque}");
690
691 let out = sanitize_text(&text);
692 assert!(!out.contains("MII"), "{out}");
693 assert!(!out.contains("abcdefghijklmnop"), "{out}");
694 assert!(out.contains("[redacted]"), "{out}");
695 }
696 }
697
697 lines RUST