Skip to main content

ftui_render/
sanitize.rs

1#![forbid(unsafe_code)]
2
3//! Sanitization for untrusted terminal output.
4//!
5//! This module implements the sanitize-by-default policy (ADR-006) to protect
6//! against terminal escape injection attacks. Any untrusted bytes displayed
7//! as logs, tool output, or LLM streams must be treated as **data**, not
8//! executed as terminal control sequences.
9//!
10//! # Threat Model
11//!
12//! Malicious content in logs could:
13//! 1. Manipulate cursor position (break inline mode)
14//! 2. Change terminal colors/modes persistently
15//! 3. Hide text or show fake prompts (social engineering)
16//! 4. Trigger terminal queries that exfiltrate data
17//! 5. Set window title to misleading values
18//!
19//! # Performance
20//!
21//! - **Fast path (95%+ of cases)**: Scan for ESC byte using memchr.
22//!   If no ESC found, content is safe - return borrowed slice.
23//!   Zero allocation in common case, < 100ns for typical log line.
24//!
25//! - **Slow path**: Allocate output buffer, strip control sequences,
26//!   return owned String. Linear in input size.
27//!
28//! # Usage
29//!
30//! ```
31//! use ftui_render::sanitize::sanitize;
32//! use std::borrow::Cow;
33//!
34//! // Fast path - no escapes, returns borrowed
35//! let safe = sanitize("Normal log message");
36//! assert!(matches!(safe, Cow::Borrowed(_)));
37//!
38//! // Slow path - escapes stripped, returns owned
39//! let malicious = sanitize("Evil \x1b[31mred\x1b[0m text");
40//! assert!(matches!(malicious, Cow::Owned(_)));
41//! assert_eq!(malicious.as_ref(), "Evil red text");
42//! ```
43
44use std::borrow::Cow;
45
46use memchr::memchr;
47
48/// Terminal control policy for log output. Stripping is the default.
49#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50pub enum SanitizeMode {
51    /// Remove all escape sequences and forbidden controls.
52    #[default]
53    Strip,
54    /// Preserve bounded SGR styling sequences, but no terminal commands.
55    SgrOnly,
56    /// Pass through trusted text unchanged, including terminal commands.
57    Raw,
58}
59
60/// Apply an explicit terminal control policy.
61pub fn sanitize_with(input: &str, mode: SanitizeMode) -> Cow<'_, str> {
62    match mode {
63        SanitizeMode::Strip => sanitize(input),
64        SanitizeMode::SgrOnly => sanitize_sgr_only(input),
65        SanitizeMode::Raw => Cow::Borrowed(input),
66    }
67}
68
69/// Preserve SGR styling in semi-trusted text while removing terminal commands.
70///
71/// Only `ESC [ <params> m` is allowed, with parameters consisting exclusively
72/// of ASCII digits, semicolons and colons, and a total sequence length of at
73/// most 64 bytes. Other controls follow [`sanitize`]. Unchanged input is
74/// borrowed. Styling may still conceal or recolor text; use [`sanitize`] when
75/// even that is undesirable. The log writer resets styling at line boundaries.
76pub fn sanitize_sgr_only(input: &str) -> Cow<'_, str> {
77    if is_plain_text(input.as_bytes()) {
78        Cow::Borrowed(input)
79    } else {
80        sanitize_slow(input, SanitizeMode::SgrOnly)
81    }
82}
83
84/// Sanitize untrusted text for safe terminal display.
85///
86/// # Fast Path
87/// If no ESC (0x1B) found and no forbidden C0 controls, returns borrowed input
88/// with zero allocation.
89///
90/// # Slow Path
91/// Strips all escape sequences and forbidden C0 controls, returns owned String.
92///
93/// # What Gets Stripped
94/// - ESC (0x1B) and all following CSI/OSC/DCS/APC sequences
95/// - C0 controls except: TAB (0x09), LF (0x0A), CR (0x0D)
96/// - C1 controls (U+0080..U+009F) — these are the 8-bit equivalents of
97///   ESC-prefixed sequences and some terminals honor them
98/// - DEL (0x7F)
99///
100/// # What Gets Preserved
101/// - TAB, LF, CR (allowed control characters)
102/// - All printable ASCII (0x20-0x7E)
103/// - All valid UTF-8 sequences above U+009F
104#[inline]
105pub fn sanitize(input: &str) -> Cow<'_, str> {
106    if is_plain_text(input.as_bytes()) {
107        return Cow::Borrowed(input);
108    }
109
110    // Slow path: strip escape sequences
111    sanitize_slow(input, SanitizeMode::Strip)
112}
113
114#[inline]
115fn is_plain_text(bytes: &[u8]) -> bool {
116    memchr(0x1B, bytes).is_none()
117        && memchr(0x7F, bytes).is_none()
118        && !has_forbidden_c0(bytes)
119        && !has_c1_controls(bytes)
120}
121
122/// Check if any forbidden C0 control characters are present.
123///
124/// Forbidden: 0x00-0x08, 0x0B-0x0C, 0x0E-0x1A, 0x1C-0x1F
125/// Allowed: TAB (0x09), LF (0x0A), CR (0x0D)
126#[inline]
127fn has_forbidden_c0(bytes: &[u8]) -> bool {
128    bytes.iter().any(|&b| is_forbidden_c0(b))
129}
130
131/// Check if a single byte is a forbidden C0 control.
132#[inline]
133const fn is_forbidden_c0(b: u8) -> bool {
134    matches!(
135        b,
136        0x00..=0x08 | 0x0B..=0x0C | 0x0E..=0x1A | 0x1C..=0x1F
137    )
138}
139
140/// Check if any C1 control characters (U+0080..U+009F) are present.
141///
142/// In UTF-8, these are encoded as the two-byte sequence \xC2\x80..\xC2\x9F.
143/// C1 controls include CSI (U+009B), OSC (U+009D), DCS (U+0090), APC (U+009F),
144/// etc. — some terminals honor these as equivalent to their ESC-prefixed forms.
145#[inline]
146fn has_c1_controls(bytes: &[u8]) -> bool {
147    bytes
148        .windows(2)
149        .any(|w| w[0] == 0xC2 && (0x80..=0x9F).contains(&w[1]))
150}
151
152/// Slow path: strip escape sequences and forbidden controls.
153fn sanitize_slow(input: &str, mode: SanitizeMode) -> Cow<'_, str> {
154    let bytes = input.as_bytes();
155    // Allocate only at the first removal, including on the SGR-only path.
156    let mut output: Option<String> = None;
157    let mut kept_from = 0;
158    let mut i = 0;
159
160    while i < bytes.len() {
161        let b = bytes[i];
162        let (end, keep) = match b {
163            // ESC - start of escape sequence
164            0x1B => {
165                let end = skip_escape_sequence(bytes, i);
166                let sequence = &bytes[i..end];
167                let sgr = sequence.len() >= 3
168                    && sequence.len() <= 64
169                    && sequence.starts_with(b"\x1b[")
170                    && sequence.ends_with(b"m")
171                    && sequence[2..sequence.len() - 1]
172                        .iter()
173                        .all(|b| b.is_ascii_digit() || matches!(b, b';' | b':'));
174                (end, mode == SanitizeMode::SgrOnly && sgr)
175            }
176            // Allowed C0 controls: TAB, LF, CR
177            0x09 | 0x0A | 0x0D => (i + 1, true),
178            // Forbidden C0 controls and DEL
179            0x00..=0x08 | 0x0B..=0x0C | 0x0E..=0x1A | 0x1C..=0x1F | 0x7F => (i + 1, false),
180            // Printable ASCII
181            0x20..=0x7E => (i + 1, true),
182            // Start of UTF-8 sequence (high bit set)
183            0x80..=0xFF => {
184                if let Some((c, len)) = decode_utf8_char(&bytes[i..]) {
185                    // Skip C1 controls (U+0080..U+009F) — these are the 8-bit
186                    // equivalents of ESC-prefixed sequences (CSI, OSC, DCS, etc.)
187                    (i + len, !('\u{0080}'..='\u{009F}').contains(&c))
188                } else {
189                    // Invalid UTF-8, skip byte
190                    (i + 1, false)
191                }
192            }
193        };
194        if !keep {
195            output
196                .get_or_insert_with(|| String::with_capacity(input.len()))
197                .push_str(&input[kept_from..i]);
198            kept_from = end;
199        }
200        i = end;
201    }
202
203    match output {
204        Some(mut output) => {
205            output.push_str(&input[kept_from..]);
206            Cow::Owned(output)
207        }
208        None => Cow::Borrowed(input),
209    }
210}
211
212/// Skip over escape sequence, returning index after it.
213///
214/// Handles:
215/// - CSI: ESC [ ... final_byte (0x40-0x7E)
216/// - OSC: ESC ] ... (BEL or ST)
217/// - DCS: ESC P ... ST
218/// - PM: ESC ^ ... ST
219/// - APC: ESC _ ... ST
220/// - SOS: ESC X ... ST
221/// - Single-char escapes: ESC char
222fn skip_escape_sequence(bytes: &[u8], start: usize) -> usize {
223    let mut i = start + 1; // Skip ESC
224    if i >= bytes.len() {
225        return i;
226    }
227
228    match bytes[i] {
229        // CSI sequence: ESC [ params... final_byte
230        b'[' => {
231            i += 1;
232            // Consume parameter bytes (0x30-0x3F) and intermediate bytes (0x20-0x2F)
233            // Stop at final byte (0x40-0x7E)
234            while i < bytes.len() {
235                let b = bytes[i];
236                if (0x40..=0x7E).contains(&b) {
237                    return i + 1;
238                }
239                // Valid parameter/intermediate bytes are 0x20-0x3F
240                if !(0x20..=0x3F).contains(&b) {
241                    // Invalid char in CSI (e.g. newline, control char, or high byte)
242                    // Abort sequence processing to prevent eating valid text
243                    return i;
244                }
245                i += 1;
246            }
247        }
248        // OSC sequence: ESC ] ... (BEL or ST)
249        b']' => {
250            i += 1;
251            while i < bytes.len() {
252                let b = bytes[i];
253                // BEL terminates OSC
254                if b == 0x07 {
255                    return i + 1;
256                }
257                // ST (ESC \) terminates OSC
258                if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
259                    return i + 2;
260                }
261                // 8-bit ST (U+009C, UTF-8 C2 9C) also terminates: real
262                // terminals accept it, so a C1-ST-terminated OSC is properly
263                // terminated — treating it as content would swallow all
264                // following legitimate text to end of input.
265                if b == 0xC2 && i + 1 < bytes.len() && bytes[i + 1] == 0x9C {
266                    return i + 2;
267                }
268                // Lone ESC (not followed by \): abort OSC and let the main loop
269                // re-process this ESC as a potential new escape sequence.
270                if b == 0x1B {
271                    return i;
272                }
273                // Abort on other C0 controls (e.g. newline) to prevent swallowing logs
274                if b < 0x20 {
275                    return i;
276                }
277                i += 1;
278            }
279        }
280        // DCS/PM/APC/SOS: ESC P/^/_/X ... ST
281        b'P' | b'^' | b'_' | b'X' => {
282            i += 1;
283            while i < bytes.len() {
284                let b = bytes[i];
285                // ST (ESC \) terminates
286                if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
287                    return i + 2;
288                }
289                // 8-bit ST (U+009C) terminates, as in the OSC arm above.
290                if b == 0xC2 && i + 1 < bytes.len() && bytes[i + 1] == 0x9C {
291                    return i + 2;
292                }
293                // Lone ESC (not followed by \): abort and let the main loop
294                // re-process this ESC as a potential new escape sequence.
295                if b == 0x1B {
296                    return i;
297                }
298                // Abort on C0 controls
299                if b < 0x20 {
300                    return i;
301                }
302                i += 1;
303            }
304        }
305        // Single-char escape sequences (ESC followed by 0x20-0x7E)
306        0x20..=0x7E => {
307            return i + 1;
308        }
309        // Unknown or invalid - just skip the ESC
310        _ => {}
311    }
312
313    i
314}
315
316/// Decode a single UTF-8 character from byte slice.
317///
318/// Returns the character and number of bytes consumed, or None if invalid.
319fn decode_utf8_char(bytes: &[u8]) -> Option<(char, usize)> {
320    if bytes.is_empty() {
321        return None;
322    }
323
324    let first = bytes[0];
325    let (expected_len, mut codepoint) = match first {
326        0x00..=0x7F => return Some((first as char, 1)),
327        0xC0..=0xDF => (2, (first & 0x1F) as u32),
328        0xE0..=0xEF => (3, (first & 0x0F) as u32),
329        0xF0..=0xF7 => (4, (first & 0x07) as u32),
330        _ => return None, // Invalid lead byte
331    };
332
333    if bytes.len() < expected_len {
334        return None;
335    }
336
337    // Process continuation bytes
338    for &b in bytes.iter().take(expected_len).skip(1) {
339        if (b & 0xC0) != 0x80 {
340            return None; // Invalid continuation byte
341        }
342        codepoint = (codepoint << 6) | (b & 0x3F) as u32;
343    }
344
345    // Reject overlong encodings (RFC 3629)
346    let min_codepoint = match expected_len {
347        2 => 0x80,
348        3 => 0x800,
349        4 => 0x1_0000,
350        _ => return None,
351    };
352    if codepoint < min_codepoint {
353        return None;
354    }
355
356    // Validate codepoint
357    char::from_u32(codepoint).map(|c| (c, expected_len))
358}
359
360/// Text with trust level annotation.
361///
362/// Use this to explicitly mark whether text has been sanitized or comes
363/// from a trusted source.
364#[derive(Debug, Clone, PartialEq, Eq)]
365pub enum Text<'a> {
366    /// Sanitized text (escape sequences stripped).
367    Sanitized(Cow<'a, str>),
368
369    /// Text allowing SGR styling but no terminal commands.
370    SgrOnly(Cow<'a, str>),
371
372    /// Trusted text (may contain ANSI sequences).
373    /// Only use with content from trusted sources.
374    Trusted(Cow<'a, str>),
375}
376
377impl<'a> Text<'a> {
378    /// Create sanitized text from an untrusted source.
379    #[inline]
380    pub fn sanitized(s: &'a str) -> Self {
381        Text::Sanitized(sanitize(s))
382    }
383
384    /// Create text allowing only bounded SGR styling sequences.
385    pub fn sgr_only(s: &'a str) -> Self {
386        Text::SgrOnly(sanitize_sgr_only(s))
387    }
388
389    /// Control policy to apply again at the final emission boundary.
390    #[must_use]
391    pub const fn mode(&self) -> SanitizeMode {
392        match self {
393            Self::Sanitized(_) => SanitizeMode::Strip,
394            Self::SgrOnly(_) => SanitizeMode::SgrOnly,
395            Self::Trusted(_) => SanitizeMode::Raw,
396        }
397    }
398
399    /// Create from a trusted source (ANSI sequences allowed).
400    ///
401    /// # Safety
402    /// Only use with content from trusted sources. Untrusted content
403    /// can corrupt terminal state or deceive users.
404    #[inline]
405    pub fn trusted(s: &'a str) -> Self {
406        Text::Trusted(Cow::Borrowed(s))
407    }
408
409    /// Create owned sanitized text.
410    #[inline]
411    pub fn sanitized_owned(s: String) -> Self {
412        match sanitize(&s) {
413            Cow::Borrowed(_) => Text::Sanitized(Cow::Owned(s)),
414            Cow::Owned(owned) => Text::Sanitized(Cow::Owned(owned)),
415        }
416    }
417
418    /// Create owned trusted text.
419    #[inline]
420    pub fn trusted_owned(s: String) -> Self {
421        Text::Trusted(Cow::Owned(s))
422    }
423
424    /// Get the inner string slice.
425    #[inline]
426    #[must_use]
427    pub fn as_str(&self) -> &str {
428        match self {
429            Text::Sanitized(cow) | Text::SgrOnly(cow) | Text::Trusted(cow) => cow.as_ref(),
430        }
431    }
432
433    /// Check if this text is sanitized.
434    #[inline]
435    #[must_use]
436    pub fn is_sanitized(&self) -> bool {
437        matches!(self, Text::Sanitized(_))
438    }
439
440    /// Check if this text is trusted.
441    #[inline]
442    #[must_use]
443    pub fn is_trusted(&self) -> bool {
444        matches!(self, Text::Trusted(_))
445    }
446
447    /// Convert to owned version.
448    pub fn into_owned(self) -> Text<'static> {
449        match self {
450            Text::Sanitized(cow) => Text::Sanitized(Cow::Owned(cow.into_owned())),
451            Text::SgrOnly(cow) => Text::SgrOnly(Cow::Owned(cow.into_owned())),
452            Text::Trusted(cow) => Text::Trusted(Cow::Owned(cow.into_owned())),
453        }
454    }
455}
456
457impl AsRef<str> for Text<'_> {
458    fn as_ref(&self) -> &str {
459        self.as_str()
460    }
461}
462
463impl std::fmt::Display for Text<'_> {
464    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
465        write!(f, "{}", self.as_str())
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    use super::*;
472
473    #[test]
474    fn sgr_only_borrows_allowed_styles_and_plain_text() {
475        for input in [
476            "",
477            "plain 世界\ttext\n",
478            "\x1b[mreset",
479            "\x1b[1;31mred\x1b[0m",
480            "\x1b[38;2;255;128;0mRGB",
481            "\x1b[38:2::255:128:0mRGB\x1b[4:3munderline",
482        ] {
483            let result = sanitize_sgr_only(input);
484            assert!(matches!(result, Cow::Borrowed(_)), "{input:?}");
485            assert_eq!(result, input);
486        }
487    }
488
489    #[test]
490    fn sgr_only_rejects_terminal_commands_and_non_sgr_parameters() {
491        for command in [
492            "\x1b[2J",
493            "\x1b[3J",
494            "\x1b[H",
495            "\x1b[?1049h",
496            "\x1b[?25l",
497            "\x1b[1;20r",
498            "\x1b[?31m",
499            "\x1b[>4m",
500            "\x1b[1 m",
501            "\x1b]0;title\x07",
502            "\x1b]52;c;secret\x1b\\",
503            "\x1b]8;;https://example.com\x1b\\",
504            "\x1bPsecret\x1b\\",
505            "\x1b_secret\x1b\\",
506            "\x1b^secret\x1b\\",
507            "\x1bXsecret\x1b\\",
508            "\x1bXsecret\u{009c}",
509            "\x1b7",
510            "\x1bc",
511            "\x00\x08\x0b\x0c\x1f\x7f\u{0080}\u{009b}\u{009f}",
512        ] {
513            let input = format!("before{command}\x1b[32mafter");
514            assert_eq!(
515                sanitize_sgr_only(&input),
516                "before\x1b[32mafter",
517                "{command:?}"
518            );
519            assert_eq!(sanitize(&input), "beforeafter", "{command:?}");
520        }
521    }
522
523    #[test]
524    fn sgr_only_bounds_whole_sequences_and_drops_incomplete_ones() {
525        let allowed = format!("\x1b[{}m", "1".repeat(61));
526        assert_eq!(allowed.len(), 64);
527        assert!(matches!(sanitize_sgr_only(&allowed), Cow::Borrowed(_)));
528        let too_long = format!("\x1b[{}m", "1".repeat(62));
529        assert_eq!(sanitize_sgr_only(&format!("{too_long}text")), "text");
530        for input in ["text\x1b", "text\x1b[", "text\x1b[31", "text\x1b]title"] {
531            assert_eq!(sanitize_sgr_only(input), "text");
532        }
533        assert_eq!(sanitize_sgr_only("\x1b[31\ntext"), "\ntext");
534        assert_eq!(sanitize_sgr_only("\x1b[31世界"), "世界");
535    }
536
537    #[test]
538    fn text_modes_and_owned_sgr_preserve_the_selected_policy() {
539        let input = "\x1b[31mred\x1b[2J";
540        let styled = Text::sgr_only(input).into_owned();
541        assert_eq!(styled.as_str(), "\x1b[31mred");
542        assert_eq!(styled.mode(), SanitizeMode::SgrOnly);
543        assert!(!styled.is_trusted());
544        assert_eq!(Text::sanitized(input).mode(), SanitizeMode::Strip);
545        assert_eq!(Text::trusted(input).mode(), SanitizeMode::Raw);
546        assert_eq!(sanitize_with(input, SanitizeMode::default()), "red");
547        assert_eq!(sanitize_with(input, SanitizeMode::SgrOnly), styled.as_str());
548        assert!(matches!(sanitize_with(input, SanitizeMode::Raw), Cow::Borrowed(s) if s == input));
549    }
550
551    // ============== Fast Path Tests ==============
552
553    #[test]
554    fn fast_path_no_escape() {
555        let input = "Normal log message without escapes";
556        let result = sanitize(input);
557        assert!(matches!(result, Cow::Borrowed(_)));
558        assert_eq!(result.as_ref(), input);
559    }
560
561    #[test]
562    fn fast_path_with_allowed_controls() {
563        let input = "Line1\nLine2\tTabbed\rCarriage";
564        let result = sanitize(input);
565        assert!(matches!(result, Cow::Borrowed(_)));
566        assert_eq!(result.as_ref(), input);
567    }
568
569    #[test]
570    fn fast_path_unicode() {
571        let input = "Hello \u{4e16}\u{754c} \u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}";
572        let result = sanitize(input);
573        assert!(matches!(result, Cow::Borrowed(_)));
574        assert_eq!(result.as_ref(), input);
575    }
576
577    #[test]
578    fn fast_path_empty() {
579        let input = "";
580        let result = sanitize(input);
581        assert!(matches!(result, Cow::Borrowed(_)));
582        assert_eq!(result.as_ref(), "");
583    }
584
585    #[test]
586    fn fast_path_printable_ascii() {
587        let input = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
588        let result = sanitize(input);
589        assert!(matches!(result, Cow::Borrowed(_)));
590        assert_eq!(result.as_ref(), input);
591    }
592
593    // ============== Slow Path: CSI Sequences ==============
594
595    #[test]
596    fn slow_path_strips_sgr_color() {
597        let input = "Hello \x1b[31mred\x1b[0m world";
598        let result = sanitize(input);
599        assert!(matches!(result, Cow::Owned(_)));
600        assert_eq!(result.as_ref(), "Hello red world");
601    }
602
603    #[test]
604    fn slow_path_strips_cursor_movement() {
605        let input = "Before\x1b[2;5HAfter";
606        let result = sanitize(input);
607        assert_eq!(result.as_ref(), "BeforeAfter");
608    }
609
610    #[test]
611    fn slow_path_strips_erase() {
612        let input = "Text\x1b[2JCleared";
613        let result = sanitize(input);
614        assert_eq!(result.as_ref(), "TextCleared");
615    }
616
617    #[test]
618    fn slow_path_strips_multiple_sequences() {
619        let input = "\x1b[1mBold\x1b[0m \x1b[4mUnderline\x1b[24m \x1b[38;5;196mColor\x1b[0m";
620        let result = sanitize(input);
621        assert_eq!(result.as_ref(), "Bold Underline Color");
622    }
623
624    // ============== Slow Path: OSC Sequences ==============
625
626    #[test]
627    fn slow_path_strips_osc_title_bel() {
628        // OSC 0: set title, terminated by BEL
629        let input = "Text\x1b]0;Evil Title\x07More";
630        let result = sanitize(input);
631        assert_eq!(result.as_ref(), "TextMore");
632    }
633
634    #[test]
635    fn slow_path_strips_osc_title_st() {
636        // OSC 0: set title, terminated by ST
637        let input = "Text\x1b]0;Evil Title\x1b\\More";
638        let result = sanitize(input);
639        assert_eq!(result.as_ref(), "TextMore");
640    }
641
642    #[test]
643    fn slow_path_strips_osc8_hyperlink() {
644        // OSC 8: hyperlink
645        let input = "Click \x1b]8;;https://evil.com\x07here\x1b]8;;\x07 please";
646        let result = sanitize(input);
647        assert_eq!(result.as_ref(), "Click here please");
648    }
649
650    #[test]
651    fn osc_terminated_by_c1_st_does_not_swallow_following_text() {
652        // Regression: the OSC skipper only knew BEL and ESC-\ terminators.
653        // The 8-bit ST (U+009C) — which real terminals accept — was consumed
654        // as content, so everything after a C1-ST-terminated OSC was
655        // swallowed to end of input.
656        let input = "Before\x1b]0;title\u{009C}hello world";
657        let result = sanitize(input);
658        assert_eq!(result.as_ref(), "Beforehello world");
659    }
660
661    #[test]
662    fn dcs_pm_apc_terminated_by_c1_st_do_not_swallow_following_text() {
663        for intro in ['P', '^', '_'] {
664            let input = format!("Before\x1b{intro}payload\u{009C}after");
665            let result = sanitize(&input);
666            assert_eq!(
667                result.as_ref(),
668                "Beforeafter",
669                "introducer {intro:?}: text after C1 ST swallowed"
670            );
671        }
672    }
673
674    // ============== Slow Path: DCS/PM/APC ==============
675
676    #[test]
677    fn slow_path_strips_dcs() {
678        let input = "Before\x1bPdevice control string\x1b\\After";
679        let result = sanitize(input);
680        assert_eq!(result.as_ref(), "BeforeAfter");
681    }
682
683    #[test]
684    fn slow_path_strips_apc() {
685        let input = "Before\x1b_application program command\x1b\\After";
686        let result = sanitize(input);
687        assert_eq!(result.as_ref(), "BeforeAfter");
688    }
689
690    #[test]
691    fn slow_path_strips_pm() {
692        let input = "Before\x1b^privacy message\x1b\\After";
693        let result = sanitize(input);
694        assert_eq!(result.as_ref(), "BeforeAfter");
695    }
696
697    #[test]
698    fn slow_path_strips_osc52_clipboard() {
699        let input = "Before\x1b]52;c;SGVsbG8=\x07After";
700        let result = sanitize(input);
701        assert_eq!(result.as_ref(), "BeforeAfter");
702    }
703
704    #[test]
705    fn slow_path_strips_osc52_clipboard_st() {
706        let input = "Before\x1b]52;c;SGVsbG8=\x1b\\After";
707        let result = sanitize(input);
708        assert_eq!(result.as_ref(), "BeforeAfter");
709    }
710
711    #[test]
712    fn slow_path_strips_private_modes() {
713        let input = "A\x1b[?1049hB\x1b[?1000hC\x1b[?2004hD";
714        let result = sanitize(input);
715        assert_eq!(result.as_ref(), "ABCD");
716    }
717
718    // ============== Slow Path: C0 Controls ==============
719
720    #[test]
721    fn slow_path_strips_nul() {
722        let input = "Hello\x00World";
723        let result = sanitize(input);
724        assert_eq!(result.as_ref(), "HelloWorld");
725    }
726
727    #[test]
728    fn slow_path_strips_bel() {
729        // BEL (0x07) outside of OSC should be stripped
730        let input = "Hello\x07World";
731        let result = sanitize(input);
732        assert_eq!(result.as_ref(), "HelloWorld");
733    }
734
735    #[test]
736    fn slow_path_strips_backspace() {
737        let input = "Hello\x08World";
738        let result = sanitize(input);
739        assert_eq!(result.as_ref(), "HelloWorld");
740    }
741
742    #[test]
743    fn slow_path_strips_form_feed() {
744        let input = "Hello\x0CWorld";
745        let result = sanitize(input);
746        assert_eq!(result.as_ref(), "HelloWorld");
747    }
748
749    #[test]
750    fn slow_path_strips_vertical_tab() {
751        let input = "Hello\x0BWorld";
752        let result = sanitize(input);
753        assert_eq!(result.as_ref(), "HelloWorld");
754    }
755
756    #[test]
757    fn slow_path_strips_del() {
758        let input = "Hello\x7FWorld";
759        let result = sanitize(input);
760        assert_eq!(result.as_ref(), "HelloWorld");
761    }
762
763    #[test]
764    fn slow_path_preserves_tab_lf_cr() {
765        let input = "Line1\nLine2\tTabbed\rReturn";
766        // This should trigger slow path due to needing to scan
767        // but preserve tab/lf/cr
768        let result = sanitize(input);
769        assert_eq!(result.as_ref(), "Line1\nLine2\tTabbed\rReturn");
770    }
771
772    // ============== Edge Cases ==============
773
774    #[test]
775    fn handles_truncated_csi() {
776        let input = "Hello\x1b[";
777        let result = sanitize(input);
778        assert!(!result.contains('\x1b'));
779        assert_eq!(result.as_ref(), "Hello");
780    }
781
782    #[test]
783    fn handles_truncated_dcs() {
784        let input = "Hello\x1bP1;2;3";
785        let result = sanitize(input);
786        assert!(!result.contains('\x1b'));
787        assert_eq!(result.as_ref(), "Hello");
788    }
789
790    #[test]
791    fn handles_truncated_apc() {
792        let input = "Hello\x1b_test";
793        let result = sanitize(input);
794        assert!(!result.contains('\x1b'));
795        assert_eq!(result.as_ref(), "Hello");
796    }
797
798    #[test]
799    fn handles_truncated_pm() {
800        let input = "Hello\x1b^secret";
801        let result = sanitize(input);
802        assert!(!result.contains('\x1b'));
803        assert_eq!(result.as_ref(), "Hello");
804    }
805
806    #[test]
807    fn handles_truncated_osc() {
808        let input = "Hello\x1b]0;Title";
809        let result = sanitize(input);
810        assert!(!result.contains('\x1b'));
811        assert_eq!(result.as_ref(), "Hello");
812    }
813
814    #[test]
815    fn handles_esc_at_end() {
816        let input = "Hello\x1b";
817        let result = sanitize(input);
818        assert_eq!(result.as_ref(), "Hello");
819    }
820
821    #[test]
822    fn handles_lone_esc() {
823        let input = "\x1b";
824        let result = sanitize(input);
825        assert_eq!(result.as_ref(), "");
826    }
827
828    #[test]
829    fn handles_single_char_escape() {
830        // ESC 7 (save cursor) and ESC 8 (restore cursor)
831        let input = "Before\x1b7Middle\x1b8After";
832        let result = sanitize(input);
833        assert_eq!(result.as_ref(), "BeforeMiddleAfter");
834    }
835
836    #[test]
837    fn handles_unknown_escape() {
838        // ESC followed by a byte that's not a valid escape introducer
839        // Using a valid printable byte that's not a known escape char
840        let input = "Before\x1b!After";
841        let result = sanitize(input);
842        // Single-char escape: ESC ! gets stripped
843        assert_eq!(result.as_ref(), "BeforeAfter");
844    }
845
846    // ============== Unicode Tests ==============
847
848    #[test]
849    fn preserves_unicode_characters() {
850        let input = "\u{4e16}\u{754c}"; // Chinese characters
851        let result = sanitize(input);
852        assert_eq!(result.as_ref(), "\u{4e16}\u{754c}");
853    }
854
855    #[test]
856    fn preserves_emoji() {
857        let input = "\u{1f600}\u{1f389}\u{1f680}"; // Emoji
858        let result = sanitize(input);
859        assert_eq!(result.as_ref(), "\u{1f600}\u{1f389}\u{1f680}");
860    }
861
862    #[test]
863    fn preserves_combining_characters() {
864        // e with combining acute accent
865        let input = "e\u{0301}";
866        let result = sanitize(input);
867        assert_eq!(result.as_ref(), "e\u{0301}");
868    }
869
870    #[test]
871    fn mixed_unicode_and_escapes() {
872        let input = "\u{4e16}\x1b[31m\u{754c}\x1b[0m";
873        let result = sanitize(input);
874        assert_eq!(result.as_ref(), "\u{4e16}\u{754c}");
875    }
876
877    // ============== Text Type Tests ==============
878
879    #[test]
880    fn text_sanitized() {
881        let text = Text::sanitized("Hello \x1b[31mWorld\x1b[0m");
882        assert!(text.is_sanitized());
883        assert!(!text.is_trusted());
884        assert_eq!(text.as_str(), "Hello World");
885    }
886
887    #[test]
888    fn text_trusted() {
889        let text = Text::trusted("Hello \x1b[31mWorld\x1b[0m");
890        assert!(!text.is_sanitized());
891        assert!(text.is_trusted());
892        assert_eq!(text.as_str(), "Hello \x1b[31mWorld\x1b[0m");
893    }
894
895    #[test]
896    fn text_into_owned() {
897        let text = Text::sanitized("Hello");
898        let owned = text.into_owned();
899        assert!(owned.is_sanitized());
900        assert_eq!(owned.as_str(), "Hello");
901    }
902
903    #[test]
904    fn text_display() {
905        let text = Text::sanitized("Hello");
906        assert_eq!(format!("{text}"), "Hello");
907    }
908
909    // ============== Property Tests (basic) ==============
910
911    #[test]
912    fn output_never_contains_esc() {
913        let inputs = [
914            "Normal text",
915            "\x1b[31mRed\x1b[0m",
916            "\x1b]0;Title\x07",
917            "\x1bPDCS\x1b\\",
918            "Mixed\x1b[1m\x1b]8;;url\x07text\x1b]8;;\x07\x1b[0m",
919            "",
920            "\x1b",
921            "\x1b[",
922            "\x1b]",
923        ];
924
925        for input in inputs {
926            let result = sanitize(input);
927            assert!(
928                !result.contains('\x1b'),
929                "Output contains ESC for input: {input:?}"
930            );
931        }
932    }
933
934    #[test]
935    fn output_never_contains_forbidden_c0() {
936        let inputs = [
937            "\x00\x01\x02\x03\x04\x05\x06\x07",
938            "\x08\x0B\x0C\x0E\x0F",
939            "\x10\x11\x12\x13\x14\x15\x16\x17",
940            "\x18\x19\x1A\x1C\x1D\x1E\x1F",
941            "Mixed\x00text\x07with\x0Ccontrols",
942        ];
943
944        for input in inputs {
945            let result = sanitize(input);
946            for b in result.as_bytes() {
947                assert!(
948                    !is_forbidden_c0(*b),
949                    "Output contains forbidden C0 0x{b:02X} for input: {input:?}"
950                );
951            }
952        }
953    }
954
955    #[test]
956    fn allowed_controls_preserved_in_output() {
957        let input = "Tab\there\nNewline\rCarriage";
958        let result = sanitize(input);
959        assert!(result.contains('\t'));
960        assert!(result.contains('\n'));
961        assert!(result.contains('\r'));
962    }
963
964    // ============== Decode UTF-8 Tests ==============
965
966    #[test]
967    fn decode_ascii() {
968        let bytes = b"A";
969        let result = decode_utf8_char(bytes);
970        assert_eq!(result, Some(('A', 1)));
971    }
972
973    #[test]
974    fn decode_two_byte() {
975        let bytes = "\u{00E9}".as_bytes(); // é
976        let result = decode_utf8_char(bytes);
977        assert_eq!(result, Some(('\u{00E9}', 2)));
978    }
979
980    #[test]
981    fn decode_three_byte() {
982        let bytes = "\u{4e16}".as_bytes(); // Chinese
983        let result = decode_utf8_char(bytes);
984        assert_eq!(result, Some(('\u{4e16}', 3)));
985    }
986
987    #[test]
988    fn decode_four_byte() {
989        let bytes = "\u{1f600}".as_bytes(); // Emoji
990        let result = decode_utf8_char(bytes);
991        assert_eq!(result, Some(('\u{1f600}', 4)));
992    }
993
994    #[test]
995    fn decode_invalid_lead() {
996        let bytes = &[0xFF];
997        let result = decode_utf8_char(bytes);
998        assert_eq!(result, None);
999    }
1000
1001    #[test]
1002    fn decode_truncated() {
1003        let bytes = &[0xC2]; // Incomplete 2-byte sequence
1004        let result = decode_utf8_char(bytes);
1005        assert_eq!(result, None);
1006    }
1007
1008    #[test]
1009    fn decode_invalid_continuation() {
1010        let bytes = &[0xC2, 0x00]; // Invalid continuation byte
1011        let result = decode_utf8_char(bytes);
1012        assert_eq!(result, None);
1013    }
1014
1015    // ================================================================
1016    // Adversarial Security Tests (bd-397)
1017    //
1018    // Tests below exercise the specific threat model from ADR-006:
1019    //   1. Log injection / cursor corruption
1020    //   2. Title injection (OSC 0)
1021    //   3. Clipboard hijacking (OSC 52)
1022    //   4. Terminal mode hijacking
1023    //   5. Data exfiltration via terminal queries
1024    //   6. Social engineering via fake prompts
1025    //   7. C1 control code injection
1026    //   8. Sequence terminator confusion
1027    //   9. DoS via large / deeply nested payloads
1028    //  10. Combined / chained attacks
1029    // ================================================================
1030
1031    // ---- 1. Log injection / cursor corruption ----
1032
1033    #[test]
1034    fn adversarial_clear_screen() {
1035        let input = "\x1b[2J";
1036        let result = sanitize(input);
1037        assert_eq!(result.as_ref(), "");
1038    }
1039
1040    #[test]
1041    fn adversarial_home_cursor() {
1042        let input = "visible\x1b[Hhidden";
1043        let result = sanitize(input);
1044        assert_eq!(result.as_ref(), "visiblehidden");
1045    }
1046
1047    #[test]
1048    fn adversarial_cursor_absolute_position() {
1049        let input = "ok\x1b[999;999Hmalicious";
1050        let result = sanitize(input);
1051        assert_eq!(result.as_ref(), "okmalicious");
1052    }
1053
1054    #[test]
1055    fn adversarial_scroll_up() {
1056        let input = "text\x1b[5Smore";
1057        let result = sanitize(input);
1058        assert_eq!(result.as_ref(), "textmore");
1059    }
1060
1061    #[test]
1062    fn adversarial_scroll_down() {
1063        let input = "text\x1b[5Tmore";
1064        let result = sanitize(input);
1065        assert_eq!(result.as_ref(), "textmore");
1066    }
1067
1068    #[test]
1069    fn adversarial_erase_line() {
1070        let input = "secret\x1b[2Koverwrite";
1071        let result = sanitize(input);
1072        assert_eq!(result.as_ref(), "secretoverwrite");
1073    }
1074
1075    #[test]
1076    fn adversarial_insert_delete_lines() {
1077        let input = "text\x1b[10Linserted\x1b[5Mdeleted";
1078        let result = sanitize(input);
1079        assert_eq!(result.as_ref(), "textinserteddeleted");
1080    }
1081
1082    // ---- 2. Title injection (OSC 0, 1, 2) ----
1083
1084    #[test]
1085    fn adversarial_osc0_title_injection() {
1086        let input = "\x1b]0;PWNED - Enter Password\x07";
1087        let result = sanitize(input);
1088        assert_eq!(result.as_ref(), "");
1089        assert!(!result.contains('\x1b'));
1090        assert!(!result.contains('\x07'));
1091    }
1092
1093    #[test]
1094    fn adversarial_osc1_icon_title() {
1095        let input = "\x1b]1;evil-icon\x07";
1096        let result = sanitize(input);
1097        assert_eq!(result.as_ref(), "");
1098    }
1099
1100    #[test]
1101    fn adversarial_osc2_window_title() {
1102        let input = "\x1b]2;sudo password required\x1b\\";
1103        let result = sanitize(input);
1104        assert_eq!(result.as_ref(), "");
1105    }
1106
1107    // ---- 3. Clipboard hijacking (OSC 52) ----
1108
1109    #[test]
1110    fn adversarial_osc52_clipboard_set_bel() {
1111        // Set clipboard to "rm -rf /" encoded in base64
1112        let input = "safe\x1b]52;c;cm0gLXJmIC8=\x07text";
1113        let result = sanitize(input);
1114        assert_eq!(result.as_ref(), "safetext");
1115    }
1116
1117    #[test]
1118    fn adversarial_osc52_clipboard_set_st() {
1119        let input = "safe\x1b]52;c;cm0gLXJmIC8=\x1b\\text";
1120        let result = sanitize(input);
1121        assert_eq!(result.as_ref(), "safetext");
1122    }
1123
1124    #[test]
1125    fn adversarial_osc52_clipboard_query() {
1126        // Query clipboard (could exfiltrate data)
1127        let input = "\x1b]52;c;?\x07";
1128        let result = sanitize(input);
1129        assert_eq!(result.as_ref(), "");
1130    }
1131
1132    // ---- 4. Terminal mode hijacking ----
1133
1134    #[test]
1135    fn adversarial_alt_screen_enable() {
1136        let input = "\x1b[?1049h";
1137        let result = sanitize(input);
1138        assert_eq!(result.as_ref(), "");
1139    }
1140
1141    #[test]
1142    fn adversarial_alt_screen_disable() {
1143        let input = "\x1b[?1049l";
1144        let result = sanitize(input);
1145        assert_eq!(result.as_ref(), "");
1146    }
1147
1148    #[test]
1149    fn adversarial_mouse_enable() {
1150        let input = "\x1b[?1000h\x1b[?1002h\x1b[?1003h\x1b[?1006h";
1151        let result = sanitize(input);
1152        assert_eq!(result.as_ref(), "");
1153    }
1154
1155    #[test]
1156    fn adversarial_bracketed_paste_enable() {
1157        let input = "\x1b[?2004h";
1158        let result = sanitize(input);
1159        assert_eq!(result.as_ref(), "");
1160    }
1161
1162    #[test]
1163    fn adversarial_focus_events_enable() {
1164        let input = "\x1b[?1004h";
1165        let result = sanitize(input);
1166        assert_eq!(result.as_ref(), "");
1167    }
1168
1169    #[test]
1170    fn adversarial_raw_mode_sequence() {
1171        // Attempt to set raw mode
1172        let input = "\x1b[?7727h";
1173        let result = sanitize(input);
1174        assert_eq!(result.as_ref(), "");
1175    }
1176
1177    #[test]
1178    fn adversarial_cursor_hide_show() {
1179        let input = "\x1b[?25l\x1b[?25h";
1180        let result = sanitize(input);
1181        assert_eq!(result.as_ref(), "");
1182    }
1183
1184    // ---- 5. Data exfiltration via terminal queries ----
1185
1186    #[test]
1187    fn adversarial_device_attributes_query_da1() {
1188        let input = "\x1b[c";
1189        let result = sanitize(input);
1190        assert_eq!(result.as_ref(), "");
1191    }
1192
1193    #[test]
1194    fn adversarial_device_attributes_query_da2() {
1195        let input = "\x1b[>c";
1196        let result = sanitize(input);
1197        assert_eq!(result.as_ref(), "");
1198    }
1199
1200    #[test]
1201    fn adversarial_device_status_report() {
1202        let input = "\x1b[6n";
1203        let result = sanitize(input);
1204        assert_eq!(result.as_ref(), "");
1205    }
1206
1207    #[test]
1208    fn adversarial_osc_color_query() {
1209        // Query background color (OSC 11)
1210        let input = "\x1b]11;?\x07";
1211        let result = sanitize(input);
1212        assert_eq!(result.as_ref(), "");
1213    }
1214
1215    #[test]
1216    fn adversarial_decrpm_query() {
1217        let input = "\x1b[?2026$p";
1218        let result = sanitize(input);
1219        assert_eq!(result.as_ref(), "");
1220    }
1221
1222    // ---- 6. Social engineering via fake prompts ----
1223
1224    #[test]
1225    fn adversarial_fake_shell_prompt() {
1226        // Try to move cursor to create a fake prompt
1227        let input = "\x1b[999;1H\x1b[2K$ sudo rm -rf /\x1b[A";
1228        let result = sanitize(input);
1229        assert!(!result.contains('\x1b'));
1230        // Only text content should survive
1231        assert_eq!(result.as_ref(), "$ sudo rm -rf /");
1232    }
1233
1234    #[test]
1235    fn adversarial_fake_password_prompt() {
1236        // Combine title set + cursor move + fake prompt
1237        let input = "\x1b]0;Terminal\x07\x1b[2J\x1b[HPassword: ";
1238        let result = sanitize(input);
1239        assert_eq!(result.as_ref(), "Password: ");
1240    }
1241
1242    #[test]
1243    fn adversarial_overwrite_existing_content() {
1244        // Try to use backspaces + CR to overwrite existing output
1245        let input = "safe output\r\x1b[2Kmalicious replacement";
1246        let result = sanitize(input);
1247        assert_eq!(result.as_ref(), "safe output\rmalicious replacement");
1248    }
1249
1250    // ---- 7. C1 control codes (single-byte, 0x80-0x9F) ----
1251    //
1252    // In ISO-8859-1, 0x80-0x9F are C1 control characters.
1253    // In UTF-8, these byte values are continuation bytes and should
1254    // be handled by the UTF-8 decoder (invalid as leading bytes).
1255    // The sanitizer should not let them through as control codes.
1256
1257    #[test]
1258    fn adversarial_c1_single_byte_csi() {
1259        // U+009B is the C1 equivalent of ESC [ (CSI)
1260        // Some terminals treat this as a CSI introducer, so it MUST be stripped.
1261        let input = "text\u{009B}31mmalicious";
1262        let result = sanitize(input);
1263        assert!(!result.contains('\x1b'));
1264        assert!(
1265            !result.contains('\u{009B}'),
1266            "C1 CSI (U+009B) must be stripped"
1267        );
1268    }
1269
1270    #[test]
1271    fn adversarial_c1_osc_byte() {
1272        // U+009D is the C1 equivalent of ESC ] (OSC)
1273        let input = "text\u{009D}0;Evil Title\x07malicious";
1274        let result = sanitize(input);
1275        assert!(!result.contains('\x1b'));
1276        assert!(
1277            !result.contains('\u{009D}'),
1278            "C1 OSC (U+009D) must be stripped"
1279        );
1280    }
1281
1282    #[test]
1283    fn adversarial_c1_dcs_byte() {
1284        // U+0090 (DCS)
1285        let input = "A\u{0090}device control\x1b\\B";
1286        let result = sanitize(input);
1287        assert!(!result.contains('\u{0090}'));
1288    }
1289
1290    #[test]
1291    fn adversarial_c1_apc_byte() {
1292        // U+009F (APC)
1293        let input = "A\u{009F}app command\x1b\\B";
1294        let result = sanitize(input);
1295        assert!(!result.contains('\u{009F}'));
1296    }
1297
1298    #[test]
1299    fn adversarial_c1_pm_byte() {
1300        // U+009E (PM)
1301        let input = "A\u{009E}private msg\x1b\\B";
1302        let result = sanitize(input);
1303        assert!(!result.contains('\u{009E}'));
1304    }
1305
1306    #[test]
1307    fn adversarial_c1_st_byte() {
1308        // U+009C (ST = String Terminator)
1309        let input = "A\u{009C}B";
1310        let result = sanitize(input);
1311        assert!(!result.contains('\u{009C}'));
1312    }
1313
1314    #[test]
1315    fn adversarial_all_c1_controls_stripped() {
1316        // Every C1 control (U+0080..U+009F) must be stripped
1317        for cp in 0x0080..=0x009F_u32 {
1318            let c = char::from_u32(cp).unwrap();
1319            let input = format!("A{c}B");
1320            let result = sanitize(&input);
1321            assert!(
1322                !result
1323                    .chars()
1324                    .any(|ch| ('\u{0080}'..='\u{009F}').contains(&ch)),
1325                "C1 control U+{cp:04X} passed through sanitizer"
1326            );
1327            // The surrounding text must survive
1328            assert!(result.contains('A'), "Text before C1 U+{cp:04X} lost");
1329            assert!(result.contains('B'), "Text after C1 U+{cp:04X} lost");
1330        }
1331    }
1332
1333    #[test]
1334    fn adversarial_c1_fast_path_triggers_slow_path() {
1335        // C1 controls must trigger the slow path even without ESC/DEL/C0
1336        let input = "clean\u{0085}text"; // U+0085 = NEL (Next Line)
1337        let result = sanitize(input);
1338        assert!(
1339            matches!(result, Cow::Owned(_)),
1340            "C1 should trigger slow path"
1341        );
1342        assert!(!result.contains('\u{0085}'));
1343        assert_eq!(result.as_ref(), "cleantext");
1344    }
1345
1346    // ---- 8. Sequence terminator confusion ----
1347
1348    #[test]
1349    fn adversarial_nested_osc_in_osc() {
1350        // OSC within OSC - inner should not terminate outer
1351        let input = "safe\x1b]8;;\x1b]0;evil\x07https://ok.com\x07text";
1352        let result = sanitize(input);
1353        assert!(!result.contains('\x1b'));
1354        assert!(!result.contains('\x07'));
1355    }
1356
1357    #[test]
1358    fn adversarial_st_inside_dcs() {
1359        // DCS with lone ESC (not followed by \) in body: aborts the DCS handler.
1360        // The lone ESC is re-processed by the main loop as ESC d (single-char escape),
1361        // and the remaining "ata" appears as text before ESC \ (another single-char escape).
1362        let input = "A\x1bPsome\x1bdata\x1b\\B";
1363        let result = sanitize(input);
1364        assert_eq!(result.as_ref(), "AataB");
1365    }
1366
1367    #[test]
1368    fn dcs_with_proper_st_fully_consumed() {
1369        // DCS properly terminated by ST (no lone ESC in body)
1370        let input = "A\x1bPsomedata\x1b\\B";
1371        let result = sanitize(input);
1372        assert_eq!(result.as_ref(), "AB");
1373    }
1374
1375    #[test]
1376    fn adversarial_bel_vs_st_terminator() {
1377        // OSC terminated by BEL, then more text, then ST
1378        let input = "A\x1b]0;title\x07B\x1b\\C";
1379        let result = sanitize(input);
1380        // BEL terminates the OSC; "B" is text; ESC \ is a single-char escape
1381        assert!(!result.contains('\x1b'));
1382        assert!(!result.contains('\x07'));
1383    }
1384
1385    #[test]
1386    fn adversarial_csi_without_final_byte() {
1387        // CSI with only parameter bytes, never reaching a final byte
1388        let input = "A\x1b[0;0;0;0;0;0;0;0;0;0B";
1389        let result = sanitize(input);
1390        // The 'B' (0x42) IS a valid CSI final byte, so entire CSI is consumed
1391        assert_eq!(result.as_ref(), "A");
1392    }
1393
1394    #[test]
1395    fn adversarial_csi_many_params_then_final() {
1396        // CSI with many parameters followed by a valid final byte
1397        let input = "X\x1b[1;2;3;4;5;6;7;8;9;10mY";
1398        let result = sanitize(input);
1399        assert_eq!(result.as_ref(), "XY");
1400    }
1401
1402    // ---- 9. DoS-style payloads ----
1403
1404    #[test]
1405    fn adversarial_very_long_csi_params() {
1406        // Very long CSI parameter string
1407        let params: String = std::iter::repeat_n("0;", 10_000).collect();
1408        let input = format!("start\x1b[{params}mend");
1409        let result = sanitize(&input);
1410        assert_eq!(result.as_ref(), "startend");
1411    }
1412
1413    #[test]
1414    fn adversarial_many_short_sequences() {
1415        // Many small CSI sequences back to back
1416        let input: String = (0..10_000).map(|_| "\x1b[0m").collect();
1417        let input = format!("start{input}end");
1418        let result = sanitize(&input);
1419        assert_eq!(result.as_ref(), "startend");
1420    }
1421
1422    #[test]
1423    fn adversarial_very_long_osc_content() {
1424        // Very long OSC payload (could be used to cause memory issues)
1425        let payload: String = std::iter::repeat_n('A', 100_000).collect();
1426        let input = format!("text\x1b]0;{payload}\x07more");
1427        let result = sanitize(&input);
1428        assert_eq!(result.as_ref(), "textmore");
1429    }
1430
1431    #[test]
1432    fn adversarial_very_long_dcs_content() {
1433        let payload: String = std::iter::repeat_n('X', 100_000).collect();
1434        let input = format!("text\x1bP{payload}\x1b\\more");
1435        let result = sanitize(&input);
1436        assert_eq!(result.as_ref(), "textmore");
1437    }
1438
1439    #[test]
1440    fn adversarial_only_escape_bytes() {
1441        // Input composed entirely of ESC bytes
1442        let input: String = std::iter::repeat_n('\x1b', 1000).collect();
1443        let result = sanitize(&input);
1444        assert_eq!(result.as_ref(), "");
1445    }
1446
1447    #[test]
1448    fn adversarial_alternating_esc_and_text() {
1449        // ESC-char-ESC-char pattern
1450        let input: String = (0..1000)
1451            .map(|i| if i % 2 == 0 { "\x1b[m" } else { "a" })
1452            .collect();
1453        let result = sanitize(&input);
1454        // Only the "a" chars survive
1455        let expected: String = std::iter::repeat_n('a', 500).collect();
1456        assert_eq!(result.as_ref(), expected);
1457    }
1458
1459    #[test]
1460    fn adversarial_all_forbidden_c0_in_sequence() {
1461        // Every forbidden C0 byte
1462        let mut input = String::from("start");
1463        for b in 0x00u8..=0x1F {
1464            if b != 0x09 && b != 0x0A && b != 0x0D && b != 0x1B {
1465                input.push(b as char);
1466            }
1467        }
1468        input.push_str("end");
1469        let result = sanitize(&input);
1470        assert_eq!(result.as_ref(), "startend");
1471    }
1472
1473    // ---- 10. Combined / chained attacks ----
1474
1475    #[test]
1476    fn adversarial_combined_title_clear_clipboard() {
1477        // Chain: set title + clear screen + set clipboard + fake prompt
1478        let input = concat!(
1479            "\x1b]0;Terminal\x07",    // set title
1480            "\x1b[2J",                // clear screen
1481            "\x1b[H",                 // home cursor
1482            "\x1b]52;c;cm0gLXJm\x07", // set clipboard
1483            "Password: ",             // fake prompt
1484        );
1485        let result = sanitize(input);
1486        assert_eq!(result.as_ref(), "Password: ");
1487        assert!(!result.contains('\x1b'));
1488        assert!(!result.contains('\x07'));
1489    }
1490
1491    #[test]
1492    fn adversarial_sgr_color_soup() {
1493        // Many SGR sequences interspersed with text to try to leak colors
1494        let input = "\x1b[31m\x1b[1m\x1b[4m\x1b[7m\x1b[38;2;255;0;0mred\x1b[0m";
1495        let result = sanitize(input);
1496        assert_eq!(result.as_ref(), "red");
1497    }
1498
1499    #[test]
1500    fn adversarial_hyperlink_wrapping_attack() {
1501        // Try to create a clickable region that covers existing content
1502        let input = concat!(
1503            "\x1b]8;;https://evil.com\x07",
1504            "Click here for info",
1505            "\x1b]8;;\x07",
1506        );
1507        let result = sanitize(input);
1508        assert_eq!(result.as_ref(), "Click here for info");
1509    }
1510
1511    #[test]
1512    fn adversarial_kitty_graphics_protocol() {
1513        // Kitty graphics protocol uses APC
1514        let input = "img\x1b_Gf=100,s=1,v=1;AAAA\x1b\\text";
1515        let result = sanitize(input);
1516        assert_eq!(result.as_ref(), "imgtext");
1517    }
1518
1519    #[test]
1520    fn adversarial_sixel_data() {
1521        // Sixel graphics data via DCS
1522        let input = "pre\x1bPq#0;2;0;0;0#1;2;100;100;100~-\x1b\\post";
1523        let result = sanitize(input);
1524        assert_eq!(result.as_ref(), "prepost");
1525    }
1526
1527    #[test]
1528    fn adversarial_mixed_valid_utf8_and_escapes() {
1529        // Unicode text interspersed with escape sequences
1530        let input = "\u{1f512}\x1b[31m\u{26a0}\x1b[0m secure\x1b]0;evil\x07\u{2705}";
1531        let result = sanitize(input);
1532        assert_eq!(result.as_ref(), "\u{1f512}\u{26a0} secure\u{2705}");
1533    }
1534
1535    #[test]
1536    fn adversarial_control_char_near_escape() {
1537        // Control chars adjacent to escape sequences
1538        let input = "\x01\x1b[31m\x02text\x03\x1b[0m\x04";
1539        let result = sanitize(input);
1540        assert!(!result.contains('\x1b'));
1541        assert_eq!(result.as_ref(), "text");
1542    }
1543
1544    #[test]
1545    fn adversarial_save_restore_cursor_attack() {
1546        // Save cursor, write fake content, restore cursor to hide it
1547        let input = "\x1b7fake prompt\x1b8real content";
1548        let result = sanitize(input);
1549        assert_eq!(result.as_ref(), "fake promptreal content");
1550    }
1551
1552    #[test]
1553    fn adversarial_dec_set_reset_barrage() {
1554        // Barrage of DEC private mode set/reset sequences
1555        let input = (1..100)
1556            .map(|i| format!("\x1b[?{i}h\x1b[?{i}l"))
1557            .collect::<String>();
1558        let input = format!("A{input}B");
1559        let result = sanitize(&input);
1560        assert_eq!(result.as_ref(), "AB");
1561    }
1562
1563    // ---- Property-based tests via proptest ----
1564
1565    mod proptest_adversarial {
1566        use super::*;
1567        use proptest::prelude::*;
1568
1569        proptest! {
1570            #[test]
1571            fn sgr_only_lossy_bytes_are_idempotent_and_preserve_plain_projection(
1572                bytes in proptest::collection::vec(any::<u8>(), 0..1024)
1573            ) {
1574                let input = String::from_utf8_lossy(&bytes);
1575                let styled = sanitize_sgr_only(&input);
1576                let second = sanitize_sgr_only(&styled);
1577                let plain_styled = sanitize(&styled);
1578                let plain_input = sanitize(&input);
1579                prop_assert_eq!(second.as_ref(), styled.as_ref());
1580                prop_assert_eq!(plain_styled.as_ref(), plain_input.as_ref());
1581            }
1582
1583            #[test]
1584            fn sgr_only_mixed_escapes_allow_only_bounded_sgr(input in mixed_adversarial_input()) {
1585                let styled = sanitize_sgr_only(&input);
1586                let second = sanitize_sgr_only(&styled);
1587                let plain_styled = sanitize(&styled);
1588                let plain_input = sanitize(&input);
1589                prop_assert_eq!(second.as_ref(), styled.as_ref());
1590                prop_assert_eq!(plain_styled.as_ref(), plain_input.as_ref());
1591                // Independent recognizer: no shared escape parser/allowlist helper.
1592                let mut chars = styled.chars();
1593                while let Some(ch) = chars.next() {
1594                    if ch == '\x1b' {
1595                        prop_assert_eq!(chars.next(), Some('['));
1596                        let mut length = 2;
1597                        loop {
1598                            let parameter = chars.next();
1599                            length += 1;
1600                            prop_assert!(length <= 64);
1601                            if parameter == Some('m') {
1602                                break;
1603                            }
1604                            prop_assert!(matches!(parameter, Some('0'..='9' | ';' | ':')));
1605                        }
1606                    } else {
1607                        prop_assert!(!ch.is_control() || matches!(ch, '\t' | '\n' | '\r'));
1608                    }
1609                }
1610            }
1611
1612            #[test]
1613            fn sanitize_never_panics(input in ".*") {
1614                let _ = sanitize(&input);
1615            }
1616
1617            #[test]
1618            fn sanitize_output_never_contains_esc(input in ".*") {
1619                let result = sanitize(&input);
1620                prop_assert!(
1621                    !result.contains('\x1b'),
1622                    "Output contained ESC for input {:?}", input
1623                );
1624            }
1625
1626            #[test]
1627            fn sanitize_output_never_contains_del(input in ".*") {
1628                let result = sanitize(&input);
1629                prop_assert!(
1630                    !result.contains('\x7f'),
1631                    "Output contained DEL for input {:?}", input
1632                );
1633            }
1634
1635            #[test]
1636            fn sanitize_output_no_forbidden_c0(input in ".*") {
1637                let result = sanitize(&input);
1638                for &b in result.as_bytes() {
1639                    prop_assert!(
1640                        !is_forbidden_c0(b),
1641                        "Output contains forbidden C0 0x{:02X}", b
1642                    );
1643                }
1644            }
1645
1646            #[test]
1647            fn sanitize_preserves_clean_input(input in "[a-zA-Z0-9 .,!?\\n\\t]+") {
1648                let result = sanitize(&input);
1649                prop_assert_eq!(result.as_ref(), input.as_str());
1650            }
1651
1652            #[test]
1653            fn sanitize_idempotent(input in ".*") {
1654                let first = sanitize(&input);
1655                let second = sanitize(first.as_ref());
1656                prop_assert_eq!(
1657                    first.as_ref(),
1658                    second.as_ref(),
1659                    "Sanitize is not idempotent"
1660                );
1661            }
1662
1663            #[test]
1664            fn sanitize_output_len_lte_input(input in ".*") {
1665                let result = sanitize(&input);
1666                prop_assert!(
1667                    result.len() <= input.len(),
1668                    "Output ({}) longer than input ({})", result.len(), input.len()
1669                );
1670            }
1671
1672            #[test]
1673            fn sanitize_output_is_valid_utf8(input in ".*") {
1674                let result = sanitize(&input);
1675                // The return type is Cow<str> so it's guaranteed valid UTF-8,
1676                // but verify the invariant explicitly.
1677                prop_assert!(std::str::from_utf8(result.as_bytes()).is_ok());
1678            }
1679
1680            #[test]
1681            fn sanitize_output_no_c1_controls(input in ".*") {
1682                let result = sanitize(&input);
1683                for c in result.as_ref().chars() {
1684                    prop_assert!(
1685                        !('\u{0080}'..='\u{009F}').contains(&c),
1686                        "Output contains C1 control U+{:04X}", c as u32
1687                    );
1688                }
1689            }
1690        }
1691
1692        // Targeted generators for adversarial byte patterns
1693
1694        fn escape_sequence() -> impl Strategy<Value = String> {
1695            prop_oneof![
1696                // CSI sequences with random params and final bytes
1697                (
1698                    proptest::collection::vec(0x30u8..=0x3F, 0..20),
1699                    0x40u8..=0x7E,
1700                )
1701                    .prop_map(|(params, final_byte)| {
1702                        let mut s = String::from("\x1b[");
1703                        for b in params {
1704                            s.push(b as char);
1705                        }
1706                        s.push(final_byte as char);
1707                        s
1708                    }),
1709                // OSC with BEL terminator
1710                proptest::string::string_regex("[^\x07\x1b]{0,50}")
1711                    .unwrap()
1712                    .prop_map(|content| format!("\x1b]{content}\x07")),
1713                // OSC with ST terminator
1714                proptest::string::string_regex("[^\x1b]{0,50}")
1715                    .unwrap()
1716                    .prop_map(|content| format!("\x1b]{content}\x1b\\")),
1717                // DCS
1718                proptest::string::string_regex("[^\x1b]{0,50}")
1719                    .unwrap()
1720                    .prop_map(|content| format!("\x1bP{content}\x1b\\")),
1721                // APC
1722                proptest::string::string_regex("[^\x1b]{0,50}")
1723                    .unwrap()
1724                    .prop_map(|content| format!("\x1b_{content}\x1b\\")),
1725                // PM
1726                proptest::string::string_regex("[^\x1b]{0,50}")
1727                    .unwrap()
1728                    .prop_map(|content| format!("\x1b^{content}\x1b\\")),
1729                // Single-char escapes
1730                (0x20u8..=0x7E).prop_map(|b| format!("\x1b{}", b as char)),
1731            ]
1732        }
1733
1734        fn mixed_adversarial_input() -> impl Strategy<Value = String> {
1735            proptest::collection::vec(
1736                prop_oneof![
1737                    // Clean text
1738                    proptest::string::string_regex("[a-zA-Z0-9 ]{1,10}").unwrap(),
1739                    // Escape sequences
1740                    escape_sequence(),
1741                    // Forbidden C0 controls
1742                    (0x00u8..=0x1F)
1743                        .prop_filter("not allowed control", |b| {
1744                            *b != 0x09 && *b != 0x0A && *b != 0x0D
1745                        })
1746                        .prop_map(|b| String::from(b as char)),
1747                ],
1748                1..20,
1749            )
1750            .prop_map(|parts| parts.join(""))
1751        }
1752
1753        proptest! {
1754            #[test]
1755            fn adversarial_mixed_input_safe(input in mixed_adversarial_input()) {
1756                let result = sanitize(&input);
1757                prop_assert!(!result.contains('\x1b'));
1758                prop_assert!(!result.contains('\x7f'));
1759                for &b in result.as_bytes() {
1760                    prop_assert!(!is_forbidden_c0(b));
1761                }
1762            }
1763
1764            #[test]
1765            fn escape_sequences_fully_stripped(seq in escape_sequence()) {
1766                let input = format!("before{seq}after");
1767                let result = sanitize(&input);
1768                prop_assert!(
1769                    !result.contains('\x1b'),
1770                    "Output contains ESC for sequence {:?}", seq
1771                );
1772                prop_assert!(
1773                    result.starts_with("before"),
1774                    "Output doesn't start with 'before' for {:?}: got {:?}", seq, result
1775                );
1776                // Note: unterminated DCS/APC/PM/OSC sequences consume to
1777                // end of input, so "after" may be absorbed. This is correct
1778                // security behavior — consuming unterminated sequences is
1779                // safer than letting potential payload through.
1780            }
1781        }
1782    }
1783}