use safehtml::{
INNOCUOUS_PROPERTY_VALUE, INNOCUOUS_URL, SafeHtml, SafeHtmlProto, SafeScript, SafeScriptProto,
SafeStyle, SafeStyleProto, SafeStyleSheet, SafeStyleSheetProto, SafeUrl, SafeUrlProto,
TrustedResourceUrl, TrustedResourceUrlProto, coerce_bytes_to_interchange_valid,
coerce_bytes_to_interchange_valid_to, coerce_to_interchange_valid_to,
escape_allow_character_references_to, escape_html_and_coerce_to, escape_html_bytes,
escape_html_bytes_and_coerce_to, escape_json_for_script, escape_json_for_script_to,
html_escaped, is_interchange_invalid, is_safe_css_selector, is_safe_style_property_name,
is_safe_style_property_value, is_safe_url_block_javascript, is_safe_url_restrictive,
is_safe_url_restrictive_with_schemes, percent_escape_css_url, percent_escape_css_url_to,
safe_html_cat, url_encode_component, url_encode_component_to,
};
#[test]
fn test_is_interchange_invalid() {
assert!(!is_interchange_invalid('a'));
assert!(!is_interchange_invalid(' '));
assert!(!is_interchange_invalid('\n'));
assert!(!is_interchange_invalid('\r'));
assert!(!is_interchange_invalid('\t'));
assert!(!is_interchange_invalid('\x0C'));
assert!(is_interchange_invalid('\0'));
assert!(is_interchange_invalid('\x01'));
assert!(is_interchange_invalid('\x08'));
assert!(is_interchange_invalid('\x0B')); assert!(is_interchange_invalid('\x1F'));
assert!(is_interchange_invalid('\x7F'));
assert!(is_interchange_invalid('\u{9F}'));
assert!(is_interchange_invalid('\u{FDD0}'));
assert!(is_interchange_invalid('\u{FDEF}'));
assert!(is_interchange_invalid('\u{FFFE}'));
assert!(is_interchange_invalid('\u{FFFF}'));
assert!(is_interchange_invalid('\u{1FFFE}'));
assert!(is_interchange_invalid('\u{10FFFF}'));
}
#[test]
fn test_coerce_to_interchange_valid_basic() {
let mut s = String::new();
coerce_to_interchange_valid_to("hello\x00world\u{FFFE}", &mut s).unwrap();
assert_eq!(s, "hello\u{FFFD}world\u{FFFD}");
}
#[test]
fn test_escape_html() {
let mut s = String::new();
escape_html_and_coerce_to("a < b & c > d \" e ' f\x00", &mut s).unwrap();
assert_eq!(s, "a < b & c > d " e ' f\u{FFFD}");
let safe = SafeHtml::escape("a < b");
assert_eq!(safe.as_str(), "a < b");
}
#[test]
fn test_escape_allow_character_references() {
let mut s = String::new();
escape_allow_character_references_to("foo & ' ' &invalid; &; bar", &mut s)
.unwrap();
assert_eq!(s, "foo & ' ' &invalid; &; bar");
let safe = SafeHtml::escape_allow_character_references("foo ");
assert_eq!(safe.as_str(), "foo ");
}
#[test]
fn test_html_comment() {
let safe = SafeHtml::comment("foo --> bar <script>");
assert_eq!(safe.as_str(), "<!--foo --> bar <script>-->");
}
#[test]
fn test_percent_escape_css_url() {
let mut s = String::new();
percent_escape_css_url_to("http://foo.com/bar?a=1&b=2#frag(3)", &mut s).unwrap();
assert_eq!(s, "http://foo.com/bar?a=1&b=2#frag%283%29");
let css_safe = SafeUrl::sanitize_for_css("http://foo.com/bar?a=1&b=2#frag(3)");
assert_eq!(css_safe.as_str(), "http://foo.com/bar?a=1&b=2#frag%283%29");
}
#[test]
fn test_is_safe_url_block_javascript() {
assert!(is_safe_url_block_javascript("/foo/bar"));
assert!(is_safe_url_block_javascript("foo/bar"));
assert!(is_safe_url_block_javascript("foo/bar?a=1&b=2"));
assert!(is_safe_url_block_javascript("path/to:file"));
assert!(is_safe_url_block_javascript(""));
assert!(is_safe_url_block_javascript("http://test.com"));
assert!(is_safe_url_block_javascript("https://test.com"));
assert!(is_safe_url_block_javascript("mailto:foo@bar.com"));
assert!(is_safe_url_block_javascript("ftp://foo.bar"));
assert!(is_safe_url_block_javascript("foo://bar"));
assert!(!is_safe_url_block_javascript("javascript:alert(1)"));
assert!(!is_safe_url_block_javascript("JAVASCRIPT:alert(1)"));
assert!(!is_safe_url_block_javascript(" javascript:alert(1)")); assert!(!is_safe_url_block_javascript("java\nscript:alert(1)"));
assert!(!is_safe_url_block_javascript("javascript:alert(1)")); }
#[test]
fn test_is_safe_url_restrictive() {
assert!(is_safe_url_restrictive("/foo/bar"));
assert!(is_safe_url_restrictive("foo/bar"));
assert!(is_safe_url_restrictive("foo/bar?a=1&b=2"));
assert!(is_safe_url_restrictive(""));
assert!(is_safe_url_restrictive("http://test.com"));
assert!(is_safe_url_restrictive("https://test.com"));
assert!(is_safe_url_restrictive("mailto:foo@bar.com"));
assert!(is_safe_url_restrictive("ftp://foo.bar"));
assert!(!is_safe_url_restrictive("foo://bar"));
assert!(!is_safe_url_restrictive("javascript:alert(1)"));
assert!(is_safe_url_restrictive_with_schemes("foo://bar", &["foo"]));
assert!(is_safe_url_restrictive_with_schemes(
"foo-bar://baz",
&["foo_bar"]
));
assert!(is_safe_url_restrictive(
"data:image/png;base64,iVBORw0KGgoAAAANS="
));
assert!(is_safe_url_restrictive("data:text/plain;base64,SGVsbG8="));
assert!(is_safe_url_restrictive("DATA:IMAGE/JPEG;BASE64,aBc123+/"));
assert!(!is_safe_url_restrictive("data:text/html;base64,SGVsbG8=")); assert!(!is_safe_url_restrictive(
"data:image/png;base64,invalid characters!"
));
assert!(!is_safe_url_restrictive("data:image/png;base64,")); }
#[test]
fn test_safe_html_concat_and_join() {
let h1 = SafeHtml::escape("hello");
let h2 = SafeHtml::escape("world");
let joined = SafeHtml::join(vec![h1, h2], &SafeHtml::escape(" - "));
assert_eq!(joined.as_str(), "hello - world");
let h1 = SafeHtml::escape("hello");
let h2 = SafeHtml::escape("world");
let concatenated = SafeHtml::concat(vec![h1, h2]);
assert_eq!(concatenated.as_str(), "helloworld");
}
#[test]
fn test_safe_html_cat_macro() {
let h1 = SafeHtml::escape("<b>hello</b>");
let raw_text = "<script>alert(1)</script>";
let result = safe_html_cat!(h1, " - ", raw_text, " count: ", 42);
assert_eq!(
result.as_str(),
"<b>hello</b> - <script>alert(1)</script> count: 42"
);
}
#[test]
fn test_safe_url_sanitize() {
let u1 = SafeUrl::sanitize("https://test.com");
assert_eq!(u1.as_str(), "https://test.com");
let u2 = SafeUrl::sanitize("javascript:alert(1)");
assert_eq!(u2.as_str(), INNOCUOUS_URL);
let u3 = SafeUrl::sanitize_block_only_javascript("foo://bar");
assert_eq!(u3.as_str(), "foo://bar");
let u4 = SafeUrl::sanitize_block_only_javascript("javascript:alert(1)");
assert_eq!(u4.as_str(), INNOCUOUS_URL);
}
#[cfg(feature = "serde")]
#[test]
fn test_serde() {
let h = SafeHtml::escape("hello <world>");
let serialized_html = serde_json::to_string(&h).unwrap();
assert_eq!(serialized_html, "\"hello <world>\"");
let deserialized_html: SafeHtml = serde_json::from_str(&serialized_html).unwrap();
assert_eq!(deserialized_html.as_str(), "hello <world>");
let u = SafeUrl::sanitize("https://test.com");
let serialized_url = serde_json::to_string(&u).unwrap();
assert_eq!(serialized_url, "\"https://test.com\"");
let deserialized_url: SafeUrl = serde_json::from_str(&serialized_url).unwrap();
assert_eq!(deserialized_url.as_str(), "https://test.com");
let unsafe_serialized_url = "\"javascript:alert(1)\"";
let deserialized_unsafe_url: Result<SafeUrl, _> = serde_json::from_str(unsafe_serialized_url);
assert!(deserialized_unsafe_url.is_err());
}
#[test]
fn test_html_escaped() {
let raw_html = "<>'\"&";
let escaped_html = "<>'"&";
let got = SafeHtml::escape(raw_html);
assert_eq!(got.as_str(), escaped_html);
}
#[test]
fn test_html_concat() {
struct TestCase {
in_vec: Vec<&'static str>,
want: &'static str,
}
let tests = [
TestCase {
in_vec: vec![],
want: "",
},
TestCase {
in_vec: vec![""],
want: "",
},
TestCase {
in_vec: vec!["Hello world!"],
want: "Hello world!",
},
TestCase {
in_vec: vec!["Hello", " ", "world!"],
want: "Hello world!",
},
];
for t in &tests {
let mut htmls = Vec::new();
for &s in &t.in_vec {
unsafe {
htmls.push(SafeHtml::from_string_unchecked(s.to_string()));
}
}
let got = SafeHtml::concat(htmls);
assert_eq!(got.as_str(), t.want);
}
}
#[test]
fn test_html_from_proto() {
let raw_html = "<>'\"&";
let escaped_html = "<>'"&";
let html = SafeHtml::escape(raw_html);
let proto = html.to_proto();
assert!(
proto
.private_do_not_access_or_else_safe_html_wrapped_value
.contains(escaped_html)
);
let html2 = SafeHtml::from_proto(Some(&proto));
assert_eq!(html, html2);
let html3 = SafeHtml::from_proto(None);
assert_eq!(html3.as_str(), "");
let html4 = SafeHtml::from_proto(Some(&SafeHtmlProto::default()));
assert_eq!(html4.as_str(), "");
}
#[test]
fn test_coerce_to_interchange_valid() {
struct CharTest {
in_bytes: &'static [u8],
replaced: bool,
}
let char_tests = [
CharTest {
in_bytes: b"\x00",
replaced: true,
},
CharTest {
in_bytes: b"\x04",
replaced: true,
},
CharTest {
in_bytes: b"\x08",
replaced: true,
},
CharTest {
in_bytes: b"\t",
replaced: false,
}, CharTest {
in_bytes: b"\n",
replaced: false,
}, CharTest {
in_bytes: b"\x0B",
replaced: true,
}, CharTest {
in_bytes: b"\x0C",
replaced: false,
}, CharTest {
in_bytes: b"\r",
replaced: false,
}, CharTest {
in_bytes: b"\x0E",
replaced: true,
},
CharTest {
in_bytes: b"\x0F",
replaced: true,
},
CharTest {
in_bytes: "\u{FDCF}".as_bytes(),
replaced: false,
}, CharTest {
in_bytes: "\u{FDD0}".as_bytes(),
replaced: true,
}, CharTest {
in_bytes: "\u{FDD5}".as_bytes(),
replaced: true,
}, CharTest {
in_bytes: "\u{FDEF}".as_bytes(),
replaced: true,
}, CharTest {
in_bytes: "\u{FDF0}".as_bytes(),
replaced: false,
}, CharTest {
in_bytes: "\u{FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{1FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{1FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{2FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{2FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{3FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{3FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{4FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{4FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{5FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{5FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{6FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{6FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{7FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{7FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{8FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{8FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{9FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{9FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{AFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{AFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{BFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{BFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{CFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{CFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{DFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{DFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{EFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{EFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{FFFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{FFFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{10FFFE}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: "\u{10FFFF}".as_bytes(),
replaced: true,
},
CharTest {
in_bytes: b"\xed",
replaced: true,
},
CharTest {
in_bytes: b" ",
replaced: false,
},
CharTest {
in_bytes: "\u{FFFD}".as_bytes(),
replaced: false,
},
];
for tt in &char_tests {
let coerced = coerce_bytes_to_interchange_valid(tt.in_bytes);
if tt.replaced {
assert_eq!(
coerced, "\u{FFFD}",
"coerce_bytes_to_interchange_valid({:?}) should be replaced with FFFD",
tt.in_bytes
);
} else {
let expected_str = core::str::from_utf8(tt.in_bytes).unwrap();
assert_eq!(coerced, expected_str);
}
}
struct StrTest {
in_bytes: &'static [u8],
expected: &'static str,
}
let string_tests = [
StrTest {
in_bytes: b"abcd",
expected: "abcd",
},
StrTest {
in_bytes: "丄ê𐒖t".as_bytes(),
expected: "丄ê𐒖t",
},
StrTest {
in_bytes: b"\n\xe4\xb8\x84\xed \x00\xf0\x9f\xbf\xbea\xef\xbf\xbd",
expected: "\n丄\u{FFFD} \u{FFFD}\u{FFFD}a\u{FFFD}",
},
StrTest {
in_bytes: b"\xff\x7e",
expected: "\u{FFFD}\x7e",
},
StrTest {
in_bytes: b"\xED\xA0\x80",
expected: "\u{FFFD}\u{FFFD}\u{FFFD}",
},
StrTest {
in_bytes: b"\xED\xA1\x8C\xED\xBE\xB4",
expected: "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}",
},
StrTest {
in_bytes: b"\xC0\x80",
expected: "\u{FFFD}\u{FFFD}",
},
];
for tt in &string_tests {
let coerced = coerce_bytes_to_interchange_valid(tt.in_bytes);
assert_eq!(
coerced, tt.expected,
"coerce_bytes_to_interchange_valid({:?})",
tt.in_bytes
);
}
}
const TEST_HTML: &str = "a<b & c>d \" e' f";
const ESCAPED_HTML: &str = "a<b & c>d " e' f";
const INTERCHANGE_INVALID_HTML: &str = "hello\x00world\u{FDD0}";
const INTERCHANGE_ESCAPED_HTML: &str = "hello\u{FFFD}world\u{FFFD}";
const NON_ASCII_CHARS: &str = "hello 丄ê𐒖t";
const NUL_HTML: &str = "hello \x00 world";
const NUL_ESCAPED_HTML: &str = "hello \u{FFFD} world";
#[test]
fn test_safe_html_unchecked_and_empty_constructors() {
let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
assert_eq!(html.as_str(), TEST_HTML);
let empty = SafeHtml::empty();
assert!(empty.as_str().is_empty());
}
#[test]
fn test_safe_html_escape_all_specials() {
assert_eq!(SafeHtml::escape(TEST_HTML).as_str(), ESCAPED_HTML);
}
#[test]
fn test_safe_html_comment_wraps_and_escapes() {
assert_eq!(
SafeHtml::comment("<script>").as_str(),
"<!--<script>-->"
);
}
#[test]
fn test_safe_html_nbsp_constant() {
assert_eq!(SafeHtml::nbsp().as_str(), " ");
}
#[test]
fn test_safe_html_doctype_constant() {
assert_eq!(
SafeHtml::html5_doctype_declaration().as_str(),
"<!DOCTYPE html>"
);
}
#[test]
fn test_safe_html_escape_empty_string() {
assert_eq!(SafeHtml::escape("").as_str(), "");
}
#[test]
fn test_safe_html_escape_coerces_interchange_invalid() {
assert_eq!(
SafeHtml::escape(INTERCHANGE_INVALID_HTML).as_str(),
INTERCHANGE_ESCAPED_HTML
);
}
#[test]
fn test_safe_html_escape_preserves_non_ascii() {
assert_eq!(SafeHtml::escape(NON_ASCII_CHARS).as_str(), NON_ASCII_CHARS);
}
#[test]
fn test_safe_html_escape_replaces_nul() {
assert_eq!(SafeHtml::escape(NUL_HTML).as_str(), NUL_ESCAPED_HTML);
}
#[test]
fn test_safe_html_append_safe_value() {
let mut html = SafeHtml::escape("Hi!");
let other = SafeHtml::escape(TEST_HTML);
html.append(&other);
let expected = String::from("Hi!") + ESCAPED_HTML;
assert_eq!(html.as_str(), expected);
}
#[test]
fn test_escape_and_append_appends_escaped() {
let mut html = SafeHtml::escape("Hi!");
html.escape_and_append(TEST_HTML);
let expected = String::from("Hi!") + ESCAPED_HTML;
assert_eq!(html.as_str(), expected);
}
#[test]
fn test_escape_and_append_empty_input_is_noop() {
let mut html = SafeHtml::escape(TEST_HTML);
html.escape_and_append("");
assert_eq!(html.as_str(), ESCAPED_HTML);
}
#[test]
fn test_escape_and_append_onto_empty() {
let mut html = SafeHtml::empty();
html.escape_and_append(TEST_HTML);
assert_eq!(html.as_str(), ESCAPED_HTML);
}
#[test]
fn test_escape_and_append_coerces_interchange_invalid() {
let mut html = SafeHtml::escape("Hi!");
html.escape_and_append(INTERCHANGE_INVALID_HTML);
let expected = String::from("Hi!") + INTERCHANGE_ESCAPED_HTML;
assert_eq!(html.as_str(), expected);
}
#[test]
fn test_escape_and_append_preserves_non_ascii() {
let mut html = SafeHtml::escape("Hi!");
html.escape_and_append(NON_ASCII_CHARS);
let expected = String::from("Hi!") + NON_ASCII_CHARS;
assert_eq!(html.as_str(), expected);
}
#[test]
fn test_escape_and_append_replaces_nul() {
let mut html = SafeHtml::escape("Hi!");
html.escape_and_append(NUL_HTML);
let expected = String::from("Hi!") + NUL_ESCAPED_HTML;
assert_eq!(html.as_str(), expected);
}
#[test]
fn test_character_reference_preservation_vectors() {
assert_eq!(
SafeHtml::escape_allow_character_references(" ").as_str(),
" "
);
assert_eq!(
SafeHtml::escape_allow_character_references("<").as_str(),
"<"
);
assert_eq!(
SafeHtml::escape_allow_character_references("o").as_str(),
"o"
);
assert_eq!(
SafeHtml::escape_allow_character_references("&n<bsp>!0 ").as_str(),
"&n<bsp>!0 "
);
assert_eq!(
SafeHtml::escape_allow_character_references(" ").as_str(),
"&nbsp"
);
assert_eq!(
SafeHtml::escape_allow_character_references("<script> </script>").as_str(),
"<script> </script>"
);
assert_eq!(
SafeHtml::escape_allow_character_references(" <script>;").as_str(),
"&nbsp<script>;"
);
assert_eq!(
SafeHtml::escape_allow_character_references("&foo;&").as_str(),
"&foo;&"
);
assert_eq!(
SafeHtml::escape_allow_character_references(" ").as_str(),
" "
);
assert_eq!(
SafeHtml::escape_allow_character_references("&foo;&;").as_str(),
"&foo;&;"
);
assert_eq!(
SafeHtml::escape_allow_character_references("foo&&&").as_str(),
"foo&&&"
);
assert_eq!(
SafeHtml::escape_allow_character_references("foo<&>").as_str(),
"foo<&>"
);
assert_eq!(
SafeHtml::escape_allow_character_references("foo<\n;").as_str(),
"foo&lt\n;"
);
assert_eq!(
SafeHtml::escape_allow_character_references("foo<\x07;").as_str(),
"foo&lt\u{FFFD};"
);
}
#[test]
fn test_safe_html_from_proto_variants() {
let empty_proto = SafeHtmlProto::default();
let html = SafeHtml::from_proto(Some(&empty_proto));
assert!(html.as_str().is_empty());
let test_proto = SafeHtmlProto {
private_do_not_access_or_else_safe_html_wrapped_value: TEST_HTML.to_string(),
};
let html2 = SafeHtml::from_proto(Some(&test_proto));
assert_eq!(html2.as_str(), TEST_HTML);
}
#[test]
fn test_safe_html_to_proto_wraps_value() {
let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
let proto = html.to_proto();
assert_eq!(
proto.private_do_not_access_or_else_safe_html_wrapped_value,
TEST_HTML
);
}
#[test]
fn test_safe_html_display_formats_value() {
let html = unsafe { SafeHtml::from_string_unchecked(TEST_HTML.to_string()) };
let s = format!("{}", html);
assert_eq!(s, TEST_HTML);
}
#[test]
fn test_html_operators() {
let mut h1 = SafeHtml::escape("hello");
let h2 = SafeHtml::escape(" world");
h1 += &h2;
assert_eq!(h1.as_str(), "hello world");
let h3 = h1 + h2;
assert_eq!(h3.as_str(), "hello world world");
}
#[test]
fn test_url_encode_component() {
assert_eq!(url_encode_component("hello world"), "hello%20world");
assert_eq!(url_encode_component("a-b.c_d~e"), "a-b.c_d~e");
assert_eq!(url_encode_component("?&=#%+"), "%3F%26%3D%23%25%2B");
assert_eq!(url_encode_component("1/2"), "1%2F2");
}
#[test]
fn test_safe_script_json() {
let raw_json = r#"{"name": "<script>alert(1)</script>", "age": 20, "query": "a&b"}"#;
let expected = r#"{"name": "\u003cscript\u003ealert(1)\u003c/script\u003e", "age": 20, "query": "a\u0026b"}"#;
assert_eq!(escape_json_for_script(raw_json), expected);
let script = SafeScript::from_escaped_json(raw_json);
assert_eq!(script.as_str(), expected);
}
#[test]
fn test_escape_coerce_parity_low_codepoints() {
for u in 0u32..=0xA0 {
let c = char::from_u32(u).unwrap();
if matches!(c, '&' | '<' | '>' | '"' | '\'') {
continue;
}
let s = format!("a{}b", c);
let mut coerced = String::new();
coerce_to_interchange_valid_to(&s, &mut coerced).unwrap();
let mut escaped = String::new();
escape_html_and_coerce_to(&s, &mut escaped).unwrap();
assert_eq!(coerced, escaped, "divergence at U+{:04X}", u);
}
for c in [
'\u{FDD0}',
'\u{FDEF}',
'\u{FFFE}',
'\u{10FFFF}',
'\u{FDCF}',
'\u{FDF0}',
] {
let s = format!("a{}b", c);
let mut coerced = String::new();
coerce_to_interchange_valid_to(&s, &mut coerced).unwrap();
let mut escaped = String::new();
escape_html_and_coerce_to(&s, &mut escaped).unwrap();
assert_eq!(coerced, escaped, "divergence at U+{:04X}", c as u32);
}
}
#[test]
fn test_escape_matches_reference() {
fn reference_escape(s: &str) -> String {
let mut out = String::new();
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
c if is_interchange_invalid(c) => out.push('\u{FFFD}'),
c => out.push(c),
}
}
out
}
let samples = [
"",
"plain ascii with no specials at all",
"<>&\"'",
"a\x7Fb\u{85}c\u{9F}d",
"mixed 丄ê𐒖t <b>bold</b> & 'quoted' \"text\" \u{FDD0}",
"\t\n\r\x0C allowed whitespace survives",
"🎉<🎉>🎉&🎉",
"trailing special <",
"< leading special",
];
for s in samples {
assert_eq!(
SafeHtml::escape(s).as_str(),
reference_escape(s),
"input: {:?}",
s
);
}
}
#[test]
fn test_scanner_positional_sweep() {
for len in [1usize, 2, 15, 16, 17, 31, 32, 33] {
for pos in 0..len {
let mut bytes = vec![b'a'; len];
bytes[pos] = b'<';
let s = String::from_utf8(bytes).unwrap();
let mut got = String::new();
escape_html_and_coerce_to(&s, &mut got).unwrap();
assert_eq!(got, s.replace('<', "<"), "len={} pos={}", len, pos);
}
}
}
#[test]
fn test_escape_html_del_and_controls() {
assert_eq!(SafeHtml::escape("a\x7Fb").as_str(), "a\u{FFFD}b");
assert_eq!(SafeHtml::escape("a\u{85}b").as_str(), "a\u{FFFD}b");
assert_eq!(SafeHtml::escape("\t\n\r\x0C").as_str(), "\t\n\r\x0C");
}
#[test]
fn test_escape_html_multibyte_adjacency() {
assert_eq!(SafeHtml::escape("🎉<🎉").as_str(), "🎉<🎉");
assert_eq!(SafeHtml::escape("é<").as_str(), "é<");
assert_eq!(SafeHtml::escape("<é").as_str(), "<é");
assert_eq!(SafeHtml::escape("𐒖").as_str(), "𐒖");
}
#[test]
fn test_escape_html_bytes_corner_cases() {
assert_eq!(escape_html_bytes(b"<\xFF>"), "<\u{FFFD}>");
assert_eq!(escape_html_bytes(b"abc\xE4\xB8"), "abc\u{FFFD}");
assert_eq!(escape_html_bytes(b""), "");
assert_eq!(escape_html_bytes("é<".as_bytes()), "é<");
assert_eq!(escape_html_bytes(b"\xFF<\xFF"), "\u{FFFD}<\u{FFFD}");
}
#[test]
fn test_json_escape_line_separators() {
assert_eq!(
escape_json_for_script("a\u{2028}b\u{2029}c"),
"a\\u2028b\\u2029c"
);
assert_eq!(escape_json_for_script("†‡•"), "†‡•");
}
#[test]
fn test_json_escape_edges() {
assert_eq!(escape_json_for_script(""), "");
assert_eq!(escape_json_for_script("<"), "\\u003c");
assert_eq!(
escape_json_for_script("<<<<"),
"\\u003c\\u003c\\u003c\\u003c"
);
assert_eq!(escape_json_for_script("</script>"), "\\u003c/script\\u003e");
let plain = r#"{"key": "value with spaces and 'quotes'"}"#;
assert_eq!(escape_json_for_script(plain), plain);
}
#[test]
fn test_url_policy_pins() {
assert!(is_safe_url_block_javascript("//evil.example/x"));
assert!(is_safe_url_restrictive("//evil.example/x"));
assert!(is_safe_url_restrictive("http"));
assert!(is_safe_url_restrictive("HTTP://a"));
assert!(is_safe_url_restrictive("HtTpS://a"));
assert!(is_safe_url_restrictive("MAILTO:a@b"));
assert!(!is_safe_url_restrictive("httpx://a"));
assert!(is_safe_url_block_javascript("data:text/html,<script>"));
assert!(is_safe_url_block_javascript("vbscript:x"));
assert!(is_safe_url_restrictive_with_schemes(
"javascript:alert(1)",
&["javascript"]
));
assert!(!is_safe_url_restrictive_with_schemes("foobar:x", &["foo"]));
assert!(!is_safe_url_restrictive_with_schemes("foo://bar", &[""]));
assert!(!is_safe_url_block_javascript(":foo"));
assert!(!is_safe_url_restrictive(":foo"));
assert!(!is_safe_url_restrictive("a&b"));
assert!(!is_safe_url_block_javascript("java\tscript:alert(1)"));
assert!(!is_safe_url_block_javascript("java script:alert(1)"));
}
#[test]
fn test_data_url_corners() {
assert!(!is_safe_url_restrictive(
"data:image/svg+xml;base64,PHN2Zz4="
));
assert!(!is_safe_url_restrictive("data:image/png;base64")); assert!(!is_safe_url_restrictive("data:;base64,QUJD")); assert!(!is_safe_url_restrictive("data:image/png,plain")); assert!(!is_safe_url_restrictive(
"data:image/png;foo=bar;base64,QUJD"
)); assert!(is_safe_url_restrictive("data:image/png;base64,QQ=="));
assert!(!is_safe_url_restrictive("data:image/png;base64,Q=Q"));
assert!(is_safe_url_restrictive("data:image/png;base64,="));
assert!(is_safe_url_restrictive("data:audio/x-matroska;base64,QUJD"));
}
#[test]
fn test_innocuous_url_fixed_point() {
assert_eq!(SafeUrl::sanitize(INNOCUOUS_URL).as_str(), INNOCUOUS_URL);
assert_eq!(
SafeUrl::sanitize_block_only_javascript(INNOCUOUS_URL).as_str(),
INNOCUOUS_URL
);
}
#[test]
fn test_safe_url_sanitize_variants() {
assert_eq!(
SafeUrl::sanitize_for_css("javascript:alert(1)").as_str(),
INNOCUOUS_URL
);
assert_eq!(
SafeUrl::sanitize_with_schemes("git://host/repo", &["git"]).as_str(),
"git://host/repo"
);
assert_eq!(
SafeUrl::sanitize_with_schemes("evil://x", &["git"]).as_str(),
INNOCUOUS_URL
);
}
#[test]
fn test_char_refs_corners() {
assert_eq!(
SafeHtml::escape_allow_character_references("&#;").as_str(),
"&#;"
);
assert_eq!(
SafeHtml::escape_allow_character_references("&NBSP;").as_str(),
"&NBSP;"
);
assert_eq!(
SafeHtml::escape_allow_character_references("&nb\u{E9}sp;").as_str(),
"&nbésp;"
);
let long = format!("&{}", "a".repeat(10_000));
assert_eq!(
SafeHtml::escape_allow_character_references(&long).as_str(),
format!("&{}", "a".repeat(10_000))
);
}
#[test]
fn test_url_encode_non_ascii() {
assert_eq!(url_encode_component("é"), "%C3%A9");
assert_eq!(url_encode_component("naïve day"), "na%C3%AFve%20day");
assert_eq!(url_encode_component(""), "");
}
#[test]
fn test_css_url_escape_corners() {
assert_eq!(percent_escape_css_url("a%27b"), "a%27b");
assert_eq!(percent_escape_css_url("'\"\\(),"), "%27%22%5C%28%29%2C");
assert_eq!(percent_escape_css_url("é"), "%C3%A9");
}
struct FailingWriter {
budget: usize,
}
impl core::fmt::Write for FailingWriter {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
if s.len() > self.budget {
return Err(core::fmt::Error);
}
self.budget -= s.len();
Ok(())
}
}
#[test]
fn test_writer_errors_propagate_without_panic() {
let input = "a<b\x7F\u{2028}é🎉 \x00 end";
for budget in 0..64 {
let _ = escape_html_and_coerce_to(input, &mut FailingWriter { budget });
let _ = coerce_to_interchange_valid_to(input, &mut FailingWriter { budget });
let _ = escape_allow_character_references_to(input, &mut FailingWriter { budget });
let _ = escape_json_for_script_to(input, &mut FailingWriter { budget });
let _ = url_encode_component_to(input, &mut FailingWriter { budget });
let _ = percent_escape_css_url_to(input, &mut FailingWriter { budget });
let _ =
coerce_bytes_to_interchange_valid_to(input.as_bytes(), &mut FailingWriter { budget });
let _ = escape_html_bytes_and_coerce_to(b"<\xFF>", &mut FailingWriter { budget });
}
assert!(escape_html_and_coerce_to("<", &mut FailingWriter { budget: 0 }).is_err());
assert!(escape_html_and_coerce_to("", &mut FailingWriter { budget: 0 }).is_ok());
}
#[test]
fn test_from_constant_and_default() {
assert_eq!(SafeHtml::from_constant("<div>").as_str(), "<div>");
assert_eq!(
SafeUrl::from_constant("https://cdn.example/a").as_str(),
"https://cdn.example/a"
);
assert_eq!(
SafeScript::from_constant("console.log(1)").as_str(),
"console.log(1)"
);
assert_eq!(
TrustedResourceUrl::from_constant("/static/app.js").as_str(),
"/static/app.js"
);
assert_eq!(
SafeStyle::from_constant("width:1em;").as_str(),
"width:1em;"
);
assert_eq!(
SafeStyleSheet::from_constant("p{width:1em;}").as_str(),
"p{width:1em;}"
);
assert_eq!(SafeHtml::default().as_str(), "");
assert_eq!(SafeUrl::default().as_str(), "");
assert_eq!(SafeScript::default().as_str(), "");
assert_eq!(TrustedResourceUrl::default().as_str(), "");
assert_eq!(SafeStyle::default().as_str(), "");
assert_eq!(SafeStyleSheet::default().as_str(), "");
}
#[test]
fn test_trusted_resource_url_basics() {
let empty = TrustedResourceUrl::empty();
assert!(empty.as_str().is_empty());
let u = TrustedResourceUrl::from_constant("/app.js");
assert_eq!(format!("{}", u), "/app.js");
assert_eq!(u.as_ref(), "/app.js");
assert_eq!(u.clone().into_string(), "/app.js");
let raw = unsafe { TrustedResourceUrl::from_string_unchecked("x".to_string()) };
assert_eq!(raw.as_str(), "x");
}
#[test]
fn test_safe_script_basics() {
assert!(SafeScript::empty().as_str().is_empty());
let s = SafeScript::from_constant("var x = 1;");
assert_eq!(format!("{}", s), "var x = 1;");
assert_eq!(s.clone().into_string(), "var x = 1;");
}
#[test]
fn test_push_query_param() {
let mut u = SafeUrl::sanitize("https://example.com/search");
u.push_query_param("q", "a&b=c d");
assert_eq!(u.as_str(), "https://example.com/search?q=a%26b%3Dc%20d");
u.push_query_param("page", "2");
assert_eq!(
u.as_str(),
"https://example.com/search?q=a%26b%3Dc%20d&page=2"
);
let mut f = SafeUrl::sanitize("https://example.com/p?x=1#frag");
f.push_query_param("y", "2");
assert_eq!(f.as_str(), "https://example.com/p?x=1&y=2#frag");
let mut t = TrustedResourceUrl::from_constant("/static/app.js");
t.push_query_param("v", "1.2.3");
assert_eq!(t.as_str(), "/static/app.js?v=1.2.3");
}
#[test]
fn test_proto_symmetry() {
let url = SafeUrl::sanitize("https://example.com");
let p = url.to_proto();
assert_eq!(SafeUrl::from_proto(Some(&p)), url);
assert_eq!(SafeUrl::from_proto(None).as_str(), "");
assert_eq!(
SafeUrl::from_proto(Some(&SafeUrlProto::default())).as_str(),
""
);
let script = SafeScript::from_constant("f()");
let p = script.to_proto();
assert_eq!(SafeScript::from_proto(Some(&p)), script);
assert_eq!(SafeScript::from_proto(None).as_str(), "");
assert_eq!(
SafeScript::from_proto(Some(&SafeScriptProto::default())).as_str(),
""
);
let tru = TrustedResourceUrl::from_constant("/x.js");
let p = tru.to_proto();
assert_eq!(TrustedResourceUrl::from_proto(Some(&p)), tru);
assert_eq!(TrustedResourceUrl::from_proto(None).as_str(), "");
assert_eq!(
TrustedResourceUrl::from_proto(Some(&TrustedResourceUrlProto::default())).as_str(),
""
);
let style = SafeStyle::from_constant("width:1em;");
let p = style.to_proto();
assert_eq!(SafeStyle::from_proto(Some(&p)), style);
assert_eq!(SafeStyle::from_proto(None).as_str(), "");
assert_eq!(
SafeStyle::from_proto(Some(&SafeStyleProto::default())).as_str(),
""
);
let sheet = SafeStyleSheet::from_constant("p{width:1em;}");
let p = sheet.to_proto();
assert_eq!(SafeStyleSheet::from_proto(Some(&p)), sheet);
assert_eq!(SafeStyleSheet::from_proto(None).as_str(), "");
assert_eq!(
SafeStyleSheet::from_proto(Some(&SafeStyleSheetProto::default())).as_str(),
""
);
}
#[test]
fn test_from_and_from_iterator() {
let s: String = SafeHtml::escape("x<y").into();
assert_eq!(s, "x<y");
let parts = vec![SafeHtml::escape("a"), SafeHtml::escape("b")];
let joined = SafeHtml::join(&parts, &SafeHtml::escape(","));
assert_eq!(joined.as_str(), "a,b");
let collected: SafeHtml = parts.iter().collect();
assert_eq!(collected.as_str(), "ab");
let collected_owned: SafeHtml = parts.into_iter().collect();
assert_eq!(collected_owned.as_str(), "ab");
}
#[test]
fn test_join_concat_empty() {
assert_eq!(SafeHtml::concat(Vec::<SafeHtml>::new()).as_str(), "");
assert_eq!(
SafeHtml::join(Vec::<SafeHtml>::new(), &SafeHtml::nbsp()).as_str(),
""
);
let parts = vec![SafeHtml::escape("a"), SafeHtml::escape("b")];
assert_eq!(SafeHtml::join(&parts, &SafeHtml::empty()).as_str(), "ab");
}
#[test]
fn test_safe_html_cat_edges() {
assert_eq!(safe_html_cat!().as_str(), "");
assert_eq!(safe_html_cat!('<').as_str(), "<");
assert_eq!(
safe_html_cat!(-5, " ", 2.5, " ", true).as_str(),
"-5 2.5 true"
);
}
#[test]
fn test_html_escaped_display() {
assert_eq!(
format!("{}", html_escaped("<a href='x'>")),
"<a href='x'>"
);
assert_eq!(
format!("pre {} post", html_escaped("a&b")),
"pre a&b post"
);
}
#[test]
fn test_style_property_value_validation() {
assert!(is_safe_style_property_value("1em"));
assert!(is_safe_style_property_value("100%"));
assert!(is_safe_style_property_value("#f00"));
assert!(is_safe_style_property_value("red !important"));
assert!(is_safe_style_property_value("0 auto"));
assert!(is_safe_style_property_value(""));
assert!(is_safe_style_property_value("1/2"));
assert!(!is_safe_style_property_value("/* comment */"));
assert!(!is_safe_style_property_value("a//b"));
assert!(!is_safe_style_property_value("a*/b*"));
assert!(!is_safe_style_property_value("url(http://evil)"));
assert!(!is_safe_style_property_value("expression(alert(1))"));
assert!(!is_safe_style_property_value("red;background:url(x)"));
assert!(!is_safe_style_property_value("'quoted'"));
assert!(!is_safe_style_property_value("a:b"));
assert!(!is_safe_style_property_value("<style>"));
assert!(is_safe_style_property_name("background-color"));
assert!(!is_safe_style_property_name(""));
assert!(!is_safe_style_property_name("color:red;x"));
}
#[test]
fn test_safe_style_from_properties() {
let style = SafeStyle::from_properties(&[
("width", "1em"),
("background-color", "#fff"),
("height", " 2em "), ]);
assert_eq!(
style.as_str(),
"width:1em;background-color:#fff;height:2em;"
);
let evil = SafeStyle::from_properties(&[("color", "red;}</style><script>x</script>")]);
assert_eq!(
evil.as_str(),
format!("color:{};", INNOCUOUS_PROPERTY_VALUE)
);
let skipped = SafeStyle::from_properties(&[("bad name!", "red"), ("color", "red")]);
assert_eq!(skipped.as_str(), "color:red;");
let mut a = SafeStyle::from_properties(&[("width", "1em")]);
a.append(&SafeStyle::from_properties(&[("height", "2em")]));
assert_eq!(a.as_str(), "width:1em;height:2em;");
}
#[test]
fn test_safe_style_background_image_url() {
let mut style = SafeStyle::empty();
style.push_background_image_url("https://example.com/img.png?a=1");
assert_eq!(
style.as_str(),
"background-image:url(\"https://example.com/img.png?a=1\");"
);
let mut breakout = SafeStyle::empty();
breakout.push_background_image_url("https://e.com/\");background:url(\"x");
assert!(!breakout.as_str().contains("\")b"));
assert!(breakout.as_str().starts_with("background-image:url(\""));
let mut evil = SafeStyle::empty();
evil.push_background_image_url("javascript:alert(1)");
assert!(evil.as_str().contains("about:invalid"));
}
#[test]
fn test_css_selector_validation() {
assert!(is_safe_css_selector("p"));
assert!(is_safe_css_selector("div.card > ul li:first-child"));
assert!(is_safe_css_selector("#id, .cls, a:hover"));
assert!(is_safe_css_selector("input[type=\"text\"]"));
assert!(is_safe_css_selector("*"));
assert!(!is_safe_css_selector(""));
assert!(!is_safe_css_selector("p{color:red}q"));
assert!(!is_safe_css_selector("p</style>"));
assert!(!is_safe_css_selector("a/*b*/"));
assert!(!is_safe_css_selector("p;q"));
assert!(!is_safe_css_selector("@media"));
assert!(!is_safe_css_selector("p)"));
assert!(!is_safe_css_selector("p("));
assert!(!is_safe_css_selector("a[b"));
assert!(!is_safe_css_selector("a\"b"));
assert!(!is_safe_css_selector("a\\b"));
}
#[test]
fn test_safe_style_sheet_rules() {
let style = SafeStyle::from_properties(&[("color", "red")]);
let sheet = SafeStyleSheet::from_style_rule("p.note", &style).unwrap();
assert_eq!(sheet.as_str(), "p.note{color:red;}");
assert!(SafeStyleSheet::from_style_rule("p{}</style>", &style).is_none());
let mut combined = SafeStyleSheet::from_style_rule("p", &style).unwrap();
combined.append(&SafeStyleSheet::from_style_rule("q", &style).unwrap());
assert_eq!(combined.as_str(), "p{color:red;}q{color:red;}");
}
#[cfg(feature = "serde")]
#[test]
fn test_serde_script_style_and_trusted() {
let s = SafeScript::from_constant("f(1)");
let ser = serde_json::to_string(&s).unwrap();
assert_eq!(ser, "\"f(1)\"");
let de: SafeScript = serde_json::from_str(&ser).unwrap();
assert_eq!(de, s);
let t = TrustedResourceUrl::from_constant("/a.js");
let ser = serde_json::to_string(&t).unwrap();
let de: TrustedResourceUrl = serde_json::from_str(&ser).unwrap();
assert_eq!(de, t);
let st = SafeStyle::from_properties(&[("width", "1em")]);
let ser = serde_json::to_string(&st).unwrap();
let de: SafeStyle = serde_json::from_str(&ser).unwrap();
assert_eq!(de, st);
let sh = SafeStyleSheet::from_constant("p{width:1em;}");
let ser = serde_json::to_string(&sh).unwrap();
let de: SafeStyleSheet = serde_json::from_str(&ser).unwrap();
assert_eq!(de, sh);
let rel: SafeUrl = serde_json::from_str("\"/path?x=1\"").unwrap();
assert_eq!(rel.as_str(), "/path?x=1");
}
#[test]
fn const_constructors_are_const_and_correct() {
const HTML: SafeHtml = SafeHtml::from_constant("<b>hi</b>");
const EMPTY: SafeHtml = SafeHtml::empty();
const NBSP: SafeHtml = SafeHtml::nbsp();
static URL: SafeUrl = SafeUrl::from_constant("https://example.com");
const SCRIPT: SafeScript = SafeScript::from_constant("run();");
const RES: TrustedResourceUrl = TrustedResourceUrl::from_constant("/static/app.js");
const STYLE: SafeStyle = SafeStyle::from_constant("color:red;");
const SHEET: SafeStyleSheet = SafeStyleSheet::from_constant("p{color:red;}");
assert_eq!(HTML.as_str(), "<b>hi</b>");
assert_eq!(EMPTY.as_str(), "");
assert_eq!(NBSP.as_str(), " ");
assert_eq!(URL.as_str(), "https://example.com");
assert_eq!(SCRIPT.as_str(), "run();");
assert_eq!(RES.as_str(), "/static/app.js");
assert_eq!(STYLE.as_str(), "color:red;");
assert_eq!(SHEET.as_str(), "p{color:red;}");
}
#[test]
fn constants_promote_to_owned_on_mutation() {
let mut html = SafeHtml::from_constant("<b>");
html.escape_and_append("<i>");
assert_eq!(html.as_str(), "<b><i>");
let mut url = SafeUrl::from_constant("https://example.com/");
url.push_query_param("q", "a b");
assert_eq!(url.as_str(), "https://example.com/?q=a%20b");
let mut style = SafeStyle::from_constant("color:red;");
style.push_property("margin", "0");
assert_eq!(style.as_str(), "color:red;margin:0;");
let mut sheet = SafeStyleSheet::from_constant("p{color:red;}");
sheet.append(&SafeStyleSheet::from_constant("b{margin:0;}"));
assert_eq!(sheet.as_str(), "p{color:red;}b{margin:0;}");
assert_eq!(SafeHtml::from_constant("x").into_string(), "x");
assert_eq!(String::from(SafeUrl::from_constant("/a")), "/a");
}
#[test]
fn borrowed_types_const_construction() {
use safehtml::{SafeHtmlStr, SafeStyleStr, SafeUrlStr};
const GREETING: &SafeHtmlStr = SafeHtmlStr::from_constant("<b>hello</b>");
static STYLE: &SafeStyleStr = SafeStyleStr::from_constant("color:red;");
assert_eq!(GREETING.as_str(), "<b>hello</b>");
assert_eq!(STYLE.as_str(), "color:red;");
assert_eq!(SafeHtmlStr::EMPTY.as_str(), "");
assert_eq!(SafeUrlStr::INNOCUOUS.as_str(), INNOCUOUS_URL);
assert_eq!(GREETING.len(), 12);
assert!(GREETING.starts_with("<b>"));
}
#[test]
fn borrowed_and_owned_interop() {
use safehtml::SafeHtmlStr;
let owned = SafeHtml::escape("<i>");
let borrowed: &SafeHtmlStr = &owned;
assert_eq!(borrowed.as_str(), "<i>");
assert!(owned.contains("lt"));
let owned_again: SafeHtml = borrowed.to_owned();
assert_eq!(owned_again, owned);
let converted = SafeHtml::from(SafeHtmlStr::from_constant("<hr>"));
assert_eq!(converted.as_str(), "<hr>");
assert_eq!(owned, *borrowed);
let cow: std::borrow::Cow<'_, SafeHtmlStr> = std::borrow::Cow::Borrowed(borrowed);
assert_eq!(cow.as_str(), "<i>");
let cat = safehtml::safe_html_cat!(SafeHtmlStr::from_constant("<p>"), "5 < 6");
assert_eq!(cat.as_str(), "<p>5 < 6");
}