From 60a543b6aace5160a29ede4f57fbda841e845df7 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:03:29 +0000 Subject: [PATCH 01/14] fix(core): strip terminal escape sequences before output redaction (#1605) Co-Authored-By: Claude Sonnet 5.5 --- ...-1605-redact-secrets-in-coloured-output.md | 2 + crates/core/src/ai/live_redaction.rs | 12 + crates/core/src/ai/mod.rs | 1 + crates/core/src/ai/redactor.rs | 2 +- crates/core/src/ai/redactor_property.rs | 4 + crates/core/src/ai/terminal_escapes.rs | 266 ++++++++++++++++++ .../0068-security-hardening-prelaunch.md | 9 + 7 files changed, 295 insertions(+), 1 deletion(-) create mode 100644 changelog.d/issue-1605-redact-secrets-in-coloured-output.md create mode 100644 crates/core/src/ai/terminal_escapes.rs diff --git a/changelog.d/issue-1605-redact-secrets-in-coloured-output.md b/changelog.d/issue-1605-redact-secrets-in-coloured-output.md new file mode 100644 index 000000000..4de627deb --- /dev/null +++ b/changelog.d/issue-1605-redact-secrets-in-coloured-output.md @@ -0,0 +1,2 @@ +### Security +- Secrets in command output that contains terminal colour or cursor codes (for example `grep --color=always`) are now masked before the text reaches the AI, the chat or logs. The codes are removed from that text. diff --git a/crates/core/src/ai/live_redaction.rs b/crates/core/src/ai/live_redaction.rs index 1d68818fc..7ce0aa9e7 100644 --- a/crates/core/src/ai/live_redaction.rs +++ b/crates/core/src/ai/live_redaction.rs @@ -328,4 +328,16 @@ mod tests { let all_but_last: String = (0..199).map(|i| format!("line {i}\n")).collect(); assert_eq!(shown, all_but_last); } + + #[test] + fn test_coloured_secret_across_chunks_is_never_shown_nor_half_escape() { + let raw = "ok\n\x1b[01;31m\x1b[Kpassword \x1b[m\x1b[K= hunter2\nnext\nmore\n"; + assert_never_shows(raw, "hunter2"); + for chunk in 1..=raw.len() { + let shown = live_view(raw, chunk); + assert!(!shown.contains('\u{1b}'), "chunk {chunk}: {shown:?}"); + assert!(!shown.contains("[01;31m"), "chunk {chunk}: {shown:?}"); + assert!(!shown.contains("[K"), "chunk {chunk}: {shown:?}"); + } + } } diff --git a/crates/core/src/ai/mod.rs b/crates/core/src/ai/mod.rs index 1c643f341..704804fd8 100644 --- a/crates/core/src/ai/mod.rs +++ b/crates/core/src/ai/mod.rs @@ -30,6 +30,7 @@ mod redactor_property; mod redactor_reference; mod rejection; mod second_opinion; +mod terminal_escapes; mod types; #[cfg(test)] diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 86d80ab9b..48ad951d2 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,7 +1409,7 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - let mut text = String::from_utf8_lossy(data).into_owned(); + let mut text = super::terminal_escapes::strip(data); for rule in patterns { if rule.regex.is_match(&text) { text = rule.regex.replace_all(&text, rule.replacement).into_owned(); diff --git a/crates/core/src/ai/redactor_property.rs b/crates/core/src/ai/redactor_property.rs index 3579b5ff1..aeef0caeb 100644 --- a/crates/core/src/ai/redactor_property.rs +++ b/crates/core/src/ai/redactor_property.rs @@ -3,6 +3,10 @@ //! //! A failure means a redactor change redacts less than before. Fix the //! redactor, not the reference. +//! +//! The generated documents contain no terminal escape sequences (issue +//! #1605), so the current redactor's escape stripping changes nothing here and +//! both sides see the same text; the reference is intentionally unchanged. use proptest::prelude::*; diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs new file mode 100644 index 000000000..76cc3aefc --- /dev/null +++ b/crates/core/src/ai/terminal_escapes.rs @@ -0,0 +1,266 @@ +//! Removal of terminal escape sequences before redaction (issue #1605, +//! Spec 0068 Part 1). +//! +//! Colour and cursor codes between a key and its value, inside a PEM header +//! or in front of a token break every redaction pattern. [`strip`] removes +//! them first, in one place, so every caller of the redactor sees stripped +//! text. Removed: CSI (`ESC [` … final byte `0x40–0x7E`, also the 8-bit +//! `0x9B` form), string sequences (OSC `ESC ]`, DCS, SOS, PM, APC up to +//! `BEL` or `ESC \`), other two- and three-byte `ESC` sequences and a lone +//! `ESC`. A sequence never swallows a line break: it ends in front of `\n` +//! or `\r`, so lines stay line-based for the live redactor. An unterminated +//! sequence is removed up to the end of the text. + +/// Decodes `data` as UTF-8 (invalid bytes become U+FFFD, as before) and +/// removes terminal escape sequences. Text without any escape introducer is +/// returned unchanged. +pub(crate) fn strip(data: &[u8]) -> String { + let mut text = String::with_capacity(data.len()); + for chunk in data.utf8_chunks() { + text.push_str(chunk.valid()); + for b in chunk.invalid() { + // A raw 0x9B is the 8-bit CSI introducer; it cannot be part of + // valid UTF-8 here. Keep it distinguishable from U+FFFD. + text.push(if *b == 0x9B { '\u{9B}' } else { '\u{FFFD}' }); + } + } + if !text.contains(['\u{1B}', '\u{9B}']) { + return text; + } + strip_str(&text) +} + +fn strip_str(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut it = text.chars().peekable(); + while let Some(c) = it.next() { + match c { + '\u{9B}' => skip_csi(&mut it), + '\u{1B}' => match it.peek().copied() { + Some('[') => { + it.next(); + skip_csi(&mut it); + } + Some(']' | 'P' | 'X' | '^' | '_') => { + it.next(); + skip_string(&mut it); + } + Some(n) if ('\u{20}'..='\u{2F}').contains(&n) => { + // Intermediates (`ESC ( B`), then one final byte. + while matches!(it.peek(), Some(n) if ('\u{20}'..='\u{2F}').contains(n)) { + it.next(); + } + if matches!(it.peek(), Some(n) if ('\u{30}'..='\u{7E}').contains(n)) { + it.next(); + } + } + Some(n) if ('\u{30}'..='\u{7E}').contains(&n) => { + it.next(); + } + // Lone ESC (end of text, line break, other byte). + _ => {} + }, + _ => out.push(c), + } + } + out +} + +/// CSI body: parameter/intermediate bytes, then a final byte. Any other +/// character (a line break, say) ends the sequence without being consumed. +fn skip_csi(it: &mut std::iter::Peekable>) { + while let Some(&c) = it.peek() { + match c { + '\u{20}'..='\u{3F}' => { + it.next(); + } + '\u{40}'..='\u{7E}' => { + it.next(); + return; + } + _ => return, + } + } +} + +/// String sequence body: up to `BEL` or `ESC \` (both consumed). A line +/// break ends it unconsumed; so does an `ESC` not followed by `\`. +fn skip_string(it: &mut std::iter::Peekable>) { + while let Some(&c) = it.peek() { + match c { + '\u{7}' => { + it.next(); + return; + } + '\u{1B}' => { + it.next(); + if it.peek() == Some(&'\\') { + it.next(); + } + return; + } + '\n' | '\r' => return, + _ => { + it.next(); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::strip; + + #[test] + fn test_sgr_and_erase_are_removed() { + assert_eq!( + strip(b"\x1b[01;31m\x1b[Kpassword \x1b[m\x1b[K= hunter2"), + "password = hunter2" + ); + } + + #[test] + fn test_osc_with_bel_and_st_is_removed() { + assert_eq!(strip(b"a\x1b]0;title\x07b"), "ab"); + assert_eq!(strip(b"a\x1b]8;;http://x\x1b\\b"), "ab"); + } + + #[test] + fn test_lone_esc_and_two_byte_sequences_are_removed() { + assert_eq!(strip(b"a\x1bb"), "a"); + assert_eq!(strip(b"a\x1b"), "a"); + assert_eq!(strip(b"a\x1b\nb"), "a\nb"); + assert_eq!(strip(b"a\x1b(Bb"), "ab"); + } + + #[test] + fn test_unterminated_sequences_are_removed_to_the_end() { + assert_eq!(strip(b"abc\x1b["), "abc"); + assert_eq!(strip(b"abc\x1b[31"), "abc"); + assert_eq!(strip(b"abc\x1b]0;title"), "abc"); + } + + #[test] + fn test_unterminated_sequence_keeps_the_line_break() { + assert_eq!(strip(b"a\x1b[3\nsecret"), "a\nsecret"); + assert_eq!(strip(b"a\x1b]0;t\r\nb"), "a\r\nb"); + } + + #[test] + fn test_c1_csi_is_removed_raw_and_encoded() { + assert_eq!(strip(b"a\x9b31mb"), "ab"); + assert_eq!(strip("a\u{9b}31mb".as_bytes()), "ab"); + } + + #[test] + fn test_plain_text_is_unchanged() { + let s = "grüße ě (0x9B continuation) [31m 日本\n\r\t"; + assert_eq!(strip(s.as_bytes()), s); + assert_eq!(strip(b"a\xffb"), "a\u{FFFD}b"); + } + + // ---- Redaction of coloured output (issue #1605) ---- + + use crate::ai::redactor_generators::secret_snippet; + use crate::ai::{DefaultOutputRedactor, OutputRedactor}; + use proptest::prelude::*; + + fn red(text: &str) -> String { + DefaultOutputRedactor::new().redact_text(text) + } + + #[test] + fn test_grep_color_password_value_is_masked() { + let out = red("\x1b[01;31m\x1b[Kpassword \x1b[m\x1b[K= hunter2\n"); + assert!(!out.contains("hunter2"), "{out:?}"); + assert!(!out.contains('\u{1b}'), "{out:?}"); + } + + #[test] + fn test_pem_header_with_sgr_masks_the_body() { + let raw = "\x1b[31m-----BEGIN\x1b[0m \x1b[1mRSA PRIVATE KEY\x1b[0m-----\n\ + MIIEowIBAAKCAQEAsecretbodyline1\nsecretbodyline2AAAA\n\ + -----END RSA PRIVATE KEY-----\n"; + let out = red(raw); + assert!(!out.contains("secretbodyline"), "{out:?}"); + assert!(!out.contains("MIIEowIBAAKCAQEA"), "{out:?}"); + } + + #[test] + fn test_token_right_after_sgr_is_masked() { + let token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789"; + let out = red(&format!("\x1b[32m{token}\x1b[0m")); + assert!(!out.contains(token), "{out:?}"); + assert!( + !out.contains("abcdefghijklmnopqrstuvwxyz0123456789"), + "{out:?}" + ); + } + + #[test] + fn test_key_and_value_coloured_separately_is_masked() { + let out = red("\x1b[36mpassword\x1b[0m=\x1b[33mhunter2secret\x1b[0m"); + assert!(!out.contains("hunter2secret"), "{out:?}"); + } + + #[test] + fn test_redact_output_strips_stdout_and_stderr() { + let o = crate::ssh::CommandOutput { + stdout: b"\x1b[31mpassword\x1b[0m=hunter2".to_vec(), + stderr: b"\x1b[31mpassword\x1b[0m=hunter3".to_vec(), + exit_code: Some(0), + truncated: false, + }; + let r = DefaultOutputRedactor::new().redact(&o); + let all = format!( + "{}{}", + String::from_utf8_lossy(&r.stdout), + String::from_utf8_lossy(&r.stderr) + ); + assert!(!all.contains("hunter"), "{all:?}"); + assert!(!all.contains('\u{1b}'), "{all:?}"); + } + + fn sgr() -> impl Strategy { + proptest::sample::select(vec![ + "\x1b[0m", + "\x1b[01;31m", + "\x1b[K", + "\x1b[38;5;196m", + "\x1b[m", + ]) + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(300))] + + /// Random SGR around key, separator and value never lets a secret + /// through. + #[test] + fn coloured_secret_is_still_redacted( + snip in secret_snippet(), + a in sgr(), b in sgr(), c in sgr(), + ) { + let mut text = String::new(); + for ch in snip.text.chars() { + if matches!(ch, ' ' | '=' | ':' | '"' | '\'') { + text.push_str(a); + text.push(ch); + text.push_str(b); + } else { + text.push(ch); + } + } + for secret in &snip.secrets { + text = text.replace(secret.as_str(), &format!("{a}{secret}{c}")); + } + // Only secrets the redactor masks in plain text count (some + // low-entropy values are not masked there either). + let plain = red(&snip.text); + let out = red(&text); + for secret in snip.secrets.iter().filter(|s| !plain.contains(s.as_str())) { + prop_assert!(!out.contains(secret.as_str()), "{secret:?} in {out:?} (input {text:?})"); + } + } + } +} diff --git a/docs/specs/0068-security-hardening-prelaunch.md b/docs/specs/0068-security-hardening-prelaunch.md index 64fc6f5f5..b13854910 100644 --- a/docs/specs/0068-security-hardening-prelaunch.md +++ b/docs/specs/0068-security-hardening-prelaunch.md @@ -43,6 +43,15 @@ Regeln dafür: „Basic authentication" bleiben unverändert. - **Kein generisches Hoch-Entropie-Muster** (bewusst verworfen: zu viele Falsch-Positive). +- **Terminal-Escape-Sequenzen werden vor dem Abgleich entfernt.** Farb- und + Cursor-Codes (CSI inklusive `ESC[K` und der 8-Bit-Form `0x9B`, OSC, + sonstige `ESC`-Folgen, ein einzelnes `ESC`) zwischen Schlüssel und Wert, in + einer PEM-Kopfzeile oder vor einem Token verhindern die Erkennung nicht + mehr (z. B. Ausgabe von `grep --color=always`). Der weitergegebene Text + (KI, Chat, Logs) ist der bereinigte Text; eine Folge am Ende einer + abgeschnittenen Ausgabe wird bis zum Ende entfernt. Text ohne `ESC` bleibt + unverändert, Zeilenumbrüche bleiben erhalten. Das gilt auch für die + Live-Ausgabe. ## Teil 2 — Lesebefehle auf Secret-Pfade verlangen Bestätigung From 21328e554733db31c9393139032a5d83c04407d2 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 19:51:18 +0000 Subject: [PATCH 02/14] fix(core): redact before and after stripping escapes so a lone ESC cannot eat a secret's first char (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 20 ++++++++++++--- crates/core/src/ai/terminal_escapes.rs | 34 ++++++++++++++++++++------ 2 files changed, 43 insertions(+), 11 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 48ad951d2..25fef17bf 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1408,13 +1408,25 @@ impl OutputRedactor for DefaultOutputRedactor { /// Byte-Sequenzen ist "durch Ersatzzeichen ersetzt, aber Secret trotzdem /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. -fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - let mut text = super::terminal_escapes::strip(data); +fn apply_patterns(text: &mut String, patterns: &[PatternRule]) { for rule in patterns { - if rule.regex.is_match(&text) { - text = rule.regex.replace_all(&text, rule.replacement).into_owned(); + if rule.regex.is_match(text) { + *text = rule.regex.replace_all(text, rule.replacement).into_owned(); } } +} + +fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { + // Pass 1 on the original text (a lone ESC or 0x9B directly in front of a + // secret would otherwise swallow its first character), then strip the + // escape sequences and run the patterns again for secrets that were + // split by them (issue #1605). + let mut text = super::terminal_escapes::decode(data); + apply_patterns(&mut text, patterns); + if text.contains(['\u{1B}', '\u{9B}']) { + text = super::terminal_escapes::strip_text(text); + apply_patterns(&mut text, patterns); + } absorb_fragments_next_to_placeholders(&text).into_bytes() } diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 76cc3aefc..8c709792d 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -15,6 +15,11 @@ /// removes terminal escape sequences. Text without any escape introducer is /// returned unchanged. pub(crate) fn strip(data: &[u8]) -> String { + strip_text(decode(data)) +} + +/// Lossy UTF-8 decoding without removing any escape sequence. +pub(crate) fn decode(data: &[u8]) -> String { let mut text = String::with_capacity(data.len()); for chunk in data.utf8_chunks() { text.push_str(chunk.valid()); @@ -24,6 +29,11 @@ pub(crate) fn strip(data: &[u8]) -> String { text.push(if *b == 0x9B { '\u{9B}' } else { '\u{FFFD}' }); } } + text +} + +/// Removes terminal escape sequences from already decoded text. +pub(crate) fn strip_text(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { return text; } @@ -187,14 +197,24 @@ mod tests { } #[test] - fn test_token_right_after_sgr_is_masked() { + fn test_token_split_by_sgr_is_masked() { + let out = red("ghp_abcdefghijkl\x1b[0mmnopqrstuvwxyz0123456789"); + assert!(!out.contains("abcdefghijkl"), "{out:?}"); + assert!(!out.contains("mnopqrstuvwxyz"), "{out:?}"); + } + + #[test] + fn test_secret_right_after_lone_esc_or_c1_csi_is_masked() { let token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789"; - let out = red(&format!("\x1b[32m{token}\x1b[0m")); - assert!(!out.contains(token), "{out:?}"); - assert!( - !out.contains("abcdefghijklmnopqrstuvwxyz0123456789"), - "{out:?}" - ); + for lead in ["\x1b", "\u{9b}"] { + let out = red(&format!("{lead}{token}")); + assert!(!out.contains("abcdefghijkl"), "{lead:?}: {out:?}"); + } + let out = red("\x1bAKIAIOSFODNN7EXAMPLE"); + assert!(!out.contains("IOSFODNN7EXAMPLE"), "{out:?}"); + let pem = "\x1b-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAsecretbody\n-----END RSA PRIVATE KEY-----"; + let out = red(pem); + assert!(!out.contains("secretbody"), "{out:?}"); } #[test] From d19e01821e208678e6d8532b0ef750a964f7ddf8 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:10:33 +0000 Subject: [PATCH 03/14] fix(core): gate test-only strip helper (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/terminal_escapes.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 8c709792d..a60aabba8 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -14,6 +14,7 @@ /// Decodes `data` as UTF-8 (invalid bytes become U+FFFD, as before) and /// removes terminal escape sequences. Text without any escape introducer is /// returned unchanged. +#[cfg(test)] pub(crate) fn strip(data: &[u8]) -> String { strip_text(decode(data)) } From 248470bf2852480741930dc86b9604bb36278620 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:35:50 +0000 Subject: [PATCH 04/14] refactor(core): move escape-aware redaction pass into terminal_escapes (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 25 +++++++------------------ crates/core/src/ai/terminal_escapes.rs | 15 ++++++++++++++- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 25fef17bf..6e76e5677 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1408,25 +1408,14 @@ impl OutputRedactor for DefaultOutputRedactor { /// Byte-Sequenzen ist "durch Ersatzzeichen ersetzt, aber Secret trotzdem /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. -fn apply_patterns(text: &mut String, patterns: &[PatternRule]) { - for rule in patterns { - if rule.regex.is_match(text) { - *text = rule.regex.replace_all(text, rule.replacement).into_owned(); - } - } -} - fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - // Pass 1 on the original text (a lone ESC or 0x9B directly in front of a - // secret would otherwise swallow its first character), then strip the - // escape sequences and run the patterns again for secrets that were - // split by them (issue #1605). - let mut text = super::terminal_escapes::decode(data); - apply_patterns(&mut text, patterns); - if text.contains(['\u{1B}', '\u{9B}']) { - text = super::terminal_escapes::strip_text(text); - apply_patterns(&mut text, patterns); - } + let text = super::terminal_escapes::around_strip(data, |text| { + for rule in patterns { + if rule.regex.is_match(text) { + *text = rule.regex.replace_all(text, rule.replacement).into_owned(); + } + } + }); absorb_fragments_next_to_placeholders(&text).into_bytes() } diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index a60aabba8..bb67e34b3 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -20,7 +20,7 @@ pub(crate) fn strip(data: &[u8]) -> String { } /// Lossy UTF-8 decoding without removing any escape sequence. -pub(crate) fn decode(data: &[u8]) -> String { +fn decode(data: &[u8]) -> String { let mut text = String::with_capacity(data.len()); for chunk in data.utf8_chunks() { text.push_str(chunk.valid()); @@ -33,6 +33,19 @@ pub(crate) fn decode(data: &[u8]) -> String { text } +/// Decodes `data` and runs `apply` before stripping escape sequences (a lone +/// ESC would eat the first character of a following secret) and again after +/// it (secrets split by escapes), issue #1605. +pub(crate) fn around_strip(data: &[u8], apply: impl Fn(&mut String)) -> String { + let mut text = decode(data); + apply(&mut text); + if text.contains(['\u{1B}', '\u{9B}']) { + text = strip_text(text); + apply(&mut text); + } + text +} + /// Removes terminal escape sequences from already decoded text. pub(crate) fn strip_text(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { From c3284598edc49635c4d743dfa1c1e5fa9196c660 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:20:43 +0000 Subject: [PATCH 05/14] fix(core): keep placeholder when an escape introducer precedes it (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 3 +++ crates/core/src/ai/terminal_escapes.rs | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 6e76e5677..c8f3f4669 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1415,6 +1415,9 @@ fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { *text = rule.regex.replace_all(text, rule.replacement).into_owned(); } } + // Absorb in every pass, so a tail next to a placeholder is gone + // before escape stripping can change what is adjacent to it. + *text = absorb_fragments_next_to_placeholders(text); }); absorb_fragments_next_to_placeholders(&text).into_bytes() } diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index bb67e34b3..9d23309e4 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -51,6 +51,12 @@ pub(crate) fn strip_text(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { return text; } + // An introducer right before an already inserted placeholder would + // otherwise form `ESC [` + `R` and eat the placeholder's start; drop + // only the introducer (issue #1605 review). + let text = text + .replace("\u{1B}[REDACTED]", "[REDACTED]") + .replace("\u{9B}[REDACTED]", "[REDACTED]"); strip_str(&text) } @@ -135,6 +141,12 @@ fn skip_string(it: &mut std::iter::Peekable>) { mod tests { use super::strip; + #[test] + fn test_introducer_before_placeholder_keeps_placeholder() { + assert_eq!(strip(b"a\x1b[REDACTED]b"), "a[REDACTED]b"); + assert_eq!(strip(b"a\x9b[REDACTED]b"), "a[REDACTED]b"); + } + #[test] fn test_sgr_and_erase_are_removed() { assert_eq!( @@ -193,6 +205,18 @@ mod tests { DefaultOutputRedactor::new().redact_text(text) } + #[test] + fn test_introducer_before_secret_keeps_placeholder_and_absorbs_tail() { + assert_eq!( + red("id \x1bAKIAIOSFODNN7EXAMPLEtailsecret99 y"), + "id [REDACTED] y" + ); + assert_eq!( + red("id \u{9b}AKIAIOSFODNN7EXAMPLEtailsecret99 y"), + "id [REDACTED] y" + ); + } + #[test] fn test_grep_color_password_value_is_masked() { let out = red("\x1b[01;31m\x1b[Kpassword \x1b[m\x1b[K= hunter2\n"); From e83383a5fc92e05eddd46cad05d1f5b2a80e76fb Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:45:46 +0000 Subject: [PATCH 06/14] fix(core): absorb inside each redaction pass, drop redundant final pass (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index c8f3f4669..3edbd7092 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,17 +1409,15 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - let text = super::terminal_escapes::around_strip(data, |text| { + super::terminal_escapes::around_strip(data, |text| { for rule in patterns { if rule.regex.is_match(text) { *text = rule.regex.replace_all(text, rule.replacement).into_owned(); } } - // Absorb in every pass, so a tail next to a placeholder is gone - // before escape stripping can change what is adjacent to it. - *text = absorb_fragments_next_to_placeholders(text); - }); - absorb_fragments_next_to_placeholders(&text).into_bytes() + *text = absorb_fragments_next_to_placeholders(text); // #1605 + }) + .into_bytes() } /// Spec 0068 (dritte Review-Runde, ERHÖHT): hat ein Muster nur einen Teil From 097210e3a1da42fb52d718d043f116583adc2e23 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:23:28 +0000 Subject: [PATCH 07/14] fix(core): strip escapes once before redacting, keep lone ESC/CSI from eating characters (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 16 +++--- crates/core/src/ai/terminal_escapes.rs | 76 ++++++++++++++------------ 2 files changed, 50 insertions(+), 42 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 3edbd7092..f17e69830 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,15 +1409,15 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - super::terminal_escapes::around_strip(data, |text| { - for rule in patterns { - if rule.regex.is_match(text) { - *text = rule.regex.replace_all(text, rule.replacement).into_owned(); - } + // Decode and strip terminal escapes first, then redact once (#1605). + let mut text = super::terminal_escapes::strip_text(super::terminal_escapes::decode(data)); + for rule in patterns { + if rule.regex.is_match(&text) { + text = rule.regex.replace_all(&text, rule.replacement).into_owned(); } - *text = absorb_fragments_next_to_placeholders(text); // #1605 - }) - .into_bytes() + } + absorb_fragments_next_to_placeholders(&text) // #1605 + .into_bytes() } /// Spec 0068 (dritte Review-Runde, ERHÖHT): hat ein Muster nur einen Teil diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 9d23309e4..88266c115 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -20,7 +20,7 @@ pub(crate) fn strip(data: &[u8]) -> String { } /// Lossy UTF-8 decoding without removing any escape sequence. -fn decode(data: &[u8]) -> String { +pub(crate) fn decode(data: &[u8]) -> String { let mut text = String::with_capacity(data.len()); for chunk in data.utf8_chunks() { text.push_str(chunk.valid()); @@ -33,30 +33,11 @@ fn decode(data: &[u8]) -> String { text } -/// Decodes `data` and runs `apply` before stripping escape sequences (a lone -/// ESC would eat the first character of a following secret) and again after -/// it (secrets split by escapes), issue #1605. -pub(crate) fn around_strip(data: &[u8], apply: impl Fn(&mut String)) -> String { - let mut text = decode(data); - apply(&mut text); - if text.contains(['\u{1B}', '\u{9B}']) { - text = strip_text(text); - apply(&mut text); - } - text -} - /// Removes terminal escape sequences from already decoded text. pub(crate) fn strip_text(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { return text; } - // An introducer right before an already inserted placeholder would - // otherwise form `ESC [` + `R` and eat the placeholder's start; drop - // only the introducer (issue #1605 review). - let text = text - .replace("\u{1B}[REDACTED]", "[REDACTED]") - .replace("\u{9B}[REDACTED]", "[REDACTED]"); strip_str(&text) } @@ -65,7 +46,14 @@ fn strip_str(text: &str) -> String { let mut it = text.chars().peekable(); while let Some(c) = it.next() { match c { - '\u{9B}' => skip_csi(&mut it), + // A bare 0x9B is dropped alone; only with a parameter byte + // (`0x9B 3 1 m`) is it a sequence, so a secret's first + // character is never taken for the final byte. + '\u{9B}' => { + if matches!(it.peek(), Some(n) if ('\u{20}'..='\u{3F}').contains(n)) { + skip_csi(&mut it); + } + } '\u{1B}' => match it.peek().copied() { Some('[') => { it.next(); @@ -75,19 +63,19 @@ fn strip_str(text: &str) -> String { it.next(); skip_string(&mut it); } - Some(n) if ('\u{20}'..='\u{2F}').contains(&n) => { + // `-` and `.` stay out (a PEM header starts with dashes). + Some(' ' | '#' | '%' | '(' | ')' | '*' | '+') => { // Intermediates (`ESC ( B`), then one final byte. - while matches!(it.peek(), Some(n) if ('\u{20}'..='\u{2F}').contains(n)) { + while matches!(it.peek(), Some(' ' | '#' | '%' | '(' | ')' | '*' | '+')) { it.next(); } if matches!(it.peek(), Some(n) if ('\u{30}'..='\u{7E}').contains(n)) { it.next(); } } - Some(n) if ('\u{30}'..='\u{7E}').contains(&n) => { - it.next(); - } - // Lone ESC (end of text, line break, other byte). + // Lone ESC (end of text, line break, printable character): + // drop only the ESC, never the character after it, which + // may be the first character of a secret. _ => {} }, _ => out.push(c), @@ -141,12 +129,6 @@ fn skip_string(it: &mut std::iter::Peekable>) { mod tests { use super::strip; - #[test] - fn test_introducer_before_placeholder_keeps_placeholder() { - assert_eq!(strip(b"a\x1b[REDACTED]b"), "a[REDACTED]b"); - assert_eq!(strip(b"a\x9b[REDACTED]b"), "a[REDACTED]b"); - } - #[test] fn test_sgr_and_erase_are_removed() { assert_eq!( @@ -163,7 +145,7 @@ mod tests { #[test] fn test_lone_esc_and_two_byte_sequences_are_removed() { - assert_eq!(strip(b"a\x1bb"), "a"); + assert_eq!(strip(b"a\x1bbcd"), "abcd"); assert_eq!(strip(b"a\x1b"), "a"); assert_eq!(strip(b"a\x1b\nb"), "a\nb"); assert_eq!(strip(b"a\x1b(Bb"), "ab"); @@ -217,6 +199,22 @@ mod tests { ); } + #[test] + fn test_sgr_around_secret_leaves_exact_placeholder() { + assert_eq!( + red("x \x1b[31mAKIAIOSFODNN7EXAMPLE\x1b[0m y"), + "x [REDACTED] y" + ); + } + + #[test] + fn test_sgr_coloured_tail_is_absorbed() { + assert_eq!( + red("k AKIAIOSFODNN7EXAMPLE\x1b[1mtailsecret99"), + "k [REDACTED]" + ); + } + #[test] fn test_grep_color_password_value_is_masked() { let out = red("\x1b[01;31m\x1b[Kpassword \x1b[m\x1b[K= hunter2\n"); @@ -292,6 +290,16 @@ mod tests { proptest! { #![proptest_config(ProptestConfig::with_cases(300))] + /// SGR-wrapped secret redacts exactly like the plain text. + #[test] + fn sgr_wrapped_equals_plain(snip in secret_snippet(), a in sgr(), c in sgr()) { + let mut wrapped = snip.text.clone(); + for secret in &snip.secrets { + wrapped = wrapped.replace(secret.as_str(), &format!("{a}{secret}{c}")); + } + prop_assert_eq!(red(&wrapped), red(&snip.text), "input {:?}", wrapped); + } + /// Random SGR around key, separator and value never lets a secret /// through. #[test] From fa430d45f036db950f7e94867bed89751aec07d4 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:16:35 +0000 Subject: [PATCH 08/14] fix(core): replace non-SGR escapes by one space, add escape property test (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/terminal_escapes.rs | 135 ++++++++++++++---- .../0068-security-hardening-prelaunch.md | 6 +- 2 files changed, 114 insertions(+), 27 deletions(-) diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 88266c115..463448674 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -7,7 +7,8 @@ //! text. Removed: CSI (`ESC [` … final byte `0x40–0x7E`, also the 8-bit //! `0x9B` form), string sequences (OSC `ESC ]`, DCS, SOS, PM, APC up to //! `BEL` or `ESC \`), other two- and three-byte `ESC` sequences and a lone -//! `ESC`. A sequence never swallows a line break: it ends in front of `\n` +//! `ESC`. SGR (`m`) and erase (`K`) leave no trace; every other sequence +//! (and a lone `ESC`/`0x9B`) becomes one space. A sequence never swallows a line break: it ends in front of `\n` //! or `\r`, so lines stay line-based for the live redactor. An unterminated //! sequence is removed up to the end of the text. @@ -46,22 +47,25 @@ fn strip_str(text: &str) -> String { let mut it = text.chars().peekable(); while let Some(c) = it.next() { match c { - // A bare 0x9B is dropped alone; only with a parameter byte - // (`0x9B 3 1 m`) is it a sequence, so a secret's first - // character is never taken for the final byte. + // `0x9B` followed by a parameter byte is a CSI; a bare one is + // only the introducer, so a secret's first character is never + // taken for the final byte. '\u{9B}' => { if matches!(it.peek(), Some(n) if ('\u{20}'..='\u{3F}').contains(n)) { - skip_csi(&mut it); + push_unless_silent(&mut out, skip_csi(&mut it)); + } else { + out.push(' '); } } '\u{1B}' => match it.peek().copied() { Some('[') => { it.next(); - skip_csi(&mut it); + push_unless_silent(&mut out, skip_csi(&mut it)); } Some(']' | 'P' | 'X' | '^' | '_') => { it.next(); skip_string(&mut it); + out.push(' '); } // `-` and `.` stay out (a PEM header starts with dashes). Some(' ' | '#' | '%' | '(' | ')' | '*' | '+') => { @@ -72,11 +76,12 @@ fn strip_str(text: &str) -> String { if matches!(it.peek(), Some(n) if ('\u{30}'..='\u{7E}').contains(n)) { it.next(); } + out.push(' '); } // Lone ESC (end of text, line break, printable character): - // drop only the ESC, never the character after it, which - // may be the first character of a secret. - _ => {} + // becomes a space and never eats the character after it, + // which may be the first character of a secret. + _ => out.push(' '), }, _ => out.push(c), } @@ -84,9 +89,18 @@ fn strip_str(text: &str) -> String { out } +/// Only SGR (`m`) and erase (`K`) leave no trace; every other sequence +/// becomes one space so that it still separates a key from its value. +fn push_unless_silent(out: &mut String, silent: bool) { + if !silent { + out.push(' '); + } +} + /// CSI body: parameter/intermediate bytes, then a final byte. Any other /// character (a line break, say) ends the sequence without being consumed. -fn skip_csi(it: &mut std::iter::Peekable>) { +/// Returns true for an SGR/erase sequence (final byte `m` or `K`). +fn skip_csi(it: &mut std::iter::Peekable>) -> bool { while let Some(&c) = it.peek() { match c { '\u{20}'..='\u{3F}' => { @@ -94,11 +108,12 @@ fn skip_csi(it: &mut std::iter::Peekable>) { } '\u{40}'..='\u{7E}' => { it.next(); - return; + return matches!(c, 'm' | 'K'); } - _ => return, + _ => return false, } } + false } /// String sequence body: up to `BEL` or `ESC \` (both consumed). A line @@ -139,29 +154,32 @@ mod tests { #[test] fn test_osc_with_bel_and_st_is_removed() { - assert_eq!(strip(b"a\x1b]0;title\x07b"), "ab"); - assert_eq!(strip(b"a\x1b]8;;http://x\x1b\\b"), "ab"); + assert_eq!(strip(b"a\x1b]0;title\x07b"), "a b"); + assert_eq!(strip(b"a\x1b]8;;http://x\x1b\\b"), "a b"); } #[test] fn test_lone_esc_and_two_byte_sequences_are_removed() { - assert_eq!(strip(b"a\x1bbcd"), "abcd"); - assert_eq!(strip(b"a\x1b"), "a"); - assert_eq!(strip(b"a\x1b\nb"), "a\nb"); - assert_eq!(strip(b"a\x1b(Bb"), "ab"); + assert_eq!(strip(b"a\x1bbcd"), "a bcd"); + assert_eq!(strip(b"a\x1b"), "a "); + assert_eq!(strip(b"a\x1b\nb"), "a \nb"); + assert_eq!(strip(b"a\x1b(Bb"), "a b"); + assert_eq!(strip("x\u{9b}gsk".as_bytes()), "x gsk"); + assert_eq!(strip(b"x\x1b[2~gsk"), "x gsk"); + assert_eq!(strip(b"x\x1b[@eyJ"), "x eyJ"); } #[test] fn test_unterminated_sequences_are_removed_to_the_end() { - assert_eq!(strip(b"abc\x1b["), "abc"); - assert_eq!(strip(b"abc\x1b[31"), "abc"); - assert_eq!(strip(b"abc\x1b]0;title"), "abc"); + assert_eq!(strip(b"abc\x1b["), "abc "); + assert_eq!(strip(b"abc\x1b[31"), "abc "); + assert_eq!(strip(b"abc\x1b]0;title"), "abc "); } #[test] fn test_unterminated_sequence_keeps_the_line_break() { - assert_eq!(strip(b"a\x1b[3\nsecret"), "a\nsecret"); - assert_eq!(strip(b"a\x1b]0;t\r\nb"), "a\r\nb"); + assert_eq!(strip(b"a\x1b[3\nsecret"), "a \nsecret"); + assert_eq!(strip(b"a\x1b]0;t\r\nb"), "a \r\nb"); } #[test] @@ -180,22 +198,67 @@ mod tests { // ---- Redaction of coloured output (issue #1605) ---- use crate::ai::redactor_generators::secret_snippet; + use crate::ai::redactor_reference::OutputRedactor as ReferenceTrait; use crate::ai::{DefaultOutputRedactor, OutputRedactor}; use proptest::prelude::*; + static REDACTOR: std::sync::LazyLock = + std::sync::LazyLock::new(DefaultOutputRedactor::new); + fn red(text: &str) -> String { - DefaultOutputRedactor::new().redact_text(text) + REDACTOR.redact_text(text) + } + + static REFERENCE: std::sync::LazyLock = + std::sync::LazyLock::new(crate::ai::redactor_reference::DefaultOutputRedactor::new); + + #[test] + fn test_non_sgr_escapes_before_secrets_do_not_leak() { + let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnopqrstuvwxyz"; + let gsk = "gsk_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJ"; + let inputs = [ + format!("x\x1b{gsk}"), + format!("x\u{9b}{gsk}"), + format!("x\x1b[2~{gsk}"), + format!("x\x1b]0;t\x07{gsk}"), + format!("x\x1b]8;;http://e\x1b\\{gsk}"), + format!("x\x1b[@{jwt}"), + "my\x1b[2~api-key: supersecret123".to_string(), + ]; + for input in &inputs { + let out = red(input); + for needle in ["abcdefghijklmnop", "eyJhbGci", "supersecret123"] { + assert!(!out.contains(needle), "{input:?} -> {out:?}"); + } + } + } + + /// Any escape sequence (not only SGR) around or in front of a secret. + fn any_escape() -> impl Strategy { + proptest::sample::select(vec![ + "\x1b", + "\u{9b}", + "\x1b[2~", + "\x1b[@", + "\x1b[1;5H", + "\x1b]0;t\x07", + "\x1b]8;;http://e\x1b\\", + "\x1bP1$r\x1b\\", + "\x1b(B", + "\x1b[0m", + "\x1b[K", + ]) } #[test] fn test_introducer_before_secret_keeps_placeholder_and_absorbs_tail() { assert_eq!( red("id \x1bAKIAIOSFODNN7EXAMPLEtailsecret99 y"), - "id [REDACTED] y" + "id [REDACTED] y" ); assert_eq!( red("id \u{9b}AKIAIOSFODNN7EXAMPLEtailsecret99 y"), - "id [REDACTED] y" + "id [REDACTED] y" ); } @@ -290,6 +353,26 @@ mod tests { proptest! { #![proptest_config(ProptestConfig::with_cases(300))] + /// Arbitrary escapes in front of and behind a snippet never leave a + /// secret the reference masks in the same input. (Inside a + /// space-free token only SGR/erase is transparent; any other + /// sequence becomes a space by design, see `sgr_wrapped_equals_plain`.) + #[test] + fn any_escape_never_leaks_what_reference_masks( + snip in secret_snippet(), a in any_escape(), c in any_escape(), + ) { + // `ESC` followed by one of `] P X ^ _ [` is by definition the + // start of a string/CSI sequence and swallows what follows. + let starts_seq = |t: &str| t.starts_with([']', 'P', 'X', '^', '_', '[']); + prop_assume!(!starts_seq(&snip.text)); + let text = format!("{a}{}{c}", snip.text); + let reference = ReferenceTrait::redact_text(&*REFERENCE, &text); + let out = red(&text); + for secret in snip.secrets.iter().filter(|s| !reference.contains(s.as_str())) { + prop_assert!(!out.contains(secret.as_str()), "{secret:?} in {out:?} (input {text:?})"); + } + } + /// SGR-wrapped secret redacts exactly like the plain text. #[test] fn sgr_wrapped_equals_plain(snip in secret_snippet(), a in sgr(), c in sgr()) { diff --git a/docs/specs/0068-security-hardening-prelaunch.md b/docs/specs/0068-security-hardening-prelaunch.md index b13854910..2d9779001 100644 --- a/docs/specs/0068-security-hardening-prelaunch.md +++ b/docs/specs/0068-security-hardening-prelaunch.md @@ -49,7 +49,11 @@ Regeln dafür: einer PEM-Kopfzeile oder vor einem Token verhindern die Erkennung nicht mehr (z. B. Ausgabe von `grep --color=always`). Der weitergegebene Text (KI, Chat, Logs) ist der bereinigte Text; eine Folge am Ende einer - abgeschnittenen Ausgabe wird bis zum Ende entfernt. Text ohne `ESC` bleibt + abgeschnittenen Ausgabe wird bis zum Ende entfernt. Farb- und Löschcodes + (SGR `…m`, Erase `…K`) verschwinden spurlos; jede andere Folge (CSI mit + anderem Endbyte, OSC/DCS/APC …, ein einzelnes `ESC` oder `0x9B`) wird durch + genau ein Leerzeichen ersetzt, damit sie Schlüssel und Wert weiterhin + trennt und nie ein folgendes Zeichen verschluckt. Text ohne `ESC` bleibt unverändert, Zeilenumbrüche bleiben erhalten. Das gilt auch für die Live-Ausgabe. From 214f985d6fdb0da786f1fc746c75a7a5a1660ad5 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:50:46 +0000 Subject: [PATCH 09/14] fix(core): keep secrets whole around non-SGR escapes via matching sentinel (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 13 +++-- crates/core/src/ai/terminal_escapes.rs | 71 ++++++++++++++++++++------ 2 files changed, 65 insertions(+), 19 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index f17e69830..604a37077 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1410,14 +1410,21 @@ impl OutputRedactor for DefaultOutputRedactor { /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { // Decode and strip terminal escapes first, then redact once (#1605). - let mut text = super::terminal_escapes::strip_text(super::terminal_escapes::decode(data)); + let mut text = + super::terminal_escapes::strip_text_for_matching(super::terminal_escapes::decode(data)); for rule in patterns { if rule.regex.is_match(&text) { text = rule.regex.replace_all(&text, rule.replacement).into_owned(); } } - absorb_fragments_next_to_placeholders(&text) // #1605 - .into_bytes() + let text = absorb_fragments_next_to_placeholders(&text); // #1605 + // Leftover escape separators become one space (they still separate words). + if text.contains(super::terminal_escapes::SEPARATOR) { + return text + .replace(super::terminal_escapes::SEPARATOR, " ") + .into_bytes(); + } + text.into_bytes() } /// Spec 0068 (dritte Review-Runde, ERHÖHT): hat ein Muster nur einen Teil diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 463448674..2a8100ab9 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -35,14 +35,29 @@ pub(crate) fn decode(data: &[u8]) -> String { } /// Removes terminal escape sequences from already decoded text. +#[cfg(test)] pub(crate) fn strip_text(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { return text; } - strip_str(&text) + strip_str(&text, ' ') +} + +/// Placeholder for a removed non-SGR sequence while the patterns run: not a +/// word character and not whitespace, so a secret value is not cut short by +/// an escape inside it (private-use code point). +pub(crate) const SEPARATOR: char = '\u{E000}'; + +/// Like [`strip_text`], but removed non-SGR sequences leave [`SEPARATOR`]; +/// the caller turns leftovers into spaces after redaction. +pub(crate) fn strip_text_for_matching(text: String) -> String { + if !text.contains(['\u{1B}', '\u{9B}']) { + return text; + } + strip_str(&text, SEPARATOR) } -fn strip_str(text: &str) -> String { +fn strip_str(text: &str, sep: char) -> String { let mut out = String::with_capacity(text.len()); let mut it = text.chars().peekable(); while let Some(c) = it.next() { @@ -52,20 +67,20 @@ fn strip_str(text: &str) -> String { // taken for the final byte. '\u{9B}' => { if matches!(it.peek(), Some(n) if ('\u{20}'..='\u{3F}').contains(n)) { - push_unless_silent(&mut out, skip_csi(&mut it)); + push_unless_silent(&mut out, sep, skip_csi(&mut it)); } else { - out.push(' '); + out.push(sep); } } '\u{1B}' => match it.peek().copied() { Some('[') => { it.next(); - push_unless_silent(&mut out, skip_csi(&mut it)); + push_unless_silent(&mut out, sep, skip_csi(&mut it)); } Some(']' | 'P' | 'X' | '^' | '_') => { it.next(); skip_string(&mut it); - out.push(' '); + out.push(sep); } // `-` and `.` stay out (a PEM header starts with dashes). Some(' ' | '#' | '%' | '(' | ')' | '*' | '+') => { @@ -76,12 +91,12 @@ fn strip_str(text: &str) -> String { if matches!(it.peek(), Some(n) if ('\u{30}'..='\u{7E}').contains(n)) { it.next(); } - out.push(' '); + out.push(sep); } // Lone ESC (end of text, line break, printable character): // becomes a space and never eats the character after it, // which may be the first character of a secret. - _ => out.push(' '), + _ => out.push(sep), }, _ => out.push(c), } @@ -91,9 +106,9 @@ fn strip_str(text: &str) -> String { /// Only SGR (`m`) and erase (`K`) leave no trace; every other sequence /// becomes one space so that it still separates a key from its value. -fn push_unless_silent(out: &mut String, silent: bool) { +fn push_unless_silent(out: &mut String, sep: char, silent: bool) { if !silent { - out.push(' '); + out.push(sep); } } @@ -225,11 +240,31 @@ mod tests { format!("x\x1b[@{jwt}"), "my\x1b[2~api-key: supersecret123".to_string(), ]; - for input in &inputs { - let out = red(input); - for needle in ["abcdefghijklmnop", "eyJhbGci", "supersecret123"] { - assert!(!out.contains(needle), "{input:?} -> {out:?}"); - } + let expected = [ + "x [REDACTED]", + "x [REDACTED]", + "x [REDACTED]", + "x [REDACTED]", + "x [REDACTED]", + "x [REDACTED]", + "my [REDACTED]", + ]; + for (input, want) in inputs.iter().zip(expected) { + assert_eq!(red(input), want, "{input:?}"); + } + } + + #[test] + fn test_non_sgr_escape_inside_secret_value_does_not_cut_it() { + for (input, want) in [ + ("password=hun\x1b[2~ter2secret", "[REDACTED]"), + ("token: abcd\x1b]0;t\x07efghsecretvalue", "[REDACTED]"), + ( + "https://user:\x1b[2~hunter2pass@host/x", + "https://user:[REDACTED]@host/x", + ), + ] { + assert_eq!(red(input), want, "{input:?}"); } } @@ -365,7 +400,11 @@ mod tests { // start of a string/CSI sequence and swallows what follows. let starts_seq = |t: &str| t.starts_with([']', 'P', 'X', '^', '_', '[']); prop_assume!(!starts_seq(&snip.text)); - let text = format!("{a}{}{c}", snip.text); + let mut text = snip.text.clone(); + for secret in &snip.secrets { + text = text.replace(secret.as_str(), &format!("{a}{secret}{c}")); + } + let text = format!("{a}{text}{c}"); let reference = ReferenceTrait::redact_text(&*REFERENCE, &text); let out = red(&text); for secret in snip.secrets.iter().filter(|s| !reference.contains(s.as_str())) { From 8e2b8d5c56cbb8c26e7db404d583dbc46c5729ee Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:12:48 +0000 Subject: [PATCH 10/14] refactor(core): move separator handling into terminal_escapes to keep redactor.rs within its size limit (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 14 +++----------- crates/core/src/ai/terminal_escapes.rs | 12 +++++++++++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index 604a37077..f5391be06 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,22 +1409,14 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - // Decode and strip terminal escapes first, then redact once (#1605). - let mut text = - super::terminal_escapes::strip_text_for_matching(super::terminal_escapes::decode(data)); + let mut text = super::terminal_escapes::strip_for_matching(data); // #1605 for rule in patterns { if rule.regex.is_match(&text) { text = rule.regex.replace_all(&text, rule.replacement).into_owned(); } } - let text = absorb_fragments_next_to_placeholders(&text); // #1605 - // Leftover escape separators become one space (they still separate words). - if text.contains(super::terminal_escapes::SEPARATOR) { - return text - .replace(super::terminal_escapes::SEPARATOR, " ") - .into_bytes(); - } - text.into_bytes() + super::terminal_escapes::restore_separators(&absorb_fragments_next_to_placeholders(&text)) + .into_bytes() } /// Spec 0068 (dritte Review-Runde, ERHÖHT): hat ein Muster nur einen Teil diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 2a8100ab9..781575b26 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -48,9 +48,19 @@ pub(crate) fn strip_text(text: String) -> String { /// an escape inside it (private-use code point). pub(crate) const SEPARATOR: char = '\u{E000}'; +/// Decodes and strips `data` for the redaction patterns (see [`SEPARATOR`]). +pub(crate) fn strip_for_matching(data: &[u8]) -> String { + strip_text_for_matching(decode(data)) +} + +/// Turns leftover [`SEPARATOR`]s (after redaction) into one space each. +pub(crate) fn restore_separators(text: &str) -> String { + text.replace(SEPARATOR, " ") +} + /// Like [`strip_text`], but removed non-SGR sequences leave [`SEPARATOR`]; /// the caller turns leftovers into spaces after redaction. -pub(crate) fn strip_text_for_matching(text: String) -> String { +fn strip_text_for_matching(text: String) -> String { if !text.contains(['\u{1B}', '\u{9B}']) { return text; } From ae4f32baeb92385c98123be597237badbd390e8f Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:00:49 +0000 Subject: [PATCH 11/14] fix(core): mask the union of raw and stripped redaction views, no sentinel (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 14 +- crates/core/src/ai/terminal_escapes.rs | 305 +++++++++++++----- .../0068-security-hardening-prelaunch.md | 10 +- 3 files changed, 244 insertions(+), 85 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index f5391be06..feb411dc1 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,14 +1409,22 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - let mut text = super::terminal_escapes::strip_for_matching(data); // #1605 + let text = super::terminal_escapes::decode(data); + // Issue #1605: with an escape introducer, mask the union of the raw and + // the stripped view; without one, exactly the plain patterns. + if super::terminal_escapes::has_introducer(&text) { + let rules: Vec<(&Regex, &str)> = + patterns.iter().map(|r| (&r.regex, r.replacement)).collect(); + let masked = super::terminal_escapes::redact_escaped(&text, &rules, REDACTED_PLACEHOLDER); + return absorb_fragments_next_to_placeholders(&masked).into_bytes(); + } + let mut text = text; for rule in patterns { if rule.regex.is_match(&text) { text = rule.regex.replace_all(&text, rule.replacement).into_owned(); } } - super::terminal_escapes::restore_separators(&absorb_fragments_next_to_placeholders(&text)) - .into_bytes() + absorb_fragments_next_to_placeholders(&text).into_bytes() } /// Spec 0068 (dritte Review-Runde, ERHÖHT): hat ein Muster nur einen Teil diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 781575b26..663eaef1b 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -2,9 +2,10 @@ //! Spec 0068 Part 1). //! //! Colour and cursor codes between a key and its value, inside a PEM header -//! or in front of a token break every redaction pattern. [`strip`] removes -//! them first, in one place, so every caller of the redactor sees stripped -//! text. Removed: CSI (`ESC [` … final byte `0x40–0x7E`, also the 8-bit +//! or in front of a token break every redaction pattern. The redactor masks +//! the union of the patterns on the raw text and on the text with the +//! sequences removed ([`redact_escaped`]); the output never carries an +//! escape sequence. Removed: CSI (`ESC [` … final byte `0x40–0x7E`, also the 8-bit //! `0x9B` form), string sequences (OSC `ESC ]`, DCS, SOS, PM, APC up to //! `BEL` or `ESC \`), other two- and three-byte `ESC` sequences and a lone //! `ESC`. SGR (`m`) and erase (`K`) leave no trace; every other sequence @@ -17,7 +18,11 @@ /// returned unchanged. #[cfg(test)] pub(crate) fn strip(data: &[u8]) -> String { - strip_text(decode(data)) + let text = decode(data); + if !has_introducer(&text) { + return text; + } + strip_tracked(&text).text } /// Lossy UTF-8 decoding without removing any escape sequence. @@ -34,105 +39,211 @@ pub(crate) fn decode(data: &[u8]) -> String { text } -/// Removes terminal escape sequences from already decoded text. -#[cfg(test)] -pub(crate) fn strip_text(text: String) -> String { - if !text.contains(['\u{1B}', '\u{9B}']) { - return text; - } - strip_str(&text, ' ') +/// True if `text` contains an escape introducer (`ESC` or `0x9B`). Text +/// without one takes the plain redaction path, byte for byte as before. +pub(crate) fn has_introducer(text: &str) -> bool { + text.contains(['\u{1B}', '\u{9B}']) } -/// Placeholder for a removed non-SGR sequence while the patterns run: not a -/// word character and not whitespace, so a secret value is not cut short by -/// an escape inside it (private-use code point). -pub(crate) const SEPARATOR: char = '\u{E000}'; - -/// Decodes and strips `data` for the redaction patterns (see [`SEPARATOR`]). -pub(crate) fn strip_for_matching(data: &[u8]) -> String { - strip_text_for_matching(decode(data)) +/// Redaction rules: pattern and replacement (as for `Regex::replace_all`). +pub(crate) type Rules<'a> = [(&'a regex::Regex, &'a str)]; + +/// Text after the rules ran, with the origin of every byte. +struct Tracked { + text: String, + /// Per byte of `text`: the byte range of the input it stems from (a + /// replacement carries the range of the whole match). + prov: Vec<(usize, usize)>, + /// Per byte of `text`: produced by a replacement. + replaced: Vec, } -/// Turns leftover [`SEPARATOR`]s (after redaction) into one space each. -pub(crate) fn restore_separators(text: &str) -> String { - text.replace(SEPARATOR, " ") +/// Applies the rules in order, exactly like repeated `replace_all`, and +/// records where every output byte comes from. +fn track(input: &str, rules: &Rules<'_>) -> Tracked { + let mut t = Tracked { + text: input.to_string(), + prov: (0..input.len()).map(|i| (i, i + 1)).collect(), + replaced: vec![false; input.len()], + }; + for (re, replacement) in rules { + if !re.is_match(&t.text) { + continue; + } + let mut text = String::with_capacity(t.text.len()); + let mut prov = Vec::with_capacity(t.prov.len()); + let mut replaced = Vec::with_capacity(t.replaced.len()); + let mut last = 0; + for caps in re.captures_iter(&t.text) { + let Some(m) = caps.get(0) else { continue }; + text.push_str(&t.text[last..m.start()]); + prov.extend_from_slice(&t.prov[last..m.start()]); + replaced.extend_from_slice(&t.replaced[last..m.start()]); + let range = t.prov[m.start()..m.end()] + .iter() + .fold((usize::MAX, 0), |(lo, hi), &(l, h)| (lo.min(l), hi.max(h))); + let range = if m.is_empty() { (0, 0) } else { range }; + let mut dst = String::new(); + caps.expand(replacement, &mut dst); + prov.extend(std::iter::repeat_n(range, dst.len())); + replaced.extend(std::iter::repeat_n(true, dst.len())); + text.push_str(&dst); + last = m.end(); + } + text.push_str(&t.text[last..]); + prov.extend_from_slice(&t.prov[last..]); + replaced.extend_from_slice(&t.replaced[last..]); + t = Tracked { + text, + prov, + replaced, + }; + } + t } -/// Like [`strip_text`], but removed non-SGR sequences leave [`SEPARATOR`]; -/// the caller turns leftovers into spaces after redaction. -fn strip_text_for_matching(text: String) -> String { - if !text.contains(['\u{1B}', '\u{9B}']) { - return text; +/// Redacts decoded text that contains an escape introducer (issue #1605). +/// +/// The result masks the union of two views: (a) the patterns on the raw +/// text, as before escape handling existed, so nothing masked there can +/// leak; (b) the patterns on the stripped text, which finds secrets that an +/// escape sequence cut apart. Matches of (a) are mapped onto the stripped +/// text by offsets; a match that touches part of a removed sequence masks +/// the whole stripped span it touches. The output carries no escape +/// sequence. +pub(crate) fn redact_escaped(raw: &str, rules: &Rules<'_>, placeholder: &str) -> String { + let raw_pass = track(raw, rules); + let mut spans: Vec<(usize, usize)> = raw_pass + .prov + .iter() + .zip(&raw_pass.replaced) + .filter(|(_, r)| **r) + .map(|(p, _)| *p) + .filter(|(lo, hi)| lo < hi) + .collect(); + spans.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::new(); + for (lo, hi) in spans { + match merged.last_mut() { + Some(last) if lo <= last.1 => last.1 = last.1.max(hi), + _ => merged.push((lo, hi)), + } + } + let touches = |(lo, hi): (usize, usize)| { + let i = merged.partition_point(|s| s.1 <= lo); + merged.get(i).is_some_and(|s| s.0 < hi) + }; + + let stripped = strip_tracked(raw); + let masked: Vec = stripped.raw.iter().map(|r| touches(*r)).collect(); + let pass = track(&stripped.text, rules); + + let mut out = String::with_capacity(pass.text.len()); + let mut in_run = false; + for (b, c) in pass.text.char_indices() { + let extra = !pass.replaced[b] && masked[pass.prov[b].0]; + if extra { + if !in_run && !out.ends_with(placeholder) { + out.push_str(placeholder); + } + in_run = true; + } else { + out.push(c); + in_run = false; + } } - strip_str(&text, SEPARATOR) + out +} + +/// Stripped text with the raw byte range of every output byte. +struct Stripped { + text: String, + raw: Vec<(usize, usize)>, } -fn strip_str(text: &str, sep: char) -> String { - let mut out = String::with_capacity(text.len()); - let mut it = text.chars().peekable(); - while let Some(c) = it.next() { +type Cs = [(usize, char)]; + +fn strip_tracked(text: &str) -> Stripped { + let cs: Vec<(usize, char)> = text.char_indices().collect(); + let end_of = |k: usize| cs.get(k).map_or(text.len(), |x| x.0); + let mut out = Stripped { + text: String::with_capacity(text.len()), + raw: Vec::with_capacity(text.len()), + }; + // A removed sequence becomes one space carrying its whole raw range. + let sep = |out: &mut Stripped, start: usize, end: usize| { + out.text.push(' '); + out.raw.push((start, end)); + }; + let mut i = 0; + while i < cs.len() { + let (start, c) = cs[i]; + i += 1; match c { // `0x9B` followed by a parameter byte is a CSI; a bare one is // only the introducer, so a secret's first character is never // taken for the final byte. '\u{9B}' => { - if matches!(it.peek(), Some(n) if ('\u{20}'..='\u{3F}').contains(n)) { - push_unless_silent(&mut out, sep, skip_csi(&mut it)); + if matches!(cs.get(i), Some(&(_, n)) if ('\u{20}'..='\u{3F}').contains(&n)) { + if !skip_csi(&cs, &mut i) { + sep(&mut out, start, end_of(i)); + } } else { - out.push(sep); + sep(&mut out, start, end_of(i)); } } - '\u{1B}' => match it.peek().copied() { + '\u{1B}' => match cs.get(i).map(|x| x.1) { Some('[') => { - it.next(); - push_unless_silent(&mut out, sep, skip_csi(&mut it)); + i += 1; + if !skip_csi(&cs, &mut i) { + sep(&mut out, start, end_of(i)); + } } Some(']' | 'P' | 'X' | '^' | '_') => { - it.next(); - skip_string(&mut it); - out.push(sep); + i += 1; + skip_string(&cs, &mut i); + sep(&mut out, start, end_of(i)); } // `-` and `.` stay out (a PEM header starts with dashes). Some(' ' | '#' | '%' | '(' | ')' | '*' | '+') => { // Intermediates (`ESC ( B`), then one final byte. - while matches!(it.peek(), Some(' ' | '#' | '%' | '(' | ')' | '*' | '+')) { - it.next(); + while matches!( + cs.get(i), + Some(&(_, ' ' | '#' | '%' | '(' | ')' | '*' | '+')) + ) { + i += 1; } - if matches!(it.peek(), Some(n) if ('\u{30}'..='\u{7E}').contains(n)) { - it.next(); + if matches!(cs.get(i), Some(&(_, n)) if ('\u{30}'..='\u{7E}').contains(&n)) { + i += 1; } - out.push(sep); + sep(&mut out, start, end_of(i)); } // Lone ESC (end of text, line break, printable character): // becomes a space and never eats the character after it, // which may be the first character of a secret. - _ => out.push(sep), + _ => sep(&mut out, start, end_of(i)), }, - _ => out.push(c), + _ => { + out.text.push(c); + let end = end_of(i); + out.raw.extend((start..end).map(|b| (b, b + 1))); + } } } out } -/// Only SGR (`m`) and erase (`K`) leave no trace; every other sequence -/// becomes one space so that it still separates a key from its value. -fn push_unless_silent(out: &mut String, sep: char, silent: bool) { - if !silent { - out.push(sep); - } -} - /// CSI body: parameter/intermediate bytes, then a final byte. Any other /// character (a line break, say) ends the sequence without being consumed. -/// Returns true for an SGR/erase sequence (final byte `m` or `K`). -fn skip_csi(it: &mut std::iter::Peekable>) -> bool { - while let Some(&c) = it.peek() { +/// Returns true for an SGR/erase sequence (final byte `m` or `K`), which +/// leaves no trace; every other sequence becomes one space so that it still +/// separates a key from its value. +fn skip_csi(cs: &Cs, i: &mut usize) -> bool { + while let Some(&(_, c)) = cs.get(*i) { match c { - '\u{20}'..='\u{3F}' => { - it.next(); - } + '\u{20}'..='\u{3F}' => *i += 1, '\u{40}'..='\u{7E}' => { - it.next(); + *i += 1; return matches!(c, 'm' | 'K'); } _ => return false, @@ -143,24 +254,22 @@ fn skip_csi(it: &mut std::iter::Peekable>) -> bool { /// String sequence body: up to `BEL` or `ESC \` (both consumed). A line /// break ends it unconsumed; so does an `ESC` not followed by `\`. -fn skip_string(it: &mut std::iter::Peekable>) { - while let Some(&c) = it.peek() { +fn skip_string(cs: &Cs, i: &mut usize) { + while let Some(&(_, c)) = cs.get(*i) { match c { '\u{7}' => { - it.next(); + *i += 1; return; } '\u{1B}' => { - it.next(); - if it.peek() == Some(&'\\') { - it.next(); + *i += 1; + if cs.get(*i).map(|x| x.1) == Some('\\') { + *i += 1; } return; } '\n' | '\r' => return, - _ => { - it.next(); - } + _ => *i += 1, } } } @@ -271,7 +380,8 @@ mod tests { ("token: abcd\x1b]0;t\x07efghsecretvalue", "[REDACTED]"), ( "https://user:\x1b[2~hunter2pass@host/x", - "https://user:[REDACTED]@host/x", + // The raw view masks the whole URL, so the union does too. + "[REDACTED]", ), ] { assert_eq!(red(input), want, "{input:?}"); @@ -292,9 +402,48 @@ mod tests { "\x1b(B", "\x1b[0m", "\x1b[K", + "\x1b ", + "\x1b(", + "\x1b[", + "\x1b[31;", + "\x1b[ ", + "\u{9b} ", ]) } + #[test] + fn test_incomplete_sequence_before_secret_leaks_nothing() { + let tok = "ghp_abcdefghijklmnopqrstuvwxyz0123456789"; + let akia = "AKIAIOSFODNN7EXAMPLE"; + let cases: Vec<(String, &str)> = vec![ + (format!("x\x1b {tok}"), "abcdefghijkl"), + (format!("x\x1b({tok}"), "abcdefghijkl"), + (format!("x \x1b({akia}"), "IOSFODNN7"), + (format!("x \x1b[{akia}"), "IOSFODNN7"), + (format!("x\x1b[{tok}"), "abcdefghijkl"), + ("\x1b[31;password=hunter2secret".to_string(), "hunter2"), + ("\x1b[ password=hunter2secret".to_string(), "hunter2"), + ("\u{9b} password=hunter2secret".to_string(), "hunter2"), + ("\u{9b} password=hunter2secret".to_string(), "assword"), + ]; + for (input, secret) in cases { + let out = red(&input); + assert!(!out.contains(secret), "{input:?} -> {out:?}"); + assert!(out.contains("[REDACTED]"), "{input:?} -> {out:?}"); + } + assert_eq!( + red("x\x1b ghp_abcdefghijklmnopqrstuvwxyz0123456789"), + "[REDACTED]" + ); + } + + #[test] + fn test_private_use_characters_without_escape_are_unchanged() { + let s = "\u{E000} icon \u{F101} file \u{E0B0}"; + assert_eq!(red(s), s); + assert_eq!(red("\u{E000}password=hunter2secret"), "\u{E000}[REDACTED]"); + } + #[test] fn test_introducer_before_secret_keeps_placeholder_and_absorbs_tail() { assert_eq!( @@ -398,18 +547,12 @@ mod tests { proptest! { #![proptest_config(ProptestConfig::with_cases(300))] - /// Arbitrary escapes in front of and behind a snippet never leave a - /// secret the reference masks in the same input. (Inside a - /// space-free token only SGR/erase is transparent; any other - /// sequence becomes a space by design, see `sgr_wrapped_equals_plain`.) + /// Arbitrary (also incomplete) escapes in front of and behind a snippet + /// never leave a secret the reference masks in the same input. #[test] fn any_escape_never_leaks_what_reference_masks( snip in secret_snippet(), a in any_escape(), c in any_escape(), ) { - // `ESC` followed by one of `] P X ^ _ [` is by definition the - // start of a string/CSI sequence and swallows what follows. - let starts_seq = |t: &str| t.starts_with([']', 'P', 'X', '^', '_', '[']); - prop_assume!(!starts_seq(&snip.text)); let mut text = snip.text.clone(); for secret in &snip.secrets { text = text.replace(secret.as_str(), &format!("{a}{secret}{c}")); diff --git a/docs/specs/0068-security-hardening-prelaunch.md b/docs/specs/0068-security-hardening-prelaunch.md index 2d9779001..caf93253b 100644 --- a/docs/specs/0068-security-hardening-prelaunch.md +++ b/docs/specs/0068-security-hardening-prelaunch.md @@ -54,8 +54,16 @@ Regeln dafür: anderem Endbyte, OSC/DCS/APC …, ein einzelnes `ESC` oder `0x9B`) wird durch genau ein Leerzeichen ersetzt, damit sie Schlüssel und Wert weiterhin trennt und nie ein folgendes Zeichen verschluckt. Text ohne `ESC` bleibt - unverändert, Zeilenumbrüche bleiben erhalten. Das gilt auch für die + unverändert (auch Zeichen aus dem privaten Unicode-Bereich, etwa + Icon-Fonts), Zeilenumbrüche bleiben erhalten. Das gilt auch für die Live-Ausgabe. +- **Nie weniger maskiert als ohne Escape-Behandlung.** Enthält die Ausgabe + eine Escape-Einleitung, gilt die Vereinigung zweier Sichten: die Muster auf + dem Rohtext (wie ohne Escape-Behandlung) und auf dem bereinigten Text. Was + eine Sicht trifft, ist im Ergebnis maskiert; trifft ein Rohtext-Treffer nur + einen Teil einer entfernten Folge, wird der ganze berührte Abschnitt des + bereinigten Textes maskiert. So bleibt auch ein Geheimnis direkt hinter einer + unvollständigen Folge (`ESC␠`, `ESC(`, `ESC[31;`) nicht im Klartext. ## Teil 2 — Lesebefehle auf Secret-Pfade verlangen Bestätigung From 7a2a34fdcb4aa62f80ca2085843aad6d651a33fc Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:22:01 +0000 Subject: [PATCH 12/14] refactor(core): move plain/escape redaction dispatch into terminal_escapes (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/redactor.rs | 18 +++--------------- crates/core/src/ai/terminal_escapes.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/crates/core/src/ai/redactor.rs b/crates/core/src/ai/redactor.rs index feb411dc1..1e1b1dac7 100644 --- a/crates/core/src/ai/redactor.rs +++ b/crates/core/src/ai/redactor.rs @@ -1409,21 +1409,9 @@ impl OutputRedactor for DefaultOutputRedactor { /// erkannt" dem Fail-safe-Prinzip (Spec 0002 Abschnitt 1) angemessener als /// die Redaction bei Nicht-UTF-8-Output ganz zu überspringen. fn redact_bytes(data: &[u8], patterns: &[PatternRule]) -> Vec { - let text = super::terminal_escapes::decode(data); - // Issue #1605: with an escape introducer, mask the union of the raw and - // the stripped view; without one, exactly the plain patterns. - if super::terminal_escapes::has_introducer(&text) { - let rules: Vec<(&Regex, &str)> = - patterns.iter().map(|r| (&r.regex, r.replacement)).collect(); - let masked = super::terminal_escapes::redact_escaped(&text, &rules, REDACTED_PLACEHOLDER); - return absorb_fragments_next_to_placeholders(&masked).into_bytes(); - } - let mut text = text; - for rule in patterns { - if rule.regex.is_match(&text) { - text = rule.regex.replace_all(&text, rule.replacement).into_owned(); - } - } + let rules = patterns.iter().map(|r| (&r.regex, r.replacement)); + // Issue #1605: escape sequences are handled in `terminal_escapes`. + let text = super::terminal_escapes::redact_decoded(data, rules, REDACTED_PLACEHOLDER); absorb_fragments_next_to_placeholders(&text).into_bytes() } diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 663eaef1b..b3bb1fe0f 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -48,6 +48,27 @@ pub(crate) fn has_introducer(text: &str) -> bool { /// Redaction rules: pattern and replacement (as for `Regex::replace_all`). pub(crate) type Rules<'a> = [(&'a regex::Regex, &'a str)]; +/// Decodes `data` and applies the rules in order. Without an escape +/// introducer that is exactly the plain patterns, byte for byte; otherwise +/// see [`redact_escaped`]. +pub(crate) fn redact_decoded<'a>( + data: &[u8], + rules: impl Iterator, + placeholder: &str, +) -> String { + let mut text = decode(data); + if has_introducer(&text) { + let rules: Vec<_> = rules.collect(); + return redact_escaped(&text, &rules, placeholder); + } + for (re, replacement) in rules { + if re.is_match(&text) { + text = re.replace_all(&text, replacement).into_owned(); + } + } + text +} + /// Text after the rules ran, with the origin of every byte. struct Tracked { text: String, From ef1d02ba5177ceb1e8e7d629effed931bb78b969 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 11:58:48 +0000 Subject: [PATCH 13/14] fix(core): one U+FFFD per invalid sequence, exact-output and random-position escape tests (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/terminal_escapes.rs | 104 ++++++++++++++++++++----- 1 file changed, 83 insertions(+), 21 deletions(-) diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index b3bb1fe0f..02cc3c7de 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -30,11 +30,18 @@ pub(crate) fn decode(data: &[u8]) -> String { let mut text = String::with_capacity(data.len()); for chunk in data.utf8_chunks() { text.push_str(chunk.valid()); - for b in chunk.invalid() { - // A raw 0x9B is the 8-bit CSI introducer; it cannot be part of - // valid UTF-8 here. Keep it distinguishable from U+FFFD. - text.push(if *b == 0x9B { '\u{9B}' } else { '\u{FFFD}' }); + let invalid = chunk.invalid(); + if invalid.is_empty() { + continue; } + // One U+FFFD per invalid sequence, as `from_utf8_lossy`. A raw 0x9B + // is the 8-bit CSI introducer (a lone continuation byte, so its own + // chunk); keep it distinguishable from U+FFFD. + text.push(if invalid == [0x9B] { + '\u{9B}' + } else { + '\u{FFFD}' + }); } text } @@ -350,6 +357,23 @@ mod tests { assert_eq!(strip(b"a\xffb"), "a\u{FFFD}b"); } + #[test] + fn test_decode_matches_lossy_without_escape() { + for data in [ + &b"abc\xE2\x82 def"[..], + b"\xF0\x9F\x98", + b"a\xffb\xC3", + b"\xE2\x82\xE2\x82\xAC", + ] { + assert_eq!( + super::decode(data), + String::from_utf8_lossy(data), + "{data:?}" + ); + } + assert_eq!(super::decode(b"x\x9by"), "x\u{9b}y"); + } + // ---- Redaction of coloured output (issue #1605) ---- use crate::ai::redactor_generators::secret_snippet; @@ -437,25 +461,18 @@ mod tests { let tok = "ghp_abcdefghijklmnopqrstuvwxyz0123456789"; let akia = "AKIAIOSFODNN7EXAMPLE"; let cases: Vec<(String, &str)> = vec![ - (format!("x\x1b {tok}"), "abcdefghijkl"), - (format!("x\x1b({tok}"), "abcdefghijkl"), - (format!("x \x1b({akia}"), "IOSFODNN7"), - (format!("x \x1b[{akia}"), "IOSFODNN7"), - (format!("x\x1b[{tok}"), "abcdefghijkl"), - ("\x1b[31;password=hunter2secret".to_string(), "hunter2"), - ("\x1b[ password=hunter2secret".to_string(), "hunter2"), - ("\u{9b} password=hunter2secret".to_string(), "hunter2"), - ("\u{9b} password=hunter2secret".to_string(), "assword"), + (format!("x\x1b {tok}"), "[REDACTED]"), + (format!("x\x1b({tok}"), "[REDACTED]"), + (format!("x \x1b({akia}"), "x [REDACTED]"), + (format!("x \x1b[{akia}"), "x [REDACTED]"), + (format!("x\x1b[{tok}"), "[REDACTED]"), + ("\x1b[31;password=hunter2secret".to_string(), "[REDACTED]"), + ("\x1b[ password=hunter2secret".to_string(), "[REDACTED]"), + ("\u{9b} password=hunter2secret".to_string(), "[REDACTED]"), ]; - for (input, secret) in cases { - let out = red(&input); - assert!(!out.contains(secret), "{input:?} -> {out:?}"); - assert!(out.contains("[REDACTED]"), "{input:?} -> {out:?}"); + for (input, expected) in cases { + assert_eq!(red(&input), expected, "{input:?}"); } - assert_eq!( - red("x\x1b ghp_abcdefghijklmnopqrstuvwxyz0123456789"), - "[REDACTED]" - ); } #[test] @@ -586,6 +603,51 @@ mod tests { } } + /// Escapes inserted at arbitrary char positions (also inside a secret) + /// never leave a literally present secret the reference masks. + #[test] + fn escapes_at_random_positions_never_leak( + snip in secret_snippet(), + inserts in proptest::collection::vec((any::(), any_escape()), 1..6), + ) { + let mut chars: Vec = snip.text.chars().collect(); + // Allowed positions: inside a secret or right after it, or at the + // end (an escape right before it is a known gap, see the PR). An escape swallows a following character, so one in the + // context (`account`, `-b`) would destroy the context, not leak. + let mut allowed = vec![false; chars.len() + 1]; + for secret in &snip.secrets { + let mut from = 0; + while let Some(off) = snip.text[from..].find(secret.as_str()) { + let start = snip.text[..from + off].chars().count(); + for slot in &mut allowed[start + 1..=start + secret.chars().count()] { + *slot = true; + } + from += off + secret.len(); + } + } + allowed[chars.len()] = true; + let slots: Vec = (0..=chars.len()).filter(|i| allowed[*i]).collect(); + // Insert from the back so earlier positions stay valid. + let mut picks: Vec<(usize, &str)> = + inserts.iter().map(|(p, e)| (slots[p % slots.len()], *e)).collect(); + picks.sort_by_key(|x| std::cmp::Reverse(x.0)); + for (at, esc) in picks { + for (i, ch) in esc.chars().enumerate() { + chars.insert(at + i, ch); + } + } + let text: String = chars.into_iter().collect(); + let reference = ReferenceTrait::redact_text(&*REFERENCE, &snip.text); + let out = red(&text); + for secret in snip + .secrets + .iter() + .filter(|s| text.contains(s.as_str()) && !reference.contains(s.as_str())) + { + prop_assert!(!out.contains(secret.as_str()), "{secret:?} in {out:?} (input {text:?})"); + } + } + /// SGR-wrapped secret redacts exactly like the plain text. #[test] fn sgr_wrapped_equals_plain(snip in secret_snippet(), a in sgr(), c in sgr()) { From 933f77a00c73ffea984c61e0d421a712d3a5bfd9 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:29:17 +0000 Subject: [PATCH 14/14] test(core): insert escapes at any slot in the redactor property (#1605) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/ai/terminal_escapes.rs | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/crates/core/src/ai/terminal_escapes.rs b/crates/core/src/ai/terminal_escapes.rs index 02cc3c7de..2b978cdbf 100644 --- a/crates/core/src/ai/terminal_escapes.rs +++ b/crates/core/src/ai/terminal_escapes.rs @@ -603,30 +603,17 @@ mod tests { } } - /// Escapes inserted at arbitrary char positions (also inside a secret) - /// never leave a literally present secret the reference masks. + /// Escapes inserted at any char position (also inside or before a secret) + /// never leave a literally present secret the reference masks in the + /// same escaped input. #[test] fn escapes_at_random_positions_never_leak( snip in secret_snippet(), inserts in proptest::collection::vec((any::(), any_escape()), 1..6), ) { let mut chars: Vec = snip.text.chars().collect(); - // Allowed positions: inside a secret or right after it, or at the - // end (an escape right before it is a known gap, see the PR). An escape swallows a following character, so one in the - // context (`account`, `-b`) would destroy the context, not leak. - let mut allowed = vec![false; chars.len() + 1]; - for secret in &snip.secrets { - let mut from = 0; - while let Some(off) = snip.text[from..].find(secret.as_str()) { - let start = snip.text[..from + off].chars().count(); - for slot in &mut allowed[start + 1..=start + secret.chars().count()] { - *slot = true; - } - from += off + secret.len(); - } - } - allowed[chars.len()] = true; - let slots: Vec = (0..=chars.len()).filter(|i| allowed[*i]).collect(); + // Any insertion slot, including before secrets and in context words. + let slots: Vec = (0..=chars.len()).collect(); // Insert from the back so earlier positions stay valid. let mut picks: Vec<(usize, &str)> = inserts.iter().map(|(p, e)| (slots[p % slots.len()], *e)).collect(); @@ -637,7 +624,7 @@ mod tests { } } let text: String = chars.into_iter().collect(); - let reference = ReferenceTrait::redact_text(&*REFERENCE, &snip.text); + let reference = ReferenceTrait::redact_text(&*REFERENCE, &text); let out = red(&text); for secret in snip .secrets