#[derive(Debug, Clone, PartialEq, Eq)]
pub enum XssMode {
EscapeAll,
Whitelist(Vec<&'static str>),
}
pub struct XssProtector {
mode: XssMode,
}
impl XssProtector {
pub fn new(mode: XssMode) -> Self {
Self { mode }
}
pub fn sanitize(&self, input: &str) -> String {
match &self.mode {
XssMode::EscapeAll => {
let mut out = String::with_capacity(input.len());
escape_into(&mut out, input);
out
},
XssMode::Whitelist(allowed) => sanitize_whitelist(input, allowed),
}
}
pub fn sanitize_owned(&self, input: String) -> String {
let needs_escape = input
.chars()
.any(|c| matches!(c, '<' | '>' | '&' | '"' | '\''));
if !needs_escape {
return input;
}
self.sanitize(&input)
}
}
fn escape_into(out: &mut String, s: &str) {
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
}
fn parse_tag(rest: &str) -> Option<(&str, bool, &str, &str)> {
let bytes = rest.as_bytes();
if bytes.is_empty() || bytes[0] != b'<' {
return None;
}
let mut pos = 1;
let mut is_closing = false;
if pos < bytes.len() && bytes[pos] == b'/' {
is_closing = true;
pos += 1;
}
let name_start = pos;
if pos >= bytes.len() || !bytes[pos].is_ascii_alphabetic() {
return None;
}
pos += 1;
while pos < bytes.len() && bytes[pos].is_ascii_alphanumeric() {
pos += 1;
}
let name = &rest[name_start..pos];
let attrs_start = pos;
while pos < bytes.len() && bytes[pos] != b'>' {
pos += 1;
}
if pos >= bytes.len() {
return None;
}
let attrs = &rest[attrs_start..pos];
let after = &rest[pos + 1..];
Some((name, is_closing, attrs, after))
}
fn strip_event_handlers(attrs: &str) -> String {
let bytes = attrs.as_bytes();
let mut out = String::with_capacity(attrs.len());
let mut i = 0;
let mut last_copy = 0;
while i < bytes.len() {
let is_attr_start = i == 0 || bytes[i - 1].is_ascii_whitespace();
if is_attr_start
&& i + 2 <= bytes.len()
&& bytes[i].eq_ignore_ascii_case(&b'o')
&& bytes[i + 1].eq_ignore_ascii_case(&b'n')
{
let mut j = i + 2;
while j < bytes.len() && bytes[j].is_ascii_alphanumeric() {
j += 1;
}
if j < bytes.len() && bytes[j] == b'=' {
out.push_str(&attrs[last_copy..i]);
j += 1;
if j < bytes.len() {
match bytes[j] {
b'"' => {
j += 1;
while j < bytes.len() && bytes[j] != b'"' {
j += 1;
}
if j < bytes.len() {
j += 1;
}
},
b'\'' => {
j += 1;
while j < bytes.len() && bytes[j] != b'\'' {
j += 1;
}
if j < bytes.len() {
j += 1;
}
},
_ => {
while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
j += 1;
}
},
}
}
last_copy = j;
i = j;
continue;
}
}
i += 1;
}
out.push_str(&attrs[last_copy..]);
out
}
fn sanitize_whitelist(input: &str, allowed: &[&'static str]) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while !rest.is_empty() {
if rest.starts_with('<') {
if let Some((name, is_closing, attrs, after)) = parse_tag(rest) {
if allowed.contains(&name) {
out.push('<');
if is_closing {
out.push('/');
}
out.push_str(name);
let cleaned = strip_event_handlers(attrs);
let cleaned = strip_dangerous_uri(&cleaned);
escape_into(&mut out, &cleaned);
out.push('>');
rest = after;
} else {
out.push_str("<");
rest = &rest[1..];
}
} else {
out.push_str("<");
rest = &rest[1..];
}
} else {
let chunk_end = rest.find('<').unwrap_or(rest.len());
escape_into(&mut out, &rest[..chunk_end]);
rest = &rest[chunk_end..];
}
}
out
}
fn strip_dangerous_uri(attrs: &str) -> String {
let bytes = attrs.as_bytes();
let mut out = String::with_capacity(attrs.len());
let mut i = 0;
let mut last_copy = 0;
fn match_attr_name(bytes: &[u8], i: usize, target: &[u8]) -> Option<usize> {
if i + target.len() > bytes.len() {
return None;
}
for (k, &c) in target.iter().enumerate() {
if !bytes[i + k].eq_ignore_ascii_case(&c) {
return None;
}
}
let mut j = i + target.len();
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if j < bytes.len() && bytes[j] == b'=' {
Some(j + 1) } else {
None
}
}
fn is_safe_uri(value: &str) -> bool {
let lower = value.to_ascii_lowercase();
if lower.starts_with('#')
|| lower.starts_with('/')
|| lower.starts_with("./")
|| lower.starts_with("../")
{
return true;
}
if lower.starts_with("http://")
|| lower.starts_with("https://")
|| lower.starts_with("mailto:")
{
return true;
}
if let Some(colon_pos) = lower.find(':') {
if let Some(slash_pos) = lower.find('/') {
if slash_pos < colon_pos {
return true; }
}
false
} else {
true }
}
while i < bytes.len() {
let is_attr_start = i == 0 || bytes[i - 1].is_ascii_whitespace();
if is_attr_start {
let target_pos = match_attr_name(bytes, i, b"href")
.or_else(|| match_attr_name(bytes, i, b"src"))
.or_else(|| match_attr_name(bytes, i, b"xlink:href"));
if let Some(value_start) = target_pos {
out.push_str(&attrs[last_copy..value_start]);
let (value_end, value_str) = extract_attr_value(bytes, value_start);
let stripped = value_str
.trim_start_matches(|c: char| c.is_ascii_whitespace() || c.is_ascii_control());
let stripped = stripped.trim_matches(|c| c == '"' || c == '\'');
if is_safe_uri(stripped) {
out.push_str(&attrs[value_start..value_end]);
} else {
if value_start < bytes.len() && bytes[value_start] == b'"' {
out.push_str("\"#\"");
} else if value_start < bytes.len() && bytes[value_start] == b'\'' {
out.push_str("'#'");
} else {
out.push('#');
}
}
last_copy = value_end;
i = value_end;
continue;
}
}
i += 1;
}
out.push_str(&attrs[last_copy..]);
out
}
fn extract_attr_value(bytes: &[u8], start: usize) -> (usize, &str) {
if start >= bytes.len() {
return (start, "");
}
match bytes[start] {
b'"' => {
let mut j = start + 1;
while j < bytes.len() && bytes[j] != b'"' {
j += 1;
}
if j < bytes.len() {
j += 1; }
(j, std::str::from_utf8(&bytes[start..j]).unwrap_or(""))
},
b'\'' => {
let mut j = start + 1;
while j < bytes.len() && bytes[j] != b'\'' {
j += 1;
}
if j < bytes.len() {
j += 1;
}
(j, std::str::from_utf8(&bytes[start..j]).unwrap_or(""))
},
_ => {
let mut j = start;
while j < bytes.len() && !bytes[j].is_ascii_whitespace() {
j += 1;
}
(j, std::str::from_utf8(&bytes[start..j]).unwrap_or(""))
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escape_all_replaces_angle_brackets() {
let p = XssProtector::new(XssMode::EscapeAll);
assert_eq!(
p.sanitize("<script>alert(1)</script>"),
"<script>alert(1)</script>"
);
}
#[test]
fn escape_all_replaces_ampersand() {
let p = XssProtector::new(XssMode::EscapeAll);
assert_eq!(p.sanitize("a & b"), "a & b");
}
#[test]
fn escape_all_replaces_double_quote() {
let p = XssProtector::new(XssMode::EscapeAll);
assert_eq!(p.sanitize("\"quote\""), ""quote"");
}
#[test]
fn escape_all_replaces_single_quote() {
let p = XssProtector::new(XssMode::EscapeAll);
assert_eq!(p.sanitize("'single'"), "'single'");
}
#[test]
fn escape_all_handles_empty_input() {
let p = XssProtector::new(XssMode::EscapeAll);
assert_eq!(p.sanitize(""), "");
}
#[test]
fn whitelist_keeps_allowed_tags() {
let p = XssProtector::new(XssMode::Whitelist(vec!["b", "i"]));
assert_eq!(
p.sanitize("<b>bold</b><script>x</script>"),
"<b>bold</b><script>x</script>"
);
}
#[test]
fn whitelist_escapes_attributes() {
let p = XssProtector::new(XssMode::Whitelist(vec!["b"]));
assert_eq!(
p.sanitize("<b class=\"x\">text</b>"),
"<b class="x">text</b>"
);
}
#[test]
fn whitelist_escapes_text_content() {
let p = XssProtector::new(XssMode::Whitelist(vec!["b"]));
assert_eq!(p.sanitize("<b>a & b</b>"), "<b>a & b</b>");
}
#[test]
fn whitelist_empty_returns_empty() {
let p = XssProtector::new(XssMode::Whitelist(vec!["b"]));
assert_eq!(p.sanitize(""), "");
}
#[test]
fn whitelist_strips_event_handler_attributes() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b onclick=alert(1)>text</b>"#);
assert!(
!result.contains("onclick"),
"event handler attribute should be stripped, got: {}",
result
);
}
#[test]
fn whitelist_strips_quoted_event_handler_attributes() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b onclick="alert(1)">text</b>"#);
assert!(
!result.contains("onclick"),
"quoted event handler attribute should be stripped, got: {}",
result
);
}
#[test]
fn whitelist_strips_single_quoted_event_handler_attributes() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b onclick='alert(1)'>text</b>"#);
assert!(
!result.contains("onclick"),
"single-quoted event handler attribute should be stripped, got: {}",
result
);
}
#[test]
fn whitelist_strips_uppercase_event_handler() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b ONCLICK=alert(1)>text</b>"#);
assert!(
!result.to_lowercase().contains("onclick"),
"uppercase ONCLICK should be stripped, got: {}",
result
);
}
#[test]
fn whitelist_strips_mixedcase_event_handler() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b OnClick=alert(1)>text</b>"#);
assert!(
!result.to_lowercase().contains("onclick"),
"mixed-case OnClick should be stripped, got: {}",
result
);
}
#[test]
fn whitelist_strips_mixedcase_onsubmit() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["b"]));
let result = protector.sanitize(r#"<b oNsUbMiT=alert(1)>text</b>"#);
assert!(
!result.to_lowercase().contains("onsubmit"),
"mixed-case oNsUbMiT should be stripped, got: {}",
result
);
}
#[test]
fn sanitize_owned_no_escape_returns_original() {
let p = XssProtector::new(XssMode::EscapeAll);
let input = String::from("hello world");
let result = p.sanitize_owned(input);
assert_eq!(result, "hello world");
}
#[test]
fn sanitize_owned_escapes_special_chars() {
let p = XssProtector::new(XssMode::EscapeAll);
let result = p.sanitize_owned(String::from("<script>alert(1)</script>"));
assert_eq!(result, "<script>alert(1)</script>");
}
#[test]
fn sanitize_owned_empty_string() {
let p = XssProtector::new(XssMode::EscapeAll);
let result = p.sanitize_owned(String::new());
assert_eq!(result, "");
}
#[test]
fn whitelist_strips_javascript_uri_in_href() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="javascript:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"javascript: scheme 应被替换为 #,实际: {}",
result
);
assert!(result.contains("#"), "href 值应含 #,实际: {}", result);
}
#[test]
fn whitelist_strips_mixedcase_javascript_uri() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="JavaScript:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"JavaScript: 大小写绕过应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_uppercase_javascript_uri() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="JAVASCRIPT:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"JAVASCRIPT: 全大写应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_with_leading_whitespace() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href=" javascript:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"前导空白的 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_data_uri_scheme() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result =
protector.sanitize(r#"<a href="data:text/html,<script>alert(1)</script>">click</a>"#);
assert!(
!result.to_lowercase().contains("data:"),
"data: scheme 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_vbscript_uri_scheme() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="vbscript:msgbox(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("vbscript"),
"vbscript: scheme 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_https_url() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="https://example.com">click</a>"#);
assert!(
result.contains("https://example.com"),
"合法 https:// URL 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_http_url() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="http://example.com">click</a>"#);
assert!(
result.contains("http://example.com"),
"合法 http:// URL 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_mailto_uri() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="mailto:user@example.com">email</a>"#);
assert!(
result.contains("mailto:user@example.com"),
"合法 mailto: 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_anchor_uri() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r##"<a href="#section">jump</a>"##);
assert!(
result.contains("#section"),
"锚点 #section 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_absolute_path() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="/path/to/resource">link</a>"#);
assert!(
result.contains("/path/to/resource"),
"绝对路径应保留,实际: {}",
result
);
}
#[test]
fn whitelist_keeps_relative_path() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href="./relative">link</a>"#);
assert!(
result.contains("./relative"),
"相对路径 ./relative 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_in_src() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["img"]));
let result = protector.sanitize(r#"<img src="javascript:alert(1)">"#);
assert!(
!result.to_lowercase().contains("javascript"),
"src 中的 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_single_quoted() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href='javascript:alert(1)'>click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"单引号 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_unquoted() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a href=javascript:alert(1)>click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"无引号 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_uppercase_attr() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a HREF="javascript:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"大写 HREF 中的 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_mixedcase_attr() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector.sanitize(r#"<a Href="javascript:alert(1)">click</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"混合大小写 Href 中的 javascript: 应被替换为 #,实际: {}",
result
);
}
#[test]
fn whitelist_strips_only_dangerous_uri_keeps_safe_attrs() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["a"]));
let result = protector
.sanitize(r#"<a href="javascript:alert(1)" title="click me" class="link">text</a>"#);
assert!(
!result.to_lowercase().contains("javascript"),
"javascript: 应被替换,实际: {}",
result
);
assert!(
result.contains("click me"),
"title 属性应保留,实际: {}",
result
);
assert!(
result.contains("link"),
"class 属性应保留,实际: {}",
result
);
}
#[test]
fn whitelist_strips_only_dangerous_uri_keeps_safe_uri() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["img"]));
let result = protector
.sanitize(r#"<img src="https://safe.com/img.png" data-href="javascript:alert(1)">"#);
assert!(
result.contains("https://safe.com/img.png"),
"安全 src 应保留,实际: {}",
result
);
}
#[test]
fn whitelist_strips_javascript_uri_in_xlink_href() {
let protector = XssProtector::new(XssMode::Whitelist(vec!["use"]));
let result = protector.sanitize(r#"<use xlink:href="javascript:alert(1)">"#);
assert!(
!result.to_lowercase().contains("javascript"),
"xlink:href 中的 javascript: 应被替换为 #,实际: {}",
result
);
}
}