pub const MAX_UNTRUSTED_FIELD_CHARS: usize = 4 * 1024;
pub fn sanitize_untrusted_field(value: &str) -> String {
value
.chars()
.filter_map(|ch| match ch {
'\n' => Some('\n'),
'\t' | '\r' => Some(' '),
_ if ch.is_control() || is_bidi_control(ch) => None,
_ => Some(ch),
})
.take(MAX_UNTRUSTED_FIELD_CHARS)
.collect()
}
fn is_bidi_control(ch: char) -> bool {
matches!(
ch,
'\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_terminal_sequences_but_keeps_text_and_newlines() {
let input = "before\x1b]52;c;Y2xpcGJvYXJk\x07after\nnext\tcolumn\rreturn\u{202e}spoof";
assert_eq!(
sanitize_untrusted_field(input),
"before]52;c;Y2xpcGJvYXJkafter\nnext column returnspoof"
);
}
#[test]
fn caps_untrusted_fields_without_splitting_unicode() {
let input = "é".repeat(MAX_UNTRUSTED_FIELD_CHARS + 10);
let output = sanitize_untrusted_field(&input);
assert_eq!(output.chars().count(), MAX_UNTRUSTED_FIELD_CHARS);
assert!(output.chars().all(|ch| ch == 'é'));
}
}