返回 CodeWhale
redaction.rs
根目录 / crates / workflow / src / redaction.rs
1 //! Redaction for anything that can reach a log, a span, or a durable receipt.
2 //!
3 //! Two classes of content are stripped before text is allowed to leave the
4 //! process — either onto a provider's wire or into a journal:
5 //!
6 //! 1. **Absolute paths.** `/Users/hunter/src/app`, `/home/x/...`, `C:\Users\…`
7 //! and `~/…` carry the operator's username, home directory, and machine
8 //! layout. A journal travels further than the machine that wrote it.
9 //! 2. **Repo-relative paths.** `crates/tui/src/main.rs`, `./deploy.sh`,
10 //! `../../secret/notes.md` — and their escaped spellings, `crates\/tui\/…`
11 //! and `crates\\tui\\…`. An absolute path discloses the machine; a relative
12 //! one discloses the private tree's shape, which is exactly as much as the
13 //! reader of a routing summary at another provider needs to reconstruct it.
14 //! The rule is deliberately conservative — see `looks_relative` — because
15 //! the failure it must not trade for is mangling ordinary prose or a
16 //! `provider/model` label.
17 //! 3. **Secret-shaped tokens.** Provider keys, bearer tokens, and
18 //! `SOMETHING_KEY=value` assignments. These have no business in a routing
19 //! summary and must never be persisted next to one.
20 //!
21 //! Redaction is *recorded*, not silent: [`Redaction::kinds`] names what was
22 //! removed so a receipt can disclose the fact without disclosing the content.
23
24 use std::collections::BTreeSet;
25
26 /// A redaction kind, as it appears on a disclosure. These are stable labels —
27 /// receipts persist them.
28 pub const REDACTION_ABSOLUTE_PATH: &str = "absolute_path";
29 pub const REDACTION_RELATIVE_PATH: &str = "relative_path";
30 pub const REDACTION_SECRET: &str = "secret";
31
32 /// Placeholder substituted for a removed absolute path.
33 const PATH_PLACEHOLDER: &str = "<path>";
34 /// Placeholder substituted for a removed secret-shaped token.
35 const SECRET_PLACEHOLDER: &str = "<redacted>";
36
37 const SECRET_NAME_MARKERS: &[&str] = &[
38 "api_key",
39 "apikey",
40 "secret",
41 "token",
42 "password",
43 "passwd",
44 "credential",
45 "authorization",
46 "auth_token",
47 "access_key",
48 "private_key",
49 "session_key",
50 ];
51
52 /// HTTP authorization scheme keywords, in their canonical HTTP capitalization.
53 ///
54 /// These are *never* the secret — the secret is the token that follows them.
55 /// Redacting the keyword and stopping there is the failure this list exists to
56 /// prevent: `Authorization: Bearer <token>` would keep the token and still
57 /// claim on the receipt that a secret had been removed.
58 ///
59 /// The capitalization is stored, not normalized away, because it carries
60 /// evidence: `Bearer` is HTTP syntax and `bearer` is an English noun. See
61 /// [`is_canonical_auth_scheme`].
62 const AUTH_SCHEMES: &[&str] = &["Bearer", "Basic", "Digest", "Token"];
63
64 /// The one scheme keyword whose canonical capitalization is, by itself, enough
65 /// to treat the following token as a credential.
66 ///
67 /// The asymmetry is deliberate and is the whole of the false-positive story.
68 /// `Basic`, `Digest`, and `Token` are ordinary capitalized English words —
69 /// "Basic auth is enabled", "Token holders vote", "Digest the results" — and
70 /// arming on them would redact the next word of perfectly ordinary prose. `Bearer`
71 /// capitalized is, in a technical corpus, the HTTP scheme essentially every
72 /// time. So `Bearer qqq` loses `qqq` even though a three-letter lowercase token
73 /// looks like nothing at all, while the other three need header context first.
74 ///
75 /// The residual cost is stated plainly: `Bearer tokens are rotated weekly`
76 /// redacts `tokens`. That is a capitalized-`Bearer` sentence, which is header
77 /// syntax by shape; ordinary prose says "bearer", and lowercase never arms on
78 /// its own.
79 const SELF_EVIDENT_AUTH_SCHEME: &str = "Bearer";
80
81 /// Minimum length before a bare token is treated as a credential value.
82 const CREDENTIAL_VALUE_MIN_LEN: usize = 16;
83
84 /// The result of redacting one string.
85 #[derive(Debug, Clone, PartialEq, Eq)]
86 pub struct Redaction {
87 text: String,
88 kinds: BTreeSet<String>,
89 }
90
91 impl Redaction {
92 /// The redacted text.
93 #[must_use]
94 pub fn text(&self) -> &str {
95 &self.text
96 }
97
98 /// Consume the redaction, yielding the redacted text.
99 #[must_use]
100 pub fn into_text(self) -> String {
101 self.text
102 }
103
104 /// Whether anything was removed.
105 #[must_use]
106 pub fn redacted(&self) -> bool {
107 !self.kinds.is_empty()
108 }
109
110 /// Which classes of content were removed — never the content itself.
111 #[must_use]
112 pub fn kinds(&self) -> Vec<String> {
113 self.kinds.iter().cloned().collect()
114 }
115 }
116
117 /// How strongly the preceding tokens claim that the *next* token is a
118 /// credential.
119 ///
120 /// A credential is routinely written as two or three tokens
121 /// (`Authorization: Bearer <token>`), so the decision cannot be made per token.
122 /// But the evidence for "a credential follows" is not uniform, and collapsing it
123 /// to a boolean is what produces either a leak or a mangled sentence:
124 ///
125 /// - `Authorization: Bearer qqq` — the credential is `qqq`, three lowercase
126 /// letters, indistinguishable in shape from a word. Only the *context* says
127 /// it is a secret, and the context says so unambiguously.
128 /// - `authorization: bearer shares responsibility` — the same context markers,
129 /// lowercase, and the next token is an English verb. Redacting `shares` would
130 /// destroy a sentence and put a false `secret` kind on a receipt.
131 ///
132 /// So the arming carries its own strength, and the shape test is applied only
133 /// where the context is weak enough to need it.
134 #[derive(Clone, Copy, PartialEq, Eq)]
135 enum CredentialArm {
136 /// Nothing is expected; the next token is judged on its own.
137 None,
138 /// The next token is the credential only if it also *looks* like one.
139 /// Lowercase scheme words and bare `Authorization:` land here.
140 IfShaped,
141 /// The next token is the credential whatever it looks like. Reached by
142 /// canonical HTTP capitalization — `Authorization: Bearer …`, or a bare
143 /// `Bearer` — where the syntax alone settles it.
144 Certain,
145 }
146
147 impl CredentialArm {
148 const fn is_armed(self) -> bool {
149 !matches!(self, Self::None)
150 }
151 }
152
153 /// What one token resolved to, and whether it armed the *next* token.
154 struct TokenOutcome {
155 /// `None` keeps the token verbatim.
156 text: Option<String>,
157 /// Whether — and how strongly — the following token carries the credential
158 /// this one introduced. `Authorization:` and a bare `Bearer` reveal nothing
159 /// themselves; the value after them is the whole secret.
160 arm: CredentialArm,
161 }
162
163 impl TokenOutcome {
164 const fn keep() -> Self {
165 Self {
166 text: None,
167 arm: CredentialArm::None,
168 }
169 }
170
171 const fn keep_and_arm(arm: CredentialArm) -> Self {
172 Self { text: None, arm }
173 }
174
175 fn replace(text: String) -> Self {
176 Self {
177 text: Some(text),
178 arm: CredentialArm::None,
179 }
180 }
181
182 fn replace_and_arm(text: String, arm: CredentialArm) -> Self {
183 Self {
184 text: Some(text),
185 arm,
186 }
187 }
188 }
189
190 #[derive(Clone, Copy, PartialEq, Eq)]
191 enum ContainerMode {
192 Array,
193 Object,
194 TupleOrMap,
195 }
196
197 impl ContainerMode {
198 fn from_open(open: char) -> Option<Self> {
199 match open {
200 '[' => Some(Self::Array),
201 '{' => Some(Self::Object),
202 '(' => Some(Self::TupleOrMap),
203 _ => None,
204 }
205 }
206
207 const fn close(self) -> char {
208 match self {
209 Self::Array => ']',
210 Self::Object => '}',
211 Self::TupleOrMap => ')',
212 }
213 }
214
215 const fn accepts_object_keys(self) -> bool {
216 matches!(self, Self::Object | Self::TupleOrMap)
217 }
218
219 const fn expects_values(self) -> bool {
220 matches!(self, Self::Array | Self::TupleOrMap)
221 }
222 }
223
224 #[derive(Clone, Copy)]
225 struct ArmedContainer {
226 mode: ContainerMode,
227 arm: CredentialArm,
228 }
229
230 const MAX_CONTAINER_DEPTH: usize = 64;
231 const MAX_NESTED_ASSIGNMENT_DEPTH: u8 = 3;
232
233 fn push_container_if_opening(
234 containers: &mut Vec<ArmedContainer>,
235 open: char,
236 arm: CredentialArm,
237 ) -> CredentialArm {
238 let Some(mode) = ContainerMode::from_open(open) else {
239 return arm;
240 };
241 if containers.len() < MAX_CONTAINER_DEPTH {
242 containers.push(ArmedContainer { mode, arm });
243 if mode.expects_values() {
244 arm
245 } else {
246 CredentialArm::None
247 }
248 } else {
249 arm
250 }
251 }
252
253 fn pop_containers_for(containers: &mut Vec<ArmedContainer>, text: &str) {
254 for ch in text.chars() {
255 if matches!(ch, ']' | '}' | ')')
256 && let Some(pos) = containers.iter().rposition(|c| c.mode.close() == ch)
257 {
258 containers.truncate(pos);
259 }
260 }
261 }
262
263 fn container_restore_arm(containers: &[ArmedContainer]) -> CredentialArm {
264 containers
265 .last()
266 .filter(|c| c.mode.expects_values())
267 .map_or(CredentialArm::None, |c| c.arm)
268 }
269
270 fn is_container_object_key(token: &str) -> bool {
271 let Some(key) = token.strip_suffix(':') else {
272 return false;
273 };
274 !key.is_empty()
275 && !key.ends_with("://")
276 && !key.contains(['=', ':'])
277 && !token.contains(STRUCTURAL_DELIMITERS)
278 && !codewhale_sanitize::redact::contains_bare_secret_token(key)
279 }
280
281 fn trailing_secret_suffix(token: &str) -> (&str, &str) {
282 let head = token.trim_end_matches([',', ']', '}', ')']);
283 (head, &token[head.len()..])
284 }
285
286 /// Redact absolute paths and secret-shaped tokens from `input`.
287 ///
288 /// Operates token-by-token over whitespace-free runs, which is enough for the
289 /// bounded, already whitespace-collapsed text this crate transmits and keeps
290 /// the rule set auditable without a regex dependency.
291 ///
292 /// One piece of state crosses token boundaries, and it has to: a credential is
293 /// routinely written as *two* tokens (`Authorization: Bearer <token>`), so a
294 /// purely per-token rule either leaks the value or redacts the English word
295 /// `bearer`. Carrying "the next token is the credential" forward — and *how
296 /// certainly*, see `CredentialArm` — is what lets this do neither.
297 #[must_use]
298 pub fn redact_for_disclosure(input: &str) -> Redaction {
299 let mut kinds = BTreeSet::new();
300 let masked_keys = codewhale_sanitize::redact::mask_private_keys(input, SECRET_PLACEHOLDER);
301 if masked_keys.is_some() {
302 kinds.insert(REDACTION_SECRET.to_string());
303 }
304 let input = masked_keys.as_deref().unwrap_or(input);
305 let (tokens, seps) = split_whitespace_preserving(input);
306 let mut out: Vec<String> = Vec::with_capacity(tokens.len());
307 let mut arm = CredentialArm::None;
308 let mut containers: Vec<ArmedContainer> = Vec::new();
309 let mut pending_name: Option<(&str, CredentialArm)> = None;
310 let mut index = 0;
311
312 while index < tokens.len() {
313 let mut token = tokens[index];
314 if seps[index].contains(['\n', '\r']) {
315 pending_name = None;
316 }
317 let name = pending_name.take();
318 if !arm.is_armed()
319 && let Some(container) = containers.last().copied()
320 {
321 if token
322 .chars()
323 .all(|c| matches!(c, ']' | '}' | ')' | ',' | ';' | '"' | '\''))
324 {
325 pop_containers_for(&mut containers, token);
326 arm = container_restore_arm(&containers);
327 out.push(token.to_string());
328 index += 1;
329 continue;
330 }
331 if container.mode.accepts_object_keys() && is_container_object_key(token) {
332 arm = container.arm;
333 out.push(token.to_string());
334 index += 1;
335 continue;
336 }
337 }
338 if arm.is_armed() {
339 let lead_end = token
340 .find(|c: char| !matches!(c, '[' | '{' | '('))
341 .unwrap_or(token.len());
342 let (lead_brackets, rest_token) = token.split_at(lead_end);
343 let mut pushed_prefix = "";
344 if !lead_brackets.is_empty()
345 && rest_token
346 .chars()
347 .all(|c| matches!(c, '[' | '{' | '(' | '"' | '\''))
348 {
349 for ch in lead_brackets.chars() {
350 if ContainerMode::from_open(ch).is_some() {
351 arm = push_container_if_opening(&mut containers, ch, arm);
352 }
353 }
354 out.push(token.to_string());
355 index += 1;
356 continue;
357 }
358 if let Some(last_open) = lead_brackets
359 .chars()
360 .rev()
361 .find_map(ContainerMode::from_open)
362 {
363 let close = last_open.close();
364 if !rest_token.contains(close) {
365 for ch in lead_brackets.chars() {
366 if ContainerMode::from_open(ch).is_some() {
367 arm = push_container_if_opening(&mut containers, ch, arm);
368 }
369 }
370 pushed_prefix = lead_brackets;
371 token = rest_token;
372 if let Some(container) = containers.last().copied()
373 && container.mode.accepts_object_keys()
374 && is_container_object_key(token)
375 {
376 arm = container.arm;
377 out.push(format!("{pushed_prefix}{token}"));
378 index += 1;
379 continue;
380 }
381 }
382 }
383 if token
384 .chars()
385 .all(|c| matches!(c, ']' | '}' | ')' | ',' | ';' | '"' | '\''))
386 {
387 pop_containers_for(&mut containers, token);
388 arm = container_restore_arm(&containers);
389 out.push(format!("{pushed_prefix}{token}"));
390 index += 1;
391 continue;
392 }
393 if let Some(container) = containers.last().copied()
394 && container.mode.accepts_object_keys()
395 && is_container_object_key(token)
396 {
397 arm = container.arm;
398 out.push(format!("{pushed_prefix}{token}"));
399 index += 1;
400 continue;
401 }
402 // `Authorization: Bearer <token>` — the scheme keyword is not the
403 // secret, so it survives and the arming carries past it. A
404 // canonically capitalized keyword also *upgrades* the arming: the
405 // header name alone left the shape in doubt, and `Bearer` settles
406 // it.
407 if is_auth_scheme(token) {
408 if is_canonical_auth_scheme(token) {
409 arm = CredentialArm::Certain;
410 }
411 out.push(format!("{pushed_prefix}{token}"));
412 index += 1;
413 continue;
414 }
415 // Weak arming still defers to shape, so an `authorization:` that
416 // introduces a sentence rather than a secret leaves the sentence
417 // intact — and leaves the receipt honest about having removed
418 // nothing.
419 if arm == CredentialArm::Certain || looks_like_credential_value(token) {
420 let (value_part, suffix) = trailing_secret_suffix(token);
421 if !value_part.is_empty() {
422 kinds.insert(REDACTION_SECRET.to_string());
423 pop_containers_for(&mut containers, suffix);
424 arm = container_restore_arm(&containers);
425 out.push(format!("{pushed_prefix}{SECRET_PLACEHOLDER}{suffix}"));
426 index += 1;
427 continue;
428 }
429 }
430 // Fall through: the token is judged on its own merits, and the
431 // arming state is replaced wholesale by `redact_token` below.
432 }
433
434 if let Some((name, sensitivity)) = name
435 && name.starts_with('-')
436 && !token.starts_with(['-', '=', ':'])
437 && (sensitivity == CredentialArm::Certain || looks_like_credential_value(token))
438 {
439 kinds.insert(REDACTION_SECRET.to_string());
440 out.push(SECRET_PLACEHOLDER.to_string());
441 index += 1;
442 continue;
443 }
444
445 if let Some((name, sensitivity)) = name
446 && let Some(rest) = token
447 .strip_prefix([':', '='])
448 .map(|rest| rest.trim_start_matches(['=', '>']))
449 {
450 let separator = &token[..token.len() - rest.len()];
451 let weak = sensitivity == CredentialArm::IfShaped
452 || name.eq_ignore_ascii_case("authorization");
453 if rest.is_empty() {
454 arm = if weak {
455 CredentialArm::IfShaped
456 } else {
457 CredentialArm::Certain
458 };
459 out.push(token.to_string());
460 } else if is_auth_scheme(rest) {
461 arm = if is_canonical_auth_scheme(rest) {
462 CredentialArm::Certain
463 } else {
464 CredentialArm::IfShaped
465 };
466 out.push(token.to_string());
467 } else if !weak || looks_like_credential_value(rest) {
468 kinds.insert(REDACTION_SECRET.to_string());
469 arm = CredentialArm::None;
470 out.push(format!("{separator}{SECRET_PLACEHOLDER}"));
471 } else {
472 arm = CredentialArm::None;
473 out.push(token.to_string());
474 }
475 index += 1;
476 continue;
477 }
478
479 let next = tokens.get(index + 1).copied();
480 let outcome = redact_token(token, next, &mut kinds, &mut containers);
481 arm = outcome.arm;
482 if outcome.text.is_none() && !arm.is_armed() {
483 let chunk = codewhale_sanitize::redact::last_escaped_chunk(token);
484 let candidate = unwrap_token(chunk);
485 if !candidate.contains(['=', ':']) {
486 let sensitivity = name_sensitivity(candidate);
487 if sensitivity.is_armed() {
488 pending_name = Some((candidate, sensitivity));
489 }
490 }
491 }
492 out.push(outcome.text.unwrap_or_else(|| token.to_string()));
493 index += 1;
494 }
495
496 let mut text = String::with_capacity(input.len());
497 text.push_str(seps[0]);
498 for (idx, piece) in out.iter().enumerate() {
499 text.push_str(piece);
500 text.push_str(seps[idx + 1]);
501 }
502 Redaction { text, kinds }
503 }
504
505 fn split_whitespace_preserving(input: &str) -> (Vec<&str>, Vec<&str>) {
506 let mut tokens = Vec::new();
507 let mut seps = Vec::new();
508 let bytes = input.as_bytes();
509 let mut i = 0;
510 while i < bytes.len() {
511 let ws_start = i;
512 while i < bytes.len() && bytes[i].is_ascii_whitespace() {
513 i += 1;
514 }
515 seps.push(&input[ws_start..i]);
516 if i == bytes.len() {
517 return (tokens, seps);
518 }
519 let tok_start = i;
520 while i < bytes.len() && !bytes[i].is_ascii_whitespace() {
521 i += 1;
522 }
523 tokens.push(&input[tok_start..i]);
524 }
525 seps.push("");
526 (tokens, seps)
527 }
528
529 fn name_sensitivity(name: &str) -> CredentialArm {
530 match codewhale_sanitize::redact::key_sensitivity(name) {
531 codewhale_sanitize::redact::KeySensitivity::Certain => return CredentialArm::Certain,
532 codewhale_sanitize::redact::KeySensitivity::IfShaped => return CredentialArm::IfShaped,
533 codewhale_sanitize::redact::KeySensitivity::None => {}
534 }
535 let norm = codewhale_sanitize::redact::normalize_sensitive_key(name);
536 if SECRET_NAME_MARKERS
537 .iter()
538 .any(|marker| *marker != "token" && norm.contains(marker))
539 {
540 return CredentialArm::Certain;
541 }
542 CredentialArm::None
543 }
544
545 const STRUCTURAL_DELIMITERS: [char; 9] = [',', '(', ')', '[', ']', '{', '}', '&', '?'];
546
547 fn redact_backslash_chunk_workflow(
548 chunk: &str,
549 chunk_next: Option<&str>,
550 pending_arm: &mut CredentialArm,
551 kinds: &mut BTreeSet<String>,
552 depth: u8,
553 ) -> Option<String> {
554 if pending_arm.is_armed() {
555 let (core, lead_quote, trail_quote) = codewhale_sanitize::redact::split_value_quotes(chunk);
556 if !core.is_empty()
557 && (*pending_arm == CredentialArm::Certain || looks_like_credential_value(core))
558 {
559 *pending_arm = CredentialArm::None;
560 kinds.insert(REDACTION_SECRET.to_string());
561 return Some(format!("{lead_quote}{SECRET_PLACEHOLDER}{trail_quote}"));
562 }
563 *pending_arm = CredentialArm::None;
564 }
565 let outcome =
566 redact_assignment_segment_at(chunk, chunk_next, kinds, CredentialArm::None, depth);
567 *pending_arm = outcome.arm;
568 outcome.text
569 }
570
571 fn next_escaped_chunk_slice(rest: &str) -> &str {
572 let mut cursor = 0;
573 while let Some(rel) = rest[cursor..].find('\\') {
574 let idx = cursor + rel;
575 if codewhale_sanitize::redact::escape_delimiter_end(rest, idx).is_some() {
576 return &rest[..idx];
577 }
578 if rest[idx + 1..].starts_with('\\') {
579 cursor = idx + 2;
580 } else {
581 cursor = idx + 1;
582 }
583 }
584 rest
585 }
586
587 fn redact_workflow_backslash_assignments(
588 text: &str,
589 next: Option<&str>,
590 kinds: &mut BTreeSet<String>,
591 depth: u8,
592 ) -> TokenOutcome {
593 let mut out = String::new();
594 let mut changed = false;
595 let mut pending_arm = CredentialArm::None;
596 let mut chunk_start = 0;
597 let mut cursor = 0;
598 while let Some(rel) = text[cursor..].find('\\') {
599 let idx = cursor + rel;
600 if let Some(delim_end) = codewhale_sanitize::redact::escape_delimiter_end(text, idx) {
601 let chunk = &text[chunk_start..idx];
602 let chunk_next = Some(next_escaped_chunk_slice(&text[delim_end..]));
603 if !changed {
604 if let Some(redacted) = redact_backslash_chunk_workflow(
605 chunk,
606 chunk_next,
607 &mut pending_arm,
608 kinds,
609 depth,
610 ) {
611 out.reserve(text.len());
612 out.push_str(&text[..chunk_start]);
613 out.push_str(&redacted);
614 out.push_str(&text[idx..delim_end]);
615 changed = true;
616 }
617 } else {
618 if let Some(redacted) = redact_backslash_chunk_workflow(
619 chunk,
620 chunk_next,
621 &mut pending_arm,
622 kinds,
623 depth,
624 ) {
625 out.push_str(&redacted);
626 } else {
627 out.push_str(chunk);
628 }
629 out.push_str(&text[idx..delim_end]);
630 }
631 chunk_start = delim_end;
632 cursor = delim_end;
633 } else if text[idx + 1..].starts_with('\\') {
634 cursor = idx + 2;
635 } else {
636 cursor = idx + 1;
637 }
638 }
639 if chunk_start == 0 {
640 return TokenOutcome::keep();
641 }
642 let tail = &text[chunk_start..];
643 if let Some(redacted) =
644 redact_backslash_chunk_workflow(tail, next, &mut pending_arm, kinds, depth)
645 {
646 if !changed {
647 out.reserve(text.len());
648 out.push_str(&text[..chunk_start]);
649 }
650 out.push_str(&redacted);
651 changed = true;
652 } else if changed {
653 out.push_str(tail);
654 }
655 if changed {
656 TokenOutcome::replace_and_arm(out, pending_arm)
657 } else if pending_arm.is_armed() {
658 TokenOutcome::keep_and_arm(pending_arm)
659 } else {
660 TokenOutcome::keep()
661 }
662 }
663
664 fn redact_assignment_segment(
665 segment: &str,
666 next: Option<&str>,
667 kinds: &mut BTreeSet<String>,
668 container_arm: CredentialArm,
669 ) -> TokenOutcome {
670 redact_assignment_segment_at(segment, next, kinds, container_arm, 0)
671 }
672
673 fn redact_assignment_segment_at(
674 segment: &str,
675 next: Option<&str>,
676 kinds: &mut BTreeSet<String>,
677 container_arm: CredentialArm,
678 depth: u8,
679 ) -> TokenOutcome {
680 for separator in ['=', ':'] {
681 let Some((name, value)) = segment.split_once(separator) else {
682 continue;
683 };
684 let sensitivity = match name_sensitivity(name) {
685 CredentialArm::None => container_arm,
686 s => s,
687 };
688 if sensitivity.is_armed() {
689 if is_auth_scheme(value) {
690 return TokenOutcome::keep_and_arm(if is_canonical_auth_scheme(value) {
691 CredentialArm::Certain
692 } else {
693 CredentialArm::IfShaped
694 });
695 }
696 if value.is_empty() {
697 let weak = sensitivity == CredentialArm::IfShaped
698 || name.eq_ignore_ascii_case("authorization");
699 return if weak {
700 if next.is_some_and(|next| {
701 is_auth_scheme(next)
702 || looks_like_credential_value(next)
703 || next.starts_with(['[', '{', '('])
704 }) {
705 TokenOutcome::keep_and_arm(CredentialArm::IfShaped)
706 } else {
707 TokenOutcome::keep()
708 }
709 } else if next.is_some() {
710 TokenOutcome::keep_and_arm(CredentialArm::Certain)
711 } else {
712 TokenOutcome::keep()
713 };
714 }
715 if sensitivity == CredentialArm::Certain || looks_like_credential_value(value) {
716 kinds.insert(REDACTION_SECRET.to_string());
717 return TokenOutcome::replace(format!("{name}{separator}{SECRET_PLACEHOLDER}"));
718 }
719 }
720 if let Some(kind) = classify_path(value) {
721 kinds.insert(kind.to_string());
722 return TokenOutcome::replace(format!("{name}{separator}{PATH_PLACEHOLDER}"));
723 }
724 if depth < MAX_NESTED_ASSIGNMENT_DEPTH && !value.starts_with("//") {
725 let (core, lead_quote, trail_quote) =
726 codewhale_sanitize::redact::split_value_quotes(value);
727 if core.contains('\\') {
728 let nested = redact_workflow_backslash_assignments(core, next, kinds, depth + 1);
729 if let Some(replaced) = nested.text {
730 return TokenOutcome::replace_and_arm(
731 format!("{name}{separator}{lead_quote}{replaced}{trail_quote}"),
732 nested.arm,
733 );
734 }
735 if nested.arm.is_armed() {
736 return TokenOutcome::keep_and_arm(nested.arm);
737 }
738 }
739 if !core.contains("://") && core.contains(['=', ':']) {
740 let nested =
741 redact_assignment_segment_at(core, next, kinds, CredentialArm::None, depth + 1);
742 if let Some(replaced) = nested.text {
743 return TokenOutcome::replace_and_arm(
744 format!("{name}{separator}{lead_quote}{replaced}{trail_quote}"),
745 nested.arm,
746 );
747 }
748 if nested.arm.is_armed() {
749 return TokenOutcome::keep_and_arm(nested.arm);
750 }
751 }
752 }
753 }
754 TokenOutcome::keep()
755 }
756
757 fn redact_structured_token(
758 token: &str,
759 next: Option<&str>,
760 kinds: &mut BTreeSet<String>,
761 containers: &mut Vec<ArmedContainer>,
762 ) -> Option<TokenOutcome> {
763 if !token.contains(STRUCTURAL_DELIMITERS) || !token.contains(['=', ':']) {
764 return None;
765 }
766 let parts: Vec<(&str, &str)> = token
767 .split_inclusive(STRUCTURAL_DELIMITERS)
768 .map(|piece| match piece.chars().next_back() {
769 Some(last) if STRUCTURAL_DELIMITERS.contains(&last) => {
770 piece.split_at(piece.len() - last.len_utf8())
771 }
772 _ => (piece, ""),
773 })
774 .collect();
775 let mut out = String::with_capacity(token.len());
776 let mut changed = false;
777 let mut seg_arm = CredentialArm::None;
778 for (idx, &(segment, delim)) in parts.iter().enumerate() {
779 let mut delim_handled = false;
780 if !segment.is_empty() {
781 if seg_arm.is_armed() {
782 if is_auth_scheme(segment) {
783 if is_canonical_auth_scheme(segment) {
784 seg_arm = CredentialArm::Certain;
785 }
786 out.push_str(segment);
787 } else if seg_arm == CredentialArm::Certain || looks_like_credential_value(segment)
788 {
789 kinds.insert(REDACTION_SECRET.to_string());
790 out.push_str(SECRET_PLACEHOLDER);
791 changed = true;
792 seg_arm = CredentialArm::None;
793 } else {
794 out.push_str(segment);
795 seg_arm = CredentialArm::None;
796 }
797 } else {
798 let seg_next = parts[idx + 1..]
799 .iter()
800 .map(|&(seg, _)| seg)
801 .find(|seg| !seg.is_empty())
802 .or(next);
803 let container_arm = containers
804 .last()
805 .filter(|c| c.mode.accepts_object_keys())
806 .map_or(CredentialArm::None, |c| c.arm);
807 let outcome = redact_assignment_segment(segment, seg_next, kinds, container_arm);
808 if let Some(replaced) = outcome.text {
809 out.push_str(&replaced);
810 changed = true;
811 } else {
812 out.push_str(segment);
813 }
814 if outcome.arm.is_armed() {
815 seg_arm = outcome.arm;
816 }
817 }
818 }
819 if let Some(delim_char) = delim.chars().next() {
820 if ContainerMode::from_open(delim_char).is_some()
821 && (seg_arm.is_armed() || !containers.is_empty())
822 {
823 let push_arm = if seg_arm.is_armed() {
824 seg_arm
825 } else {
826 containers.last().map_or(CredentialArm::None, |c| c.arm)
827 };
828 if push_arm.is_armed() {
829 seg_arm = push_container_if_opening(containers, delim_char, push_arm);
830 delim_handled = true;
831 }
832 } else if matches!(delim_char, ']' | '}' | ')') {
833 pop_containers_for(containers, delim);
834 seg_arm = container_restore_arm(containers);
835 delim_handled = true;
836 } else if delim_char == ',' && !seg_arm.is_armed() {
837 seg_arm = container_restore_arm(containers);
838 delim_handled = true;
839 }
840 }
841 let _ = delim_handled;
842 out.push_str(delim);
843 }
844 if changed {
845 if let Some(masked) =
846 codewhale_sanitize::redact::mask_bare_secret_tokens(&out, SECRET_PLACEHOLDER)
847 {
848 kinds.insert(REDACTION_SECRET.to_string());
849 return Some(TokenOutcome {
850 text: Some(masked),
851 arm: seg_arm,
852 });
853 }
854 return Some(TokenOutcome {
855 text: Some(out),
856 arm: seg_arm,
857 });
858 }
859 if seg_arm.is_armed() {
860 return Some(TokenOutcome::keep_and_arm(seg_arm));
861 }
862 None
863 }
864
865 /// Redact one whitespace-free token, recording what was removed.
866 ///
867 /// `next` is the following non-empty token, used only to decide whether a bare
868 /// authorization scheme keyword is introducing a credential or is just a word.
869 fn redact_token(
870 token: &str,
871 next: Option<&str>,
872 kinds: &mut BTreeSet<String>,
873 containers: &mut Vec<ArmedContainer>,
874 ) -> TokenOutcome {
875 if let Some(outcome) = redact_structured_token(token, next, kinds, containers) {
876 return outcome;
877 }
878 // `NAME=value` / `NAME:value` — a secret-bearing name redacts its value and
879 // keeps the name, which is the useful half.
880 let container_arm = containers
881 .last()
882 .filter(|c| c.mode.accepts_object_keys())
883 .map_or(CredentialArm::None, |c| c.arm);
884 let outcome = redact_assignment_segment(token, next, kinds, container_arm);
885 if outcome.text.is_some() || outcome.arm.is_armed() {
886 return outcome;
887 }
888
889 // A bare `Bearer` in canonical HTTP capitalization introduces a credential
890 // on its own — that is what makes `Bearer qqq` lose `qqq`, which no shape
891 // test could ever do. Any other scheme keyword, and any other
892 // capitalization, needs something credential-shaped to actually follow:
893 // `bearer of bad news` and `Token holders vote` are prose.
894 if unwrap_token(token) == SELF_EVIDENT_AUTH_SCHEME {
895 return TokenOutcome::keep_and_arm(CredentialArm::Certain);
896 }
897 if is_auth_scheme(token) && next.is_some_and(looks_like_credential_value) {
898 return TokenOutcome::keep_and_arm(CredentialArm::IfShaped);
899 }
900
901 let secret = codewhale_sanitize::redact::mask_bare_secret_tokens(token, SECRET_PLACEHOLDER);
902
903 if let Some(kind) = classify_path(token) {
904 kinds.insert(kind.to_string());
905 if secret.is_some() {
906 kinds.insert(REDACTION_SECRET.to_string());
907 }
908 return TokenOutcome::replace(PATH_PLACEHOLDER.to_string());
909 }
910
911 if let Some(masked) = secret {
912 kinds.insert(REDACTION_SECRET.to_string());
913 return TokenOutcome::replace(masked);
914 }
915
916 TokenOutcome::keep()
917 }
918
919 /// Strip the punctuation a token picks up from surrounding prose.
920 fn unwrap_token(token: &str) -> &str {
921 token
922 .trim_start_matches(['(', '[', '{', '"', '\'', '<'])
923 .trim_end_matches([',', '.', ';', ':', ')', ']', '}', '"', '\'', '>', '!', '?'])
924 }
925
926 /// Whether a token is an HTTP authorization scheme keyword (and nothing else),
927 /// in any capitalization.
928 fn is_auth_scheme(token: &str) -> bool {
929 let word = unwrap_token(token);
930 !word.is_empty()
931 && word.chars().all(|ch| ch.is_ascii_alphabetic())
932 && AUTH_SCHEMES
933 .iter()
934 .any(|scheme| scheme.eq_ignore_ascii_case(word))
935 }
936
937 /// Whether a token is a scheme keyword spelled the way HTTP spells it —
938 /// `Bearer`, not `bearer` or `BEARER`.
939 ///
940 /// This is the evidence that separates syntax from prose. It is a weak signal
941 /// read honestly: capitalization is *suggestive*, so it upgrades an arming that
942 /// header context already established, and stands alone only for
943 /// [`SELF_EVIDENT_AUTH_SCHEME`].
944 fn is_canonical_auth_scheme(token: &str) -> bool {
945 AUTH_SCHEMES.contains(&unwrap_token(token))
946 }
947
948 /// Whether a token has the shape of an opaque credential value.
949 ///
950 /// Deliberately conservative: long, punctuation-free-ish, and mixing letters
951 /// with digits. Ordinary words — however long — never qualify, which is what
952 /// keeps `bearer of responsibility` out of the redactor.
953 fn looks_like_credential_value(token: &str) -> bool {
954 let (value, _, _) = codewhale_sanitize::redact::split_value_quotes(unwrap_token(token));
955 if codewhale_sanitize::redact::contains_bare_secret_token(value) {
956 return true;
957 }
958 if value.chars().count() < CREDENTIAL_VALUE_MIN_LEN {
959 return false;
960 }
961 let mut has_digit = false;
962 let mut has_alpha = false;
963 for ch in value.chars() {
964 if ch.is_ascii_digit() {
965 has_digit = true;
966 } else if ch.is_ascii_alphabetic() {
967 has_alpha = true;
968 } else if !matches!(ch, '-' | '_' | '.' | '=' | '+' | '/' | '~') {
969 return false;
970 }
971 }
972 has_digit && has_alpha
973 }
974
975 /// Whether a token is an absolute or home-relative filesystem path.
976 ///
977 /// A lone `/` or `~` is punctuation, not a path; a Windows drive letter needs
978 /// its `:\` to count.
979 fn looks_absolute(token: &str) -> bool {
980 let trimmed = token.trim_start_matches(['(', '[', '"', '\'']);
981 if trimmed.len() < 2 {
982 return false;
983 }
984 if let Some(rest) = trimmed.strip_prefix('/') {
985 return rest.starts_with(|ch: char| ch.is_ascii_alphanumeric() || ch == '.' || ch == '_');
986 }
987 if trimmed.starts_with("~/") || trimmed.starts_with("~\\") {
988 return true;
989 }
990 if trimmed.starts_with("\\\\") {
991 return true;
992 }
993 let mut chars = trimmed.chars();
994 matches!(
995 (chars.next(), chars.next(), chars.next()),
996 (Some(drive), Some(':'), Some('\\' | '/')) if drive.is_ascii_alphabetic()
997 )
998 }
999
1000 /// Which path kind a token is, if any — the single decision both the bare-token
1001 /// and the `NAME=value` rules ask, so an assignment can never be classified
1002 /// differently from the same value standing alone.
1003 ///
1004 /// Escaped spellings are resolved first: a path that arrives inside a JSON
1005 /// string is written `crates\/tui\/src\/main.rs` or `crates\\tui\\src\\main.rs`,
1006 /// and reading only the literal characters would let either spelling through
1007 /// while the receipt claimed nothing was removed.
1008 ///
1009 /// A URL is not a filesystem path and is left to the URL-bearing-input guard
1010 /// that already refuses such a task, so a token carrying a scheme is declined
1011 /// here rather than silently reclassified.
1012 fn classify_path(token: &str) -> Option<&'static str> {
1013 let raw = trim_path_punctuation(token);
1014 let unescaped = unescape_path(raw);
1015 let candidate = trim_path_punctuation(&unescaped);
1016 if candidate.contains("://") {
1017 return None;
1018 }
1019 // Both spellings are asked, because unescaping is lossy in one direction
1020 // that matters: a UNC share is *literally* `\\host\share`, and collapsing
1021 // its leading pair would demote a machine-identifying path to a relative
1022 // one.
1023 if looks_absolute(raw) || looks_absolute(candidate) {
1024 return Some(REDACTION_ABSOLUTE_PATH);
1025 }
1026 if looks_relative(candidate) {
1027 return Some(REDACTION_RELATIVE_PATH);
1028 }
1029 None
1030 }
1031
1032 /// Strip the punctuation a path picks up from surrounding prose, including the
1033 /// escaped quotes it picks up from a JSON string.
1034 fn trim_path_punctuation(token: &str) -> &str {
1035 token
1036 .trim_start_matches(['(', '[', '{', '"', '\'', '<', '`'])
1037 .trim_end_matches([
1038 ',', ';', ':', '.', ')', ']', '}', '"', '\'', '>', '`', '!', '?',
1039 ])
1040 }
1041
1042 /// Resolve `\/` and `\\` to the separator they escape, and drop escaped quotes.
1043 ///
1044 /// Returns an owned string only because most tokens need no work; the borrowed
1045 /// fast path is not worth a second code path in a function this small.
1046 fn unescape_path(token: &str) -> String {
1047 let mut out = String::with_capacity(token.len());
1048 let mut chars = token.chars().peekable();
1049 while let Some(ch) = chars.next() {
1050 if ch != '\\' {
1051 out.push(ch);
1052 continue;
1053 }
1054 match chars.peek() {
1055 Some('/') => {
1056 out.push('/');
1057 chars.next();
1058 }
1059 Some('\\') => {
1060 out.push('\\');
1061 chars.next();
1062 }
1063 Some('"') | Some('\'') => {
1064 chars.next();
1065 }
1066 // A lone backslash is a separator in its own right (`C:\Users`).
1067 _ => out.push('\\'),
1068 }
1069 }
1070 out
1071 }
1072
1073 /// Whether a token is a repo-relative filesystem path, judged conservatively.
1074 ///
1075 /// Two signals, and nothing else, because the cost of a false positive here is
1076 /// paid in the operator's own summary: a redacted word plus a `relative_path`
1077 /// kind on a receipt that removed prose.
1078 ///
1079 /// 1. **Explicit relative syntax** — `./x`, `../x`, and their backslash forms.
1080 /// Nothing but a path is spelled that way.
1081 /// 2. **A file extension on the last segment** of a multi-segment token: stem
1082 /// plus 1–8 ASCII *alphabetic* characters. The alphabetic requirement is
1083 /// what keeps `zai/glm-5.2` a model label rather than a file, and the
1084 /// multi-segment requirement is what keeps every bare `provider/model` pair
1085 /// — `deepseek/deepseek-v4-flash`, `anthropic/claude-opus-5` — intact.
1086 ///
1087 /// The deliberate gap is an extension-less directory (`crates/tui/src`), which
1088 /// stays. Catching it would need a rule that cannot tell a directory from
1089 /// `read/write/execute`, and shredding prose to hide a directory name is the
1090 /// worse trade.
1091 fn looks_relative(candidate: &str) -> bool {
1092 if !candidate.contains(['/', '\\']) {
1093 return false;
1094 }
1095 let explicit_prefix = ["./", "../", ".\\", "..\\"]
1096 .iter()
1097 .any(|prefix| candidate.starts_with(prefix));
1098 if explicit_prefix {
1099 return true;
1100 }
1101 let trimmed = candidate.trim_end_matches(['/', '\\']);
1102 let segments: Vec<&str> = trimmed.split(['/', '\\']).collect();
1103 if segments.len() < 2 || segments.iter().any(|segment| segment.is_empty()) {
1104 return false;
1105 }
1106 let last = segments[segments.len() - 1];
1107 let Some((stem, extension)) = last.rsplit_once('.') else {
1108 return false;
1109 };
1110 !stem.is_empty()
1111 && (1..=8).contains(&extension.chars().count())
1112 && extension.chars().all(|ch| ch.is_ascii_alphabetic())
1113 }
1114
1115 /// Whether a string contains anything this module would redact.
1116 ///
1117 /// Used by assertions and by durable-write guards that must fail loudly rather
1118 /// than persist a path or a key.
1119 #[must_use]
1120 #[cfg(test)]
1121 pub fn contains_redactable(input: &str) -> bool {
1122 redact_for_disclosure(input).redacted()
1123 }
1124
1125 #[cfg(test)]
1126 mod tests {
1127 use super::*;
1128
1129 #[test]
1130 fn absolute_paths_are_replaced_and_recorded() {
1131 let redaction = redact_for_disclosure("fix /Users/hunter/src/app/main.rs and ~/notes.md");
1132
1133 assert!(!redaction.text().contains("/Users/"));
1134 assert!(!redaction.text().contains("~/"));
1135 assert!(redaction.text().contains(PATH_PLACEHOLDER));
1136 assert!(redaction.redacted());
1137 assert_eq!(redaction.kinds(), vec![REDACTION_ABSOLUTE_PATH.to_string()]);
1138 }
1139
1140 #[test]
1141 fn windows_paths_and_unc_shares_count_as_absolute() {
1142 for token in ["C:\\Users\\hunter\\app", "\\\\share\\team\\notes"] {
1143 let redaction = redact_for_disclosure(token);
1144 assert!(redaction.redacted(), "{token} must be redacted");
1145 assert_eq!(redaction.text(), PATH_PLACEHOLDER);
1146 }
1147 }
1148
1149 #[test]
1150 fn secret_shaped_tokens_and_assignments_are_replaced() {
1151 let redaction = redact_for_disclosure("use sk-live-abc123 and ZAI_API_KEY=zzz");
1152
1153 assert!(!redaction.text().contains("sk-live-abc123"));
1154 assert!(!redaction.text().contains("zzz"));
1155 assert!(
1156 redaction.text().contains("ZAI_API_KEY=<redacted>"),
1157 "the name stays, the value goes: {}",
1158 redaction.text()
1159 );
1160 assert_eq!(redaction.kinds(), vec![REDACTION_SECRET.to_string()]);
1161 }
1162
1163 /// The credential in an `Authorization` header is a *separate token* from
1164 /// the header name and from the scheme keyword. Redacting only the keyword
1165 /// leaves the secret in the clear while the receipt claims a secret was
1166 /// removed — the exact failure this covers.
1167 #[test]
1168 fn a_multi_token_authorization_header_loses_its_credential() {
1169 let credentials = [
1170 ["sk", "-live-abc123def456"].concat(),
1171 ["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX", "VCJ9"].concat(),
1172 ["abcdef0123456789", "abcdef"].concat(),
1173 ];
1174 let headers = [
1175 format!("Authorization: Bearer {}", credentials[0]),
1176 format!("authorization: bearer {}", credentials[1]),
1177 format!("-H Authorization:Bearer {}", credentials[2]),
1178 ];
1179 for header in headers {
1180 let redaction = redact_for_disclosure(&header);
1181 let text = redaction.text();
1182 assert!(redaction.redacted(), "{header} must be redacted");
1183 assert!(
1184 text.contains(SECRET_PLACEHOLDER),
1185 "{header} must carry a placeholder: {text}"
1186 );
1187 for leaked in &credentials {
1188 assert!(!text.contains(leaked), "{leaked} leaked through: {text}");
1189 }
1190 assert_eq!(redaction.kinds(), vec![REDACTION_SECRET.to_string()]);
1191 }
1192 }
1193
1194 /// A bare scheme keyword introduces a credential only when a
1195 /// credential-shaped token actually follows it.
1196 #[test]
1197 fn a_bare_bearer_token_is_removed_but_the_scheme_word_survives() {
1198 let redaction = redact_for_disclosure("send Bearer 9f8e7d6c5b4a3f2e1d0c9b8a and retry");
1199 let text = redaction.text();
1200
1201 assert!(
1202 text.contains("Bearer"),
1203 "the scheme keyword is not a secret"
1204 );
1205 assert!(!text.contains("9f8e7d6c5b4a3f2e1d0c9b8a"), "{text}");
1206 assert!(text.ends_with("and retry"), "{text}");
1207 }
1208
1209 /// Ordinary words that merely *look* like credential prefixes must survive,
1210 /// and must not report a `secret` redaction kind. `Asia`, `bearer`, and any
1211 /// identifier containing them are prose, not keys.
1212 #[test]
1213 fn ordinary_words_and_identifiers_are_not_mistaken_for_secrets() {
1214 for text in [
1215 "ship the Asia region rollout",
1216 "ASIA is a continent, not a key",
1217 "the bearer of this note may enter",
1218 "authorization: needed before merge",
1219 "rename bearer_token_header to auth_header_name",
1220 "aws_region defaults to us-east-1",
1221 "pk_display is a public identifier",
1222 ] {
1223 let redaction = redact_for_disclosure(text);
1224 assert!(!redaction.redacted(), "{text} must survive: {redaction:?}");
1225 assert_eq!(redaction.text(), text);
1226 }
1227 }
1228
1229 /// The adversarial prose set. Every line here is ordinary English that the
1230 /// scheme/prefix rules could plausibly mistake for credential syntax, and
1231 /// every one of them must come back byte-identical with an empty `kinds`.
1232 ///
1233 /// A false positive is not a harmless over-redaction: it mangles the routing
1234 /// summary a human reads *and* writes `secret` onto a durable receipt that
1235 /// removed nothing, which makes the disclosure a lie in the safe direction.
1236 #[test]
1237 fn adversarial_prose_survives_the_credential_state_machine() {
1238 for text in [
1239 // The lowercase scheme word, in every position that could arm it.
1240 "bearer shares responsibility for the rollout",
1241 "the bearer of bad news is rarely thanked",
1242 "bearer",
1243 "each bearer token header is rewritten downstream",
1244 // Capitalized scheme words that are ordinary English. These are why
1245 // canonical capitalization arms only for `Bearer`.
1246 "Token holders vote on the proposal",
1247 "Basic auth is enabled for the staging endpoint",
1248 "Digest the results before the review",
1249 // Weak header context introducing a sentence, not a secret.
1250 "authorization: needed before merge",
1251 "authorization: bearer shares responsibility",
1252 // Identifiers and prefixes that resemble key material.
1253 "variables like aws_region and pk_display stay readable",
1254 "aws_ prefixed variables are documented in the runbook",
1255 // `pk_` is a *public* key prefix and carries nothing; it is
1256 // deliberately absent from SECRET_VALUE_PREFIXES. (`sk_` is not
1257 // listed here because it genuinely is a secret prefix and redacting
1258 // it is correct.)
1259 "pk_ and pub_ are conventions, not values",
1260 "asia and akia are four letter strings",
1261 "the variables were renamed in the same commit",
1262 // Long lowercase words are still words: shape alone must not fire.
1263 "internationalization is spelled with eighteen letters",
1264 ] {
1265 let redaction = redact_for_disclosure(text);
1266 assert!(
1267 !redaction.redacted(),
1268 "{text:?} is prose and must survive untouched: {redaction:?}"
1269 );
1270 assert_eq!(redaction.text(), text);
1271 assert!(
1272 redaction.kinds().is_empty(),
1273 "{text:?} must not claim a redaction it did not make"
1274 );
1275 }
1276 }
1277
1278 /// The adversarial credential set. A real credential is often short,
1279 /// lowercase, punctuated, or otherwise shapeless — `Bearer qqq` is the
1280 /// canonical example, and no shape test could ever catch it. Context has to.
1281 #[test]
1282 fn adversarial_credentials_lose_the_whole_value() {
1283 for (text, leaked) in [
1284 // The short, shapeless credential. This is the leak the evidence
1285 // model exists to close.
1286 ("Bearer qqq", "qqq"),
1287 ("Authorization: Bearer qqq", "qqq"),
1288 ("authorization: Bearer qqq", "qqq"),
1289 // Punctuated and quoted header forms.
1290 ("Authorization: Bearer qqq.", "qqq"),
1291 ("-H \"Authorization: Bearer qqq\"", "qqq"),
1292 ("Authorization:Bearer qqq", "qqq"),
1293 // The scheme keyword may not absorb the redaction and leave the
1294 // value behind.
1295 ("send Bearer hunter2 now", "hunter2"),
1296 (
1297 "curl -H Authorization: Bearer sk-live-0000 -X POST",
1298 "sk-live-0000",
1299 ),
1300 ] {
1301 let redaction = redact_for_disclosure(text);
1302 let redacted_text = redaction.text();
1303 assert!(
1304 redaction.redacted(),
1305 "{text:?} carries a credential and must be redacted"
1306 );
1307 assert!(
1308 !redacted_text.split(' ').any(|token| token == leaked
1309 || token.trim_end_matches(['.', ',', '"', '\'']) == leaked),
1310 "{leaked:?} leaked through {text:?}: {redacted_text}"
1311 );
1312 assert!(
1313 redacted_text.contains(SECRET_PLACEHOLDER),
1314 "{text:?} must carry a placeholder: {redacted_text}"
1315 );
1316 assert!(
1317 redaction.kinds().contains(&REDACTION_SECRET.to_string()),
1318 "{text:?} must disclose the secret kind"
1319 );
1320 // The scheme keyword is not the secret and must still be readable,
1321 // so a reader can tell *what* was removed.
1322 assert!(
1323 redacted_text.to_ascii_lowercase().contains("bearer"),
1324 "the scheme keyword must survive: {redacted_text}"
1325 );
1326 }
1327 }
1328
1329 /// The one documented false positive of the capitalization rule, pinned so
1330 /// it stays deliberate rather than becoming a surprise. Capitalized `Bearer`
1331 /// followed by a word is treated as header syntax; ordinary prose spells it
1332 /// lowercase, which the test above covers.
1333 #[test]
1334 fn capitalized_bearer_arms_even_in_prose_and_that_is_the_known_cost() {
1335 let redaction = redact_for_disclosure("Bearer tokens are rotated weekly");
1336 assert_eq!(redaction.text(), "Bearer <redacted> are rotated weekly");
1337
1338 // The lowercase spelling — what prose actually uses — is untouched.
1339 let prose = redact_for_disclosure("bearer tokens are rotated weekly");
1340 assert!(!prose.redacted());
1341 }
1342
1343 /// The real AWS shape still goes, so dropping the bare `asia`/`akia`
1344 /// prefixes did not trade a false positive for a false negative.
1345 #[test]
1346 fn full_aws_access_key_ids_are_still_removed() {
1347 for key in [
1348 ["AKIA", "IOSFODNN7EXAMPLE"].concat(),
1349 ["ASIA", "IOSFODNN7EXAMPLE"].concat(),
1350 ] {
1351 let redaction = redact_for_disclosure(&format!("creds {key} rotated"));
1352 assert!(!redaction.text().contains(&key), "{}", redaction.text());
1353 assert_eq!(redaction.kinds(), vec![REDACTION_SECRET.to_string()]);
1354 }
1355 }
1356
1357 #[test]
1358 fn ordinary_prose_is_left_alone() {
1359 let redaction = redact_for_disclosure("refactor the parser and add a regression test");
1360 assert!(!redaction.redacted());
1361 assert_eq!(
1362 redaction.text(),
1363 "refactor the parser and add a regression test"
1364 );
1365 assert!(redaction.kinds().is_empty());
1366 }
1367
1368 /// A repo-relative path discloses the private tree's shape to whatever
1369 /// provider the routing summary reaches, and is persisted next to it. Every
1370 /// spelling one arrives in — bare, quoted, JSON-escaped with `\/` or `\\`,
1371 /// explicitly relative, assigned to a name, trailing prose punctuation —
1372 /// must lose the path *and* say so on the receipt.
1373 #[test]
1374 fn repo_relative_paths_are_redacted_in_every_spelling_and_disclosed() {
1375 for token in [
1376 "crates/tui/src/main.rs",
1377 "src/lib.rs",
1378 "web/lib/deploy-preflight.test.ts",
1379 ".github/workflows/web.yml",
1380 "crates\\tui\\src\\main.rs",
1381 "crates\\/tui\\/src\\/main.rs",
1382 "\\\"crates/tui/src/main.rs\\\"",
1383 "\"crates/tui/src/main.rs\"",
1384 "(crates/tui/src/main.rs)",
1385 "./deploy.sh",
1386 "../../secret/notes.md",
1387 "..\\secret\\notes.md",
1388 ] {
1389 let redaction = redact_for_disclosure(token);
1390 assert!(redaction.redacted(), "{token} must be redacted");
1391 assert!(
1392 !redaction.text().contains("main.rs")
1393 && !redaction.text().contains("notes.md")
1394 && !redaction.text().contains("deploy"),
1395 "{token} leaked: {}",
1396 redaction.text()
1397 );
1398 assert!(
1399 redaction
1400 .kinds()
1401 .contains(&REDACTION_RELATIVE_PATH.to_string()),
1402 "{token} must disclose the relative_path kind: {:?}",
1403 redaction.kinds()
1404 );
1405 }
1406
1407 // In a sentence, and as a value: the name survives, the path does not.
1408 let sentence = redact_for_disclosure("patch crates/tui/src/main.rs, then path=src/lib.rs");
1409 assert_eq!(
1410 sentence.text(),
1411 "patch <path> then path=<path>",
1412 "prose keeps its shape around the placeholder"
1413 );
1414 assert_eq!(
1415 sentence.kinds(),
1416 vec![REDACTION_RELATIVE_PATH.to_string()],
1417 "one kind, honestly reported"
1418 );
1419 }
1420
1421 /// The other half of the same rule: it must not shred ordinary prose,
1422 /// `provider/model` labels, or bare punctuation, because a false positive
1423 /// here costs the operator their own summary *and* puts a redaction kind on
1424 /// a receipt that removed nothing.
1425 #[test]
1426 fn prose_labels_and_bare_punctuation_are_not_paths() {
1427 for token in [
1428 // Provider/model labels — the exact shape a Fleet receipt carries.
1429 "deepseek/deepseek-v4-flash",
1430 "zai/glm-5.2",
1431 "anthropic/claude-opus-5",
1432 "workspace/glm-pair",
1433 // Prose that happens to carry separators.
1434 "a/b",
1435 "and/or",
1436 "read/write/execute",
1437 "TODO/FIXME",
1438 "provider/model/reasoning",
1439 // Bare punctuation and non-paths.
1440 "/",
1441 "~",
1442 "5:30",
1443 "v0.9.2",
1444 // A URL is not a filesystem path; the URL-bearing-input guard owns
1445 // it, and reclassifying it here would be a silent behavior change.
1446 "https://example.test/a/b.rs",
1447 ] {
1448 let redaction = redact_for_disclosure(token);
1449 assert!(!redaction.redacted(), "{token} must not be redacted");
1450 assert_eq!(redaction.text(), token, "{token} must survive verbatim");
1451 }
1452 }
1453
1454 /// The documented gap, pinned so it stays a decision rather than a
1455 /// surprise: an extension-less directory survives, because no rule can
1456 /// separate it from `read/write/execute` without shredding prose.
1457 #[test]
1458 fn an_extension_less_directory_is_the_known_residual() {
1459 let redaction = redact_for_disclosure("look in crates/tui/src");
1460 assert!(!redaction.redacted());
1461 }
1462
1463 const BODY: &str = "Z7qX4mNb2Vc9Lk3PwR8t";
1464 const HEX: &str = "3f9a8c1d2e4b5a6f7c8d9e0a1b2c3d4e5f6a7b8c";
1465
1466 fn reported_credential_rows() -> Vec<(String, String)> {
1467 let jwt = ["eyJhbGciOiJIUzI1NiJ9", ".eyJzdWIiOiIxIn0", ".c2lnbmF0dXJl"].concat();
1468 let pem = "-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqhkiG9w0BAQEFAASC -----END PRIVATE KEY-----";
1469 vec![
1470 (format!("OPENAI_KEY=sk-proj-{BODY}"), BODY.to_string()),
1471 (format!("GITHUB_PAT=ghp_{BODY}"), BODY.to_string()),
1472 (format!("key=sk-live-{BODY}"), BODY.to_string()),
1473 (format!("(ghp_{BODY})"), BODY.to_string()),
1474 (format!("'sk-live-{BODY}'"), BODY.to_string()),
1475 (format!("--api-key={BODY}A"), BODY.to_string()),
1476 (format!("X-Api-Key: {BODY}AB"), BODY.to_string()),
1477 (format!("use {jwt} now"), jwt.clone()),
1478 (format!("glpat-{BODY}"), BODY.to_string()),
1479 (format!("hf_{BODY}"), BODY.to_string()),
1480 (format!("AIzaSy{BODY}"), BODY.to_string()),
1481 (
1482 "ZAI_API_KEY = zk8Q2mX7vB4nL9pR3tYc".to_string(),
1483 "zk8Q2mX7vB4nL9pR3tYc".to_string(),
1484 ),
1485 ("password: hunter2".to_string(), "hunter2".to_string()),
1486 (format!("xai-{BODY}"), BODY.to_string()),
1487 (pem.to_string(), "MIIEvQIBADANBgkq".to_string()),
1488 (
1489 format!("{{\"token_value\":\"ghp_{BODY}\"}}"),
1490 BODY.to_string(),
1491 ),
1492 (format!("密钥:sk-live-{BODY}"), BODY.to_string()),
1493 (format!("use ghs_{BODY}@github.com"), BODY.to_string()),
1494 (
1495 format!("https://x-access-token:ghs_{BODY}@github.com/o/r.git"),
1496 BODY.to_string(),
1497 ),
1498 (
1499 format!("https://ghp_{BODY}@github.com/o/r.git"),
1500 BODY.to_string(),
1501 ),
1502 (
1503 format!("https://oauth2:glpat-{BODY}@gitlab.com/o/r.git"),
1504 BODY.to_string(),
1505 ),
1506 (
1507 format!("x=-----BEGIN PRIVATE KEY-----y{BODY}-----END x OPENAI_API_KEY=sk-proj-{BODY}"),
1508 BODY.to_string(),
1509 ),
1510 (
1511 "SSH_KEY=-----BEGIN OPENSSH PRIVATE KEY----- b3BlbnNzaC1rZXktdjEAAAAAB -----END OPENSSH PRIVATE KEY-----".to_string(),
1512 "b3BlbnNzaC1rZXktdjEAAAAAB".to_string(),
1513 ),
1514 (
1515 "key=\"-----BEGIN PRIVATE KEY----- MIIEvQIBADANBgkqB -----END PRIVATE KEY-----\"".to_string(),
1516 "MIIEvQIBADANBgkqB".to_string(),
1517 ),
1518 (
1519 "-----BEGIN PGP PRIVATE KEY BLOCK----- lQOYBFBxyzB -----END PGP PRIVATE KEY BLOCK-----".to_string(),
1520 "lQOYBFBxyzB".to_string(),
1521 ),
1522 (
1523 "(\"k\":\"-----BEGIN PRIVATE KEY-----\\nMIIEvQIBADANBgkqB\\n-----END PRIVATE KEY-----\\n\")".to_string(),
1524 "MIIEvQIBADANBgkqB".to_string(),
1525 ),
1526 (format!("SLACKTOKEN={HEX}"), HEX.to_string()),
1527 (format!("GHTOKEN={HEX}"), HEX.to_string()),
1528 (format!("apitoken={HEX}"), HEX.to_string()),
1529 (format!("authtoken={HEX}"), HEX.to_string()),
1530 (format!("mytoken: {HEX}"), HEX.to_string()),
1531 (format!("OPENAIAPIKEY={HEX}"), HEX.to_string()),
1532 (format!("SECRETKEY={HEX}"), HEX.to_string()),
1533 (format!("apiKey := {HEX}"), HEX.to_string()),
1534 (format!("'api_key' => {HEX}"), HEX.to_string()),
1535 (format!("password == {HEX}"), HEX.to_string()),
1536 ("password := Hunter2Xyzzy99".to_string(), "Hunter2Xyzzy99".to_string()),
1537 (format!("run codewhale login --api-key {HEX} first"), HEX.to_string()),
1538 ("mysql -u root --password Hunter2Xyzzy99".to_string(), "Hunter2Xyzzy99".to_string()),
1539 (format!("deploy --token {HEX}"), HEX.to_string()),
1540 (format!("access_tokens={HEX}"), HEX.to_string()),
1541 (format!("GITHUB_TOKENS={HEX}"), HEX.to_string()),
1542 (format!("SESSION_TOKENS={HEX}"), HEX.to_string()),
1543 (format!("api_tokens: {HEX}"), HEX.to_string()),
1544 (format!("\"refresh_tokens\": [\"{HEX}\"]"), HEX.to_string()),
1545 (format!("API_TOKENS={HEX}"), HEX.to_string()),
1546 (format!("SLACK_BOT_TOKENS={HEX}"), HEX.to_string()),
1547 (format!("{{\"model\":\"gpt\",\"api_key\":\"{HEX}\"}}"), HEX.to_string()),
1548 ("{\"user\":\"app\",\"password\":\"Hunter2Xyzzy99\"}".to_string(), "Hunter2Xyzzy99".to_string()),
1549 (format!("{{\"id\":1,\"access_token\":\"{HEX}\"}}"), HEX.to_string()),
1550 (format!("curl https://api.example.test/v1?x=1&api_key={HEX}"), HEX.to_string()),
1551 (format!("{{\"stdout\":\"ok\\nsk-proj-{BODY}\\n\"}}"), BODY.to_string()),
1552 (format!("{{\"line\":\"name\\tghp_{BODY}\"}}"), BODY.to_string()),
1553 (format!("{{\"html\":\"\\u003cghs_{BODY}\\u003e\"}}"), BODY.to_string()),
1554 (format!("{{\"log\":\"key\\nsk-ant-api03-{BODY}\"}}"), BODY.to_string()),
1555 (format!("printf 'a\\nsk-live-{BODY}'"), BODY.to_string()),
1556 ("API_TOKENS=hunter2".to_string(), "hunter2".to_string()),
1557 (
1558 "ACCESS_TOKENS=my_short_secret".to_string(),
1559 "my_short_secret".to_string(),
1560 ),
1561 (
1562 "ACCESS_TOKENS=secret_token_without_digits".to_string(),
1563 "secret_token_without_digits".to_string(),
1564 ),
1565 (
1566 format!("{{\"api_tokens\": \"{HEX}\"}}"),
1567 HEX.to_string(),
1568 ),
1569 (
1570 format!("{{\"api_tokens\": [ \"{HEX}\" ]}}"),
1571 HEX.to_string(),
1572 ),
1573 (
1574 format!("{{\"api_tokens\": {{ \"prod\": \"{HEX}\" }}}}"),
1575 HEX.to_string(),
1576 ),
1577 (
1578 format!("{{\"api_tokens\": [ \"{HEX}\", \"9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b\" ]}}"),
1579 "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b".to_string(),
1580 ),
1581 (
1582 format!("{{\"api_tokens\":[\"{HEX}\",\"9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b\"]}}"),
1583 "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a0b".to_string(),
1584 ),
1585 (
1586 format!("{{\"stdout\":\"ok\\n\\\"api_key\\\": \\\"{HEX}\\\"\"}}"),
1587 HEX.to_string(),
1588 ),
1589 (
1590 format!("{{\"stdout\":\"ok\\n\\\"api_key\\\":\\\"{HEX}\\\"\"}}"),
1591 HEX.to_string(),
1592 ),
1593 (
1594 format!("{{\"stdout\":\"ok\\napi_key: {HEX}\"}}"),
1595 HEX.to_string(),
1596 ),
1597 (
1598 "{\"stdout\":\"ok\\npassword: Hunter2Xyzzy99\"}".to_string(),
1599 "Hunter2Xyzzy99".to_string(),
1600 ),
1601 (
1602 "{\"stdout\":\"ok\\n\\\"api_key\\\":\\\"short_secret\\\"\"}".to_string(),
1603 "short_secret".to_string(),
1604 ),
1605 (
1606 format!("{{\"stdout\":\"ok\\n\\\"api_key\\\":\\n\\\"{HEX}\\\"\"}}"),
1607 HEX.to_string(),
1608 ),
1609 (
1610 format!("{{\"stdout\":\"API_KEY={HEX}\"}}"),
1611 HEX.to_string(),
1612 ),
1613 (
1614 format!("{{\"stdout\":\"ok\\u003cAPI_KEY={HEX}\\u003e\"}}"),
1615 HEX.to_string(),
1616 ),
1617 (
1618 format!("\\\\\\\"api_key\\\\\\\":\\\\\\\"{HEX}\\\\\\\""),
1619 HEX.to_string(),
1620 ),
1621 (
1622 "{\"authorization\":\"basic dXNlcjpIdW50ZXIyWHl6enk5OQ==\"}".to_string(),
1623 "dXNlcjpIdW50ZXIyWHl6enk5OQ==".to_string(),
1624 ),
1625 (
1626 "{\"b\":\"Authorization: Basic dXNlcjpIdW50ZXIyWHl6enk5OQ==\"}".to_string(),
1627 "dXNlcjpIdW50ZXIyWHl6enk5OQ==".to_string(),
1628 ),
1629 (
1630 format!("FOO=\"bar\nbaz\"\nAPI_KEY={HEX}"),
1631 HEX.to_string(),
1632 ),
1633 ]
1634 }
1635
1636 #[test]
1637 fn credentials_in_every_reported_spelling_are_removed_and_disclosed() {
1638 for (input, leaked) in reported_credential_rows() {
1639 let redaction = redact_for_disclosure(&input);
1640 assert!(
1641 !redaction.text().contains(&leaked),
1642 "{input} leaked: {}",
1643 redaction.text()
1644 );
1645 assert_eq!(
1646 redaction.kinds(),
1647 vec![REDACTION_SECRET.to_string()],
1648 "{input}"
1649 );
1650 }
1651 }
1652
1653 #[test]
1654 fn operators_and_flags_are_kept_and_only_the_value_is_removed() {
1655 for (input, expected) in [
1656 (
1657 format!("set apiKey := \"{HEX}\" in main.go"),
1658 "set apiKey := <redacted> in main.go",
1659 ),
1660 (
1661 format!("set 'api_key' => '{HEX}' in config"),
1662 "set 'api_key' => <redacted> in config",
1663 ),
1664 (
1665 format!("check password == {HEX}"),
1666 "check password == <redacted>",
1667 ),
1668 (
1669 "set password := Hunter2Xyzzy99 now".to_string(),
1670 "set password := <redacted> now",
1671 ),
1672 (
1673 format!("run codewhale login --api-key {HEX} first"),
1674 "run codewhale login --api-key <redacted> first",
1675 ),
1676 (format!("deploy --token {HEX}"), "deploy --token <redacted>"),
1677 (format!("SLACKTOKEN={HEX}"), "SLACKTOKEN=<redacted>"),
1678 (format!("mytoken: {HEX}"), "mytoken: <redacted>"),
1679 ] {
1680 let redaction = redact_for_disclosure(&input);
1681 assert_eq!(redaction.text(), expected, "{input}");
1682 assert_eq!(redaction.kinds(), vec![REDACTION_SECRET.to_string()]);
1683 }
1684 }
1685
1686 #[test]
1687 fn token_counts_are_not_secrets() {
1688 for text in [
1689 "max_tokens=8192",
1690 "tokens=5",
1691 "completion_tokens: 50",
1692 "tokenBudget: 9",
1693 "--token-limit 5",
1694 "TOKEN_LIMIT=4096",
1695 "tokenizer=bpe",
1696 "tokenizer=sentencepiece-v2",
1697 "output_tokens=512",
1698 "set --max-tokens 4096 --token-limit 5",
1699 "run --max-tokens=8192 claude-3-5-sonnet-20241022",
1700 "eval --tokens=5 deadbeef12345678",
1701 "{\"tokens\": { \"input\": 100, \"output\": 200 }}",
1702 ] {
1703 let redaction = redact_for_disclosure(text);
1704 assert_eq!(redaction.text(), text);
1705 assert!(redaction.kinds().is_empty(), "{text}");
1706 }
1707
1708 let nested_obj =
1709 redact_for_disclosure(&format!("{{\"api_tokens\": {{ \"prod\": \"{HEX}\" }}}}"));
1710 assert!(
1711 nested_obj.text().contains("\"prod\":"),
1712 "{}",
1713 nested_obj.text()
1714 );
1715 assert!(!nested_obj.text().contains(HEX), "{}", nested_obj.text());
1716
1717 let rel = redact_for_disclosure("set --tokenizer=bpe crates/engine/src/v2.rs");
1718 assert_eq!(rel.text(), "set --tokenizer=bpe <path>");
1719 assert_eq!(rel.kinds(), vec![REDACTION_RELATIVE_PATH.to_string()]);
1720
1721 let abs = redact_for_disclosure("run --token-limit=4096 /Users/alice/src/v2");
1722 assert_eq!(abs.text(), "run --token-limit=4096 <path>");
1723 assert_eq!(abs.kinds(), vec![REDACTION_ABSOLUTE_PATH.to_string()]);
1724 }
1725
1726 #[test]
1727 fn the_routing_payload_carries_none_of_the_reported_credentials() {
1728 for (input, leaked) in reported_credential_rows() {
1729 let payload = crate::fleet_reasoning::bounded_routing_payload(&format!(
1730 "fix the deploy script\n{input}\nthen rerun"
1731 ));
1732 assert!(
1733 !payload.text().contains(&leaked),
1734 "{input} reached the router: {}",
1735 payload.text()
1736 );
1737 assert!(payload.disclosure().redacted, "{input}");
1738 assert!(payload.text().starts_with("fix the deploy script"));
1739 assert!(payload.text().ends_with("then rerun"), "{}", payload.text());
1740 }
1741 }
1742
1743 #[test]
1744 fn contains_redactable_matches_the_redactor() {
1745 assert!(contains_redactable("/Users/hunter"));
1746 assert!(contains_redactable("token=abc"));
1747 assert!(!contains_redactable("land a fix in the workflow crate"));
1748 }
1749 }
1750
1750 lines RUST