use serde::Serialize;
use crate::detect::scan_text;
pub const DEFAULT_MAX_CHARS: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Invisible {
ZeroWidth,
Bidi,
Tag,
VariationSelector,
Bom,
Control,
}
pub(crate) fn invisible_kind(c: char) -> Option<Invisible> {
match c as u32 {
0x200B..=0x200D
| 0x2060..=0x2064
| 0x00AD
| 0x180E
| 0x034F
| 0x115F
| 0x1160
| 0x17B4
| 0x17B5
| 0x3164
| 0xFFA0 => Some(Invisible::ZeroWidth),
0x200E | 0x200F | 0x202A..=0x202E | 0x2066..=0x2069 | 0x061C => Some(Invisible::Bidi),
0xE0000..=0xE007F => Some(Invisible::Tag),
0xFE00..=0xFE0F | 0xE0100..=0xE01EF => Some(Invisible::VariationSelector),
0xFEFF => Some(Invisible::Bom),
0x00..=0x08 | 0x0B | 0x0E..=0x1F | 0x7F..=0x9F => Some(Invisible::Control),
_ => None,
}
}
pub(crate) fn needs_escape(c: char) -> bool {
let u = c as u32;
if u & 0xFFFE == 0xFFFE {
return true;
}
matches!(
u,
0x00..=0x1F | 0x7F..=0x9F
| 0x00AD | 0x034F | 0x061C | 0x115F | 0x1160 | 0x17B4 | 0x17B5
| 0x180B..=0x180F | 0x3164 | 0xFFA0
| 0x0600..=0x0605 | 0x06DD | 0x070F | 0x0890 | 0x0891 | 0x08E2
| 0x110BD | 0x110CD | 0x13430..=0x1345F | 0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A
| 0x1680 | 0x2000..=0x200F | 0x2028..=0x202F | 0x205F..=0x206F | 0x3000
| 0xFE00..=0xFE0F | 0xFEFF
| 0xFFF0..=0xFFFB
| 0xFDD0..=0xFDEF
| 0xE000..=0xF8FF
| 0x40000..=0xDFFFF
| 0xE0000..=0xEFFFF
| 0xF0000..=0x10FFFF
)
}
fn is_combining_mark(c: char) -> bool {
matches!(
c as u32,
0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F
)
}
pub const MAX_COMBINING_RUN: usize = 2;
pub fn escape_untrusted(s: &str, max_chars: usize) -> (String, bool) {
let mut out = String::with_capacity(s.len().min(max_chars.saturating_mul(4)));
let mut out_chars = 0usize;
let mut token = String::with_capacity(12);
let mut combining_run = 0usize;
for c in s.chars() {
token.clear();
combining_run = if is_combining_mark(c) {
combining_run + 1
} else {
0
};
match c {
'\\' => token.push_str("\\\\"),
'\n' => token.push_str("\\n"),
'\r' => token.push_str("\\r"),
'\t' => token.push_str("\\t"),
c if needs_escape(c) || combining_run > MAX_COMBINING_RUN => {
use std::fmt::Write;
let _ = write!(token, "\\u{{{:04X}}}", c as u32);
}
c => token.push(c),
}
let token_chars = token.chars().count();
if out_chars + token_chars > max_chars {
return (out, true);
}
out.push_str(&token);
out_chars += token_chars;
}
(out, false)
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct UntrustedText {
pub untrusted: bool,
pub text: String,
pub truncated: bool,
pub original_len: usize,
pub injection_flags: Vec<String>,
}
impl UntrustedText {
pub fn new(raw: &str) -> Self {
Self::with_limit(raw, DEFAULT_MAX_CHARS)
}
pub fn with_limit(raw: &str, max_chars: usize) -> Self {
let (text, truncated) = escape_untrusted(raw, max_chars);
UntrustedText {
untrusted: true,
text,
truncated,
original_len: raw.len(),
injection_flags: scan_text(raw).rules(),
}
}
pub fn is_flagged(&self) -> bool {
!self.injection_flags.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn all_chars() -> impl Iterator<Item = char> {
(0u32..=0xFFFF)
.chain(0xE0000..=0xE01EF)
.chain(0xF0000..=0xF0100)
.filter_map(char::from_u32)
}
#[test]
fn long_combining_runs_are_escaped() {
let (e, _) = escape_untrusted("e\u{301}\u{302}\u{303}\u{304}x\u{301}", 100);
assert_eq!(e, "e\u{301}\u{302}\\u{0303}\\u{0304}x\u{301}");
}
#[test]
fn listed_classes_are_escaped() {
let ranges: &[(u32, u32)] = &[
(0x00, 0x1F),
(0x7F, 0x7F),
(0x80, 0x9F),
(0x200B, 0x200F),
(0x2060, 0x2064),
(0xFEFF, 0xFEFF),
(0x00AD, 0x00AD),
(0x180E, 0x180E),
(0x034F, 0x034F),
(0x202A, 0x202E),
(0x2066, 0x2069),
(0x061C, 0x061C),
(0xE0000, 0xE007F),
(0xFE00, 0xFE0F),
(0xE0100, 0xE01EF),
(0xE000, 0xF8FF),
(0xF0000, 0xFFFFD),
(0x100000, 0x10FFFD),
];
for &(lo, hi) in ranges {
for u in lo..=hi {
let c = char::from_u32(u).unwrap();
assert!(needs_escape(c), "U+{u:04X} must be escaped");
let (e, t) = escape_untrusted(&c.to_string(), 64);
assert!(!t);
assert!(!e.contains(c), "U+{u:04X} leaked raw");
assert!(e.starts_with('\\'));
}
}
}
#[test]
fn invisible_kinds_are_escaped() {
for c in all_chars() {
if invisible_kind(c).is_some() {
assert!(needs_escape(c), "U+{:04X}", c as u32);
}
}
}
#[test]
fn exact_escape_forms() {
assert_eq!(escape_untrusted("a\\b", 99).0, "a\\\\b");
assert_eq!(escape_untrusted("\n\r\t", 99).0, "\\n\\r\\t");
assert_eq!(escape_untrusted("\u{200B}", 99).0, "\\u{200B}");
assert_eq!(escape_untrusted("\u{E0041}", 99).0, "\\u{E0041}");
assert_eq!(escape_untrusted("\0", 99).0, "\\u{0000}");
assert_eq!(escape_untrusted("héllo 日本", 99).0, "héllo 日本");
}
#[test]
fn property_no_raw_escaped_char_survives() {
let all: Vec<char> = all_chars().collect();
for chunk in all.chunks(512) {
let s: String = chunk.iter().collect();
let (e, t) = escape_untrusted(&s, usize::MAX);
assert!(!t);
for c in e.chars() {
assert!(!needs_escape(c), "raw U+{:04X} in output", c as u32);
}
}
}
#[test]
fn truncation_never_splits_escape() {
let s = "ab\u{200B}cd\u{E0041}\\x\n";
let mut boundaries = vec![0usize];
let mut acc = 0usize;
for c in s.chars() {
acc += escape_untrusted(&c.to_string(), usize::MAX).0.len();
boundaries.push(acc);
}
let (full, _) = escape_untrusted(s, usize::MAX);
assert_eq!(acc, full.len());
for max in 0..=full.chars().count() + 2 {
let (e, t) = escape_untrusted(s, max);
assert!(e.chars().count() <= max, "cap {max} exceeded: {e}");
assert!(full.starts_with(&e));
assert_eq!(t, e != full);
assert!(
boundaries.contains(&e.len()),
"split escape at cap {max}: {e}"
);
}
}
#[test]
fn cap_counts_multibyte_as_one() {
let (e, t) = escape_untrusted("日本語テキスト", 3);
assert_eq!(e, "日本語");
assert!(t);
}
}