1#![forbid(unsafe_code)]
2
3use std::borrow::Cow;
45
46use memchr::memchr;
47
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50pub enum SanitizeMode {
51 #[default]
53 Strip,
54 SgrOnly,
56 Raw,
58}
59
60pub 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
69pub 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#[inline]
105pub fn sanitize(input: &str) -> Cow<'_, str> {
106 if is_plain_text(input.as_bytes()) {
107 return Cow::Borrowed(input);
108 }
109
110 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#[inline]
127fn has_forbidden_c0(bytes: &[u8]) -> bool {
128 bytes.iter().any(|&b| is_forbidden_c0(b))
129}
130
131#[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#[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
152fn sanitize_slow(input: &str, mode: SanitizeMode) -> Cow<'_, str> {
154 let bytes = input.as_bytes();
155 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 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 0x09 | 0x0A | 0x0D => (i + 1, true),
178 0x00..=0x08 | 0x0B..=0x0C | 0x0E..=0x1A | 0x1C..=0x1F | 0x7F => (i + 1, false),
180 0x20..=0x7E => (i + 1, true),
182 0x80..=0xFF => {
184 if let Some((c, len)) = decode_utf8_char(&bytes[i..]) {
185 (i + len, !('\u{0080}'..='\u{009F}').contains(&c))
188 } else {
189 (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
212fn skip_escape_sequence(bytes: &[u8], start: usize) -> usize {
223 let mut i = start + 1; if i >= bytes.len() {
225 return i;
226 }
227
228 match bytes[i] {
229 b'[' => {
231 i += 1;
232 while i < bytes.len() {
235 let b = bytes[i];
236 if (0x40..=0x7E).contains(&b) {
237 return i + 1;
238 }
239 if !(0x20..=0x3F).contains(&b) {
241 return i;
244 }
245 i += 1;
246 }
247 }
248 b']' => {
250 i += 1;
251 while i < bytes.len() {
252 let b = bytes[i];
253 if b == 0x07 {
255 return i + 1;
256 }
257 if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
259 return i + 2;
260 }
261 if b == 0xC2 && i + 1 < bytes.len() && bytes[i + 1] == 0x9C {
266 return i + 2;
267 }
268 if b == 0x1B {
271 return i;
272 }
273 if b < 0x20 {
275 return i;
276 }
277 i += 1;
278 }
279 }
280 b'P' | b'^' | b'_' | b'X' => {
282 i += 1;
283 while i < bytes.len() {
284 let b = bytes[i];
285 if b == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\' {
287 return i + 2;
288 }
289 if b == 0xC2 && i + 1 < bytes.len() && bytes[i + 1] == 0x9C {
291 return i + 2;
292 }
293 if b == 0x1B {
296 return i;
297 }
298 if b < 0x20 {
300 return i;
301 }
302 i += 1;
303 }
304 }
305 0x20..=0x7E => {
307 return i + 1;
308 }
309 _ => {}
311 }
312
313 i
314}
315
316fn 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, };
332
333 if bytes.len() < expected_len {
334 return None;
335 }
336
337 for &b in bytes.iter().take(expected_len).skip(1) {
339 if (b & 0xC0) != 0x80 {
340 return None; }
342 codepoint = (codepoint << 6) | (b & 0x3F) as u32;
343 }
344
345 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 char::from_u32(codepoint).map(|c| (c, expected_len))
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
365pub enum Text<'a> {
366 Sanitized(Cow<'a, str>),
368
369 SgrOnly(Cow<'a, str>),
371
372 Trusted(Cow<'a, str>),
375}
376
377impl<'a> Text<'a> {
378 #[inline]
380 pub fn sanitized(s: &'a str) -> Self {
381 Text::Sanitized(sanitize(s))
382 }
383
384 pub fn sgr_only(s: &'a str) -> Self {
386 Text::SgrOnly(sanitize_sgr_only(s))
387 }
388
389 #[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 #[inline]
405 pub fn trusted(s: &'a str) -> Self {
406 Text::Trusted(Cow::Borrowed(s))
407 }
408
409 #[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 #[inline]
420 pub fn trusted_owned(s: String) -> Self {
421 Text::Trusted(Cow::Owned(s))
422 }
423
424 #[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 #[inline]
435 #[must_use]
436 pub fn is_sanitized(&self) -> bool {
437 matches!(self, Text::Sanitized(_))
438 }
439
440 #[inline]
442 #[must_use]
443 pub fn is_trusted(&self) -> bool {
444 matches!(self, Text::Trusted(_))
445 }
446
447 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 #[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 #[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 #[test]
627 fn slow_path_strips_osc_title_bel() {
628 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 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 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 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 #[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 #[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 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 let result = sanitize(input);
769 assert_eq!(result.as_ref(), "Line1\nLine2\tTabbed\rReturn");
770 }
771
772 #[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 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 let input = "Before\x1b!After";
841 let result = sanitize(input);
842 assert_eq!(result.as_ref(), "BeforeAfter");
844 }
845
846 #[test]
849 fn preserves_unicode_characters() {
850 let input = "\u{4e16}\u{754c}"; 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}"; 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 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 #[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 #[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 #[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(); 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(); 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(); 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]; 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]; let result = decode_utf8_char(bytes);
1012 assert_eq!(result, None);
1013 }
1014
1015 #[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 #[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 #[test]
1110 fn adversarial_osc52_clipboard_set_bel() {
1111 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 let input = "\x1b]52;c;?\x07";
1128 let result = sanitize(input);
1129 assert_eq!(result.as_ref(), "");
1130 }
1131
1132 #[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 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 #[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 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 #[test]
1225 fn adversarial_fake_shell_prompt() {
1226 let input = "\x1b[999;1H\x1b[2K$ sudo rm -rf /\x1b[A";
1228 let result = sanitize(input);
1229 assert!(!result.contains('\x1b'));
1230 assert_eq!(result.as_ref(), "$ sudo rm -rf /");
1232 }
1233
1234 #[test]
1235 fn adversarial_fake_password_prompt() {
1236 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 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 #[test]
1258 fn adversarial_c1_single_byte_csi() {
1259 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 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 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 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 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 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 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 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 let input = "clean\u{0085}text"; 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 #[test]
1349 fn adversarial_nested_osc_in_osc() {
1350 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 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 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 let input = "A\x1b]0;title\x07B\x1b\\C";
1379 let result = sanitize(input);
1380 assert!(!result.contains('\x1b'));
1382 assert!(!result.contains('\x07'));
1383 }
1384
1385 #[test]
1386 fn adversarial_csi_without_final_byte() {
1387 let input = "A\x1b[0;0;0;0;0;0;0;0;0;0B";
1389 let result = sanitize(input);
1390 assert_eq!(result.as_ref(), "A");
1392 }
1393
1394 #[test]
1395 fn adversarial_csi_many_params_then_final() {
1396 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 #[test]
1405 fn adversarial_very_long_csi_params() {
1406 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 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 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 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 let input: String = (0..1000)
1451 .map(|i| if i % 2 == 0 { "\x1b[m" } else { "a" })
1452 .collect();
1453 let result = sanitize(&input);
1454 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 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 #[test]
1476 fn adversarial_combined_title_clear_clipboard() {
1477 let input = concat!(
1479 "\x1b]0;Terminal\x07", "\x1b[2J", "\x1b[H", "\x1b]52;c;cm0gLXJm\x07", "Password: ", );
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 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 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 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 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 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 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 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 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 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 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 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 fn escape_sequence() -> impl Strategy<Value = String> {
1695 prop_oneof![
1696 (
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 proptest::string::string_regex("[^\x07\x1b]{0,50}")
1711 .unwrap()
1712 .prop_map(|content| format!("\x1b]{content}\x07")),
1713 proptest::string::string_regex("[^\x1b]{0,50}")
1715 .unwrap()
1716 .prop_map(|content| format!("\x1b]{content}\x1b\\")),
1717 proptest::string::string_regex("[^\x1b]{0,50}")
1719 .unwrap()
1720 .prop_map(|content| format!("\x1bP{content}\x1b\\")),
1721 proptest::string::string_regex("[^\x1b]{0,50}")
1723 .unwrap()
1724 .prop_map(|content| format!("\x1b_{content}\x1b\\")),
1725 proptest::string::string_regex("[^\x1b]{0,50}")
1727 .unwrap()
1728 .prop_map(|content| format!("\x1b^{content}\x1b\\")),
1729 (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 proptest::string::string_regex("[a-zA-Z0-9 ]{1,10}").unwrap(),
1739 escape_sequence(),
1741 (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 }
1781 }
1782 }
1783}