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() => None,
_ => Some(ch),
})
.take(MAX_UNTRUSTED_FIELD_CHARS)
.collect()
}
#[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";
assert_eq!(
sanitize_untrusted_field(input),
"before]52;c;Y2xpcGJvYXJkafter\nnext column return"
);
}
#[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 == 'é'));
}
}