2021-04-09 00:22:17 +00:00
|
|
|
use std::collections::HashSet;
|
|
|
|
|
|
|
|
use ammonia::Builder;
|
|
|
|
|
|
|
|
pub fn clean_html(unsafe_html: &str) -> String {
|
2022-02-08 21:33:05 +00:00
|
|
|
let safe_html = Builder::default()
|
|
|
|
.add_generic_attributes(&["class"])
|
|
|
|
.add_tag_attributes("a", &["rel", "target"])
|
|
|
|
.link_rel(None)
|
|
|
|
.clean(unsafe_html)
|
|
|
|
.to_string();
|
|
|
|
safe_html
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn clean_html_strict(unsafe_html: &str) -> String {
|
2021-04-09 00:22:17 +00:00
|
|
|
let mut allowed_tags = HashSet::new();
|
|
|
|
allowed_tags.insert("a");
|
|
|
|
allowed_tags.insert("br");
|
2022-01-28 00:23:23 +00:00
|
|
|
allowed_tags.insert("pre");
|
|
|
|
allowed_tags.insert("code");
|
2021-04-09 00:22:17 +00:00
|
|
|
|
|
|
|
let safe_html = Builder::default()
|
|
|
|
.tags(allowed_tags)
|
|
|
|
.clean(unsafe_html)
|
|
|
|
.to_string();
|
|
|
|
safe_html
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_clean_html() {
|
2022-02-08 21:33:05 +00:00
|
|
|
let unsafe_html = r#"<p><span class="h-card"><a href="https://example.com/user" class="u-url mention" rel="ugc">@<span>user</span></a></span> test</p>"#;
|
2021-04-09 00:22:17 +00:00
|
|
|
let safe_html = clean_html(unsafe_html);
|
2022-02-08 21:33:05 +00:00
|
|
|
assert_eq!(safe_html, r#"<p><span class="h-card"><a href="https://example.com/user" class="u-url mention" rel="ugc">@<span>user</span></a></span> test</p>"#);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_clean_html_strict() {
|
|
|
|
let unsafe_html = r#"<p>test <b>bold</b><script>dangerous</script> with <a href="https://example.com">link</a> and <code>code</code></p>"#;
|
|
|
|
let safe_html = clean_html_strict(unsafe_html);
|
2022-01-28 00:23:23 +00:00
|
|
|
assert_eq!(safe_html, r#"test bold with <a href="https://example.com" rel="noopener noreferrer">link</a> and <code>code</code>"#);
|
2021-04-09 00:22:17 +00:00
|
|
|
}
|
|
|
|
}
|