HTML Sanitizer Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓HTML Sanitizer runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓std contains no HTML at all, and that fact shapes everything. The parser is html5ever with markup5ever, Servo's implementation of the WHATWG tree-construction algorithm; the sanitizer built on it is ammonia, whose Builder accepts tags, tag_attributes, generic_attributes, url_schemes, url_relative, link_rel and strip_comments, and whose clean returns a Document rather than a String.
- ✓Make the safe string a newtype with a private field, pub struct SafeHtml(String), so clean is its only constructor, and then deliberately do not derive Deserialize for it.
- ✓The Rust trap: The tree html5ever's RcDom sink builds is Rc<Node> with RefCell interiors, and Rc is not Send.
- ✓Text nodes are StrTendrils, reference-counted slices that share the input buffer instead of copying each run, so parsing allocates far less than the node count suggests.
What HTML Sanitizer actually is
HTML Sanitizer in Rust: what you actually reach for
Rust implementation
use ammonia::{Builder, UrlRelative};
use std::collections::{HashMap, HashSet};
/// Private field, and deliberately no Deserialize impl: serde would otherwise
/// mint a SafeHtml straight off the wire without ever calling clean().
pub struct SafeHtml(String);
impl SafeHtml {
pub fn as_str(&self) -> &str {
&self.0
}
}
pub fn clean(fragment: &str) -> SafeHtml {
let mut policy = Builder::default();
policy
.tags(HashSet::from(["p", "em", "code", "figure", "figcaption", "a"]))
.tag_attributes(HashMap::from([("a", HashSet::from(["href", "hreflang"]))]))
.generic_attributes(HashSet::from(["lang"]))
.url_schemes(HashSet::from(["https", "mailto"]))
.url_relative(UrlRelative::Deny)
.link_rel(Some("noopener noreferrer nofollow"))
.strip_comments(true);
// clean() hands back a Document, not a String, because the tree is written
// out by the same html5ever serializer that read it in. Re-parsing that
// output and serializing it again is precisely how mutation XSS appears.
SafeHtml(policy.clean(fragment).to_string())
}
#[cfg(test)]
mod tests {
#[test]
fn foreign_content_and_javascript_urls_do_not_survive() {
let out = super::clean(r#"<svg><a xlink:href="javascript:alert(1)">x</a></svg>"#);
assert!(!out.as_str().contains("javascript:"));
assert!(!out.as_str().contains("<svg"));
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for HTML Sanitizer?
std contains no HTML at all, and that fact shapes everything. The parser is html5ever with markup5ever, Servo's implementation of the WHATWG tree-construction algorithm; the sanitizer built on it is ammonia, whose Builder accepts tags, tag_attributes, generic_attributes, url_schemes, url_relative, link_rel and strip_comments, and whose clean returns a Document rather than a String. The url crate's Url parses schemes. scraper and kuchikiki wrap the same parser for querying. Nothing in that list is optional garnish: hand-rolled tokenizers are where the advisories come from.
What is the most common Rust mistake when implementing HTML Sanitizer?
The tree html5ever's RcDom sink builds is Rc<Node> with RefCell interiors, and Rc is not Send. Hold one of those handles across an .await and the generated future stops being Send, so tokio::spawn refuses it with an error naming Rc<Node> rather than anything in your own signature; the fix is to finish the parse and drop every handle before the suspension point. The same design bites synchronously through RefCell: iterate a node's children under borrow() while a removal path calls borrow_mut() on that cell and you get a BorrowMutError panic at run time, because that aliasing check is dynamic, not static.
How does HTML Sanitizer actually perform in Rust?
Text nodes are StrTendrils, reference-counted slices that share the input buffer instead of copying each run, so parsing allocates far less than the node count suggests. You pay instead in pointer chasing: each child access is an Rc refcount adjustment plus a RefCell borrow-flag check, both non-atomic and both real work. ammonia::clean allocates one Document and one output String, and the policy HashSets are built once if the Builder is hoisted out of the request path. There is no collector, so peak memory is input plus tree and it drops deterministically. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.