Struct ammonia::Builder
[−]
[src]
pub struct Builder<'a> { /* fields omitted */ }
An HTML sanitizer.
Given a fragment of HTML, Ammonia will parse it according to the HTML5 parsing algorithm and sanitize any disallowed tags or attributes. This algorithm also takes care of things like unclosed and (some) misnested tags.
Examples
use ammonia::{Builder, UrlRelative}; let a = Builder::default() .link_rel(None) .url_relative(UrlRelative::PassThrough) .clean("<a href=/>test") .to_string(); assert_eq!( a, "<a href=\"/\">test</a>");
Panics
Running clean
or clean_from_reader
may cause a panic if the builder is
configured with any of these (contradictory) settings:
The
rel
attribute is added togeneric_attributes
or thetag_attributes
for the<a>
tag, andlink_rel
is not set toNone
.For example, this is going to panic, since
link_rel
is set toSome("noopener noreferrer")
by default, and it makes no sense to simultaneously say that the user is allowed to set their ownrel
attribute while saying that every link shall be set to a particular value:#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .generic_attributes(hashset!["rel"]) .clean("");
This, however, is perfectly valid:
#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .generic_attributes(hashset!["rel"]) .link_rel(None) .clean("");
The
class
attribute is inallowed_classes
and is in the correspondingtag_attributes
or ingeneric_attributes
.This is done both to line up with the treatment of
rel
, and to prevent people from accidentally allowing arbitrary classes on a particular element.This will panic:
#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .generic_attributes(hashset!["class"]) .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean("");
This, however, is perfectly valid:
#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .allowed_classes(hashmap!["span" => hashset!["hidden"]]) .clean("");
A tag is in either
tags
ortag_attributes
while also being inclean_content_tags
.Both
tags
andtag_attributes
are whitelists butclean_content_tags
is a blacklist, so it doesn't make sense to have the same tag in both.For example, this will panic, since the
aside
tag is intags
by default:#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .clean_content_tags(hashset!["aside"]) .clean("");
This, however, is valid:
#[macro_use] extern crate maplit; use ammonia::Builder; Builder::default() .rm_tags(std::iter::once("aside")) .clean_content_tags(hashset!["aside"]) .clean("");
Methods
impl<'a> Builder<'a>
[src]
[src]
Sets the tags that are allowed.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let tags = hashset!["my-tag"]; let a = Builder::new() .tags(tags) .clean("<my-tag>") .to_string(); assert_eq!(a, "<my-tag></my-tag>");
Defaults
a, abbr, acronym, area, article, aside, b, bdi,
bdo, blockquote, br, caption, center, cite, code,
col, colgroup, data, dd, del, details, dfn, div,
dl, dt, em, figcaption, figure, footer, h1, h2,
h3, h4, h5, h6, header, hgroup, hr, i, img,
ins, kbd, kbd, li, map, mark, nav, ol, p, pre,
q, rp, rt, rtc, ruby, s, samp, small, span,
strike, strong, sub, summary, sup, table, tbody,
td, th, thead, time, tr, tt, u, ul, var, wbr
[src]
Add additonal whitelisted tags without overwriting old ones.
Does nothing if the tag is already there.
Examples
let a = ammonia::Builder::default() .add_tags(std::iter::once("my-tag")) .clean("<my-tag>test</my-tag> <span>mess</span>").to_string(); assert_eq!("<my-tag>test</my-tag> <span>mess</span>", a);
[src]
Remove already-whitelisted tags.
Does nothing if the tags is already gone.
Examples
let a = ammonia::Builder::default() .rm_tags(std::iter::once("span")) .clean("<span></span>").to_string(); assert_eq!("", a);
[src]
Returns a copy of the set of whitelisted tags.
Examples
let tags = ["my-tag-1", "my-tag-2"].into_iter().cloned().collect(); let mut b = ammonia::Builder::default(); b.tags(Clone::clone(&tags)); assert_eq!(tags, b.clone_tags());
[src]
Sets the tags whose contents will be completely removed from the output.
Adding tags which are whitelisted in tags
or tag_attributes
will cause
a panic.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let tag_blacklist = hashset!["script", "style"]; let a = Builder::new() .clean_content_tags(tag_blacklist) .clean("<script>alert('hello')</script><style>a { background: #fff }</style>") .to_string(); assert_eq!(a, "");
Defaults
No tags have content removed by default.
[src]
Add additonal blacklisted clean-content tags without overwriting old ones.
Does nothing if the tag is already there.
Adding tags which are whitelisted in tags
or tag_attributes
will cause
a panic.
Examples
let a = ammonia::Builder::default() .add_clean_content_tags(std::iter::once("my-tag")) .clean("<my-tag>test</my-tag><span>mess</span>").to_string(); assert_eq!("<span>mess</span>", a);
[src]
Remove already-blacklisted clean-content tags.
Does nothing if the tags aren't blacklisted.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let tag_blacklist = hashset!["script"]; let a = ammonia::Builder::default() .clean_content_tags(tag_blacklist) .rm_clean_content_tags(std::iter::once("script")) .clean("<script>XSS</script>").to_string(); assert_eq!("XSS", a);
[src]
Returns a copy of the set of blacklisted clean-content tags.
Examples
let tags = ["my-tag-1", "my-tag-2"].into_iter().cloned().collect(); let mut b = ammonia::Builder::default(); b.clean_content_tags(Clone::clone(&tags)); assert_eq!(tags, b.clone_clean_content_tags());
fn tag_attributes(
&mut self,
value: HashMap<&'a str, HashSet<&'a str>>
) -> &mut Self
[src]
&mut self,
value: HashMap<&'a str, HashSet<&'a str>>
) -> &mut Self
Sets the HTML attributes that are allowed on specific tags.
The value is structured as a map from tag names to a set of attribute names.
If a tag is not itself whitelisted, adding entries to this map will do nothing.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let tags = hashset!["my-tag"]; let tag_attributes = hashmap![ "my-tag" => hashset!["val"] ]; let a = Builder::new().tags(tags).tag_attributes(tag_attributes) .clean("<my-tag val=1>") .to_string(); assert_eq!(a, "<my-tag val=\"1\"></my-tag>");
Defaults
a =>
href, hreflang
bdo =>
dir
blockquote =>
cite
col =>
align, char, charoff, span
colgroup =>
align, char, charoff, span
del =>
cite, datetime
hr =>
align, size, width
img =>
align, alt, height, src, width
ins =>
cite, datetime
ol =>
start
q =>
cite
table =>
align, char, charoff, summary
tbody =>
align, char, charoff
td =>
align, char, charoff, colspan, headers, rowspan
tfoot =>
align, char, charoff
th =>
align, char, charoff, colspan, headers, rowspan, scope
thead =>
align, char, charoff
tr =>
align, char, charoff
fn add_tag_attributes<I: Iterator<Item = &'a str>>(
&mut self,
tag: &'a str,
it: I
) -> &mut Self
[src]
&mut self,
tag: &'a str,
it: I
) -> &mut Self
Add additonal whitelisted tag-specific attributes without overwriting old ones.
Examples
let a = ammonia::Builder::default() .add_tags(std::iter::once("my-tag")) .add_tag_attributes("my-tag", std::iter::once("my-attr")) .clean("<my-tag my-attr>test</my-tag> <span>mess</span>").to_string(); assert_eq!("<my-tag my-attr=\"\">test</my-tag> <span>mess</span>", a);
fn rm_tag_attributes<'b, 'c, I: Iterator<Item = &'b str>>(
&mut self,
tag: &'c str,
it: I
) -> &mut Self
[src]
&mut self,
tag: &'c str,
it: I
) -> &mut Self
Remove already-whitelisted tag-specific attributes.
Does nothing if the attribute is already gone.
Examples
let a = ammonia::Builder::default() .rm_tag_attributes("a", std::iter::once("href")) .clean("<a href=\"/\"></a>").to_string(); assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
fn clone_tag_attributes(&self) -> HashMap<&'a str, HashSet<&'a str>>
[src]
Returns a copy of the set of whitelisted tag-specific attributes.
Examples
let tag_attributes = std::iter::once( ("my-tag", ["my-attr-1", "my-attr-2"].into_iter().cloned().collect()) ).collect(); let mut b = ammonia::Builder::default(); b.tag_attributes(Clone::clone(&tag_attributes)); assert_eq!(tag_attributes, b.clone_tag_attributes());
fn generic_attributes(&mut self, value: HashSet<&'a str>) -> &mut Self
[src]
Sets the attributes that are allowed on any tag.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let attributes = hashset!["data-val"]; let a = Builder::new() .generic_attributes(attributes) .clean("<b data-val=1>") .to_string(); assert_eq!(a, "<b data-val=\"1\"></b>");
Defaults
lang, title
fn add_generic_attributes<I: Iterator<Item = &'a str>>(
&mut self,
it: I
) -> &mut Self
[src]
&mut self,
it: I
) -> &mut Self
Add additonal whitelisted attributes without overwriting old ones.
Examples
let a = ammonia::Builder::default() .add_generic_attributes(std::iter::once("my-attr")) .clean("<span my-attr>mess</span>").to_string(); assert_eq!("<span my-attr=\"\">mess</span>", a);
fn rm_generic_attributes<'b, I: Iterator<Item = &'b str>>(
&mut self,
it: I
) -> &mut Self
[src]
&mut self,
it: I
) -> &mut Self
Remove already-whitelisted attributes.
Does nothing if the attribute is already gone.
Examples
let a = ammonia::Builder::default() .rm_generic_attributes(std::iter::once("title")) .clean("<span title=\"cool\"></span>").to_string(); assert_eq!("<span></span>", a);
fn clone_generic_attributes(&self) -> HashSet<&'a str>
[src]
Returns a copy of the set of whitelisted attributes.
Examples
let generic_attributes = ["my-attr-1", "my-attr-2"].into_iter().cloned().collect(); let mut b = ammonia::Builder::default(); b.generic_attributes(Clone::clone(&generic_attributes)); assert_eq!(generic_attributes, b.clone_generic_attributes());
fn url_schemes(&mut self, value: HashSet<&'a str>) -> &mut Self
[src]
Sets the URL schemes permitted on href
and src
attributes.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let url_schemes = hashset![ "http", "https", "mailto", "magnet" ]; let a = Builder::new().url_schemes(url_schemes) .clean("<a href=\"magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E\">zero-length file</a>") .to_string(); // See `link_rel` for information on the rel="noopener noreferrer" attribute // in the cleaned HTML. assert_eq!(a, "<a href=\"magnet:?xt=urn:ed2k:31D6CFE0D16AE931B73C59D7E0C089C0&xl=0&dn=zero_len.fil&xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&xt=urn:md5:D41D8CD98F00B204E9800998ECF8427E\" rel=\"noopener noreferrer\">zero-length file</a>");
Defaults
bitcoin, ftp, ftps, geo, http, https, im, irc,
ircs, magnet, mailto, mms, mx, news, nntp,
openpgp4fpr, sip, sms, smsto, ssh, tel, url,
webcal, wtai, xmpp
fn add_url_schemes<I: Iterator<Item = &'a str>>(&mut self, it: I) -> &mut Self
[src]
Add additonal whitelisted URL schemes without overwriting old ones.
Examples
let a = ammonia::Builder::default() .add_url_schemes(std::iter::once("my-scheme")) .clean("<a href=my-scheme:home>mess</span>").to_string(); assert_eq!("<a href=\"my-scheme:home\" rel=\"noopener noreferrer\">mess</a>", a);
fn rm_url_schemes<'b, I: Iterator<Item = &'b str>>(
&mut self,
it: I
) -> &mut Self
[src]
&mut self,
it: I
) -> &mut Self
Remove already-whitelisted attributes.
Does nothing if the attribute is already gone.
Examples
let a = ammonia::Builder::default() .rm_url_schemes(std::iter::once("ftp")) .clean("<a href=\"ftp://ftp.mozilla.org/\"></a>").to_string(); assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
fn clone_url_schemes(&self) -> HashSet<&'a str>
[src]
Returns a copy of the set of whitelisted URL schemes.
Examples
let url_schemes = ["my-scheme-1", "my-scheme-2"].into_iter().cloned().collect(); let mut b = ammonia::Builder::default(); b.url_schemes(Clone::clone(&url_schemes)); assert_eq!(url_schemes, b.clone_url_schemes());
fn url_relative(&mut self, value: UrlRelative) -> &mut Self
[src]
Configures the behavior for relative URLs: pass-through, resolve-with-base, or deny.
Examples
use ammonia::{Builder, UrlRelative}; let a = Builder::new().url_relative(UrlRelative::PassThrough) .clean("<a href=/>Home</a>") .to_string(); // See `link_rel` for information on the rel="noopener noreferrer" attribute // in the cleaned HTML. assert_eq!( a, "<a href=\"/\" rel=\"noopener noreferrer\">Home</a>");
Defaults
UrlRelative::PassThrough
fn is_url_relative_deny(&self) -> bool
[src]
Returns true
if the relative URL resolver is set to Deny
.
Examples
use ammonia::{Builder, UrlRelative}; let mut a = Builder::default(); a.url_relative(UrlRelative::Deny); assert!(a.is_url_relative_deny()); a.url_relative(UrlRelative::PassThrough); assert!(!a.is_url_relative_deny());
fn is_url_relative_pass_through(&self) -> bool
[src]
Returns true
if the relative URL resolver is set to PassThrough
.
Examples
use ammonia::{Builder, UrlRelative}; let mut a = Builder::default(); a.url_relative(UrlRelative::Deny); assert!(!a.is_url_relative_pass_through()); a.url_relative(UrlRelative::PassThrough); assert!(a.is_url_relative_pass_through());
fn is_url_relative_custom(&self) -> bool
[src]
Returns true
if the relative URL resolver is set to Custom
.
Examples
use ammonia::{Builder, UrlRelative}; use std::borrow::Cow; fn test(a: &str) -> Option<Cow<str>> { None } let mut a = Builder::default(); a.url_relative(UrlRelative::Custom(Box::new(test))); assert!(a.is_url_relative_custom()); a.url_relative(UrlRelative::PassThrough); assert!(!a.is_url_relative_custom()); a.url_relative(UrlRelative::Deny); assert!(!a.is_url_relative_custom());
fn link_rel(&mut self, value: Option<&'a str>) -> &mut Self
[src]
Configures a rel
attribute that will be added on links.
If rel
is in the generic or tag attributes, this must be set to None
.
Common rel
values to include:
noopener
: This prevents a particular type of XSS attack, and should usually be turned on for untrusted HTML.noreferrer
: This prevents the browser from sending the source URL to the website that is linked to.nofollow
: This prevents search engines from using this link for ranking, which disincentivizes spammers.
To turn on rel-insertion, call this function with a space-separated list. Ammonia does not parse rel-attributes; it just puts the given string into the attribute directly.
Examples
use ammonia::Builder; let a = Builder::new().link_rel(None) .clean("<a href=https://rust-lang.org/>Rust</a>") .to_string(); assert_eq!( a, "<a href=\"https://rust-lang.org/\">Rust</a>");
Defaults
Some("noopener noreferrer")
fn get_link_rel(&self) -> Option<&str>
[src]
Returns the settings for links' rel
attribute, if one is set.
Examples
use ammonia::{Builder, UrlRelative}; let mut a = Builder::default(); a.link_rel(Some("a b")); assert_eq!(a.get_link_rel(), Some("a b"));
fn allowed_classes(
&mut self,
value: HashMap<&'a str, HashSet<&'a str>>
) -> &mut Self
[src]
&mut self,
value: HashMap<&'a str, HashSet<&'a str>>
) -> &mut Self
Sets the CSS classes that are allowed on specific tags.
The values is structured as a map from tag names to a set of class names.
If the class
attribute is itself whitelisted for a tag, then adding entries to
this map will cause a panic.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let allowed_classes = hashmap![ "code" => hashset!["rs", "ex", "c", "cxx", "js"] ]; let a = Builder::new() .allowed_classes(allowed_classes) .clean("<code class=rs>fn main() {}</code>") .to_string(); assert_eq!( a, "<code class=\"rs\">fn main() {}</code>");
Defaults
The set of allowed classes is empty by default.
fn add_allowed_classes<I: Iterator<Item = &'a str>>(
&mut self,
tag: &'a str,
it: I
) -> &mut Self
[src]
&mut self,
tag: &'a str,
it: I
) -> &mut Self
Add additonal whitelisted classes without overwriting old ones.
Examples
let a = ammonia::Builder::default() .add_allowed_classes("a", std::iter::once("onebox")) .clean("<a href=/ class=onebox>mess</span>").to_string(); assert_eq!("<a href=\"/\" class=\"onebox\" rel=\"noopener noreferrer\">mess</a>", a);
fn rm_allowed_classes<'b, 'c, I: Iterator<Item = &'b str>>(
&mut self,
tag: &'c str,
it: I
) -> &mut Self
[src]
&mut self,
tag: &'c str,
it: I
) -> &mut Self
Remove already-whitelisted attributes.
Does nothing if the attribute is already gone.
Examples
let a = ammonia::Builder::default() .add_allowed_classes("span", std::iter::once("active")) .rm_allowed_classes("span", std::iter::once("active")) .clean("<span class=active>").to_string(); assert_eq!("<span class=\"\"></span>", a);
fn clone_allowed_classes(&self) -> HashMap<&'a str, HashSet<&'a str>>
[src]
Returns a copy of the set of whitelisted class attributes.
Examples
let allowed_classes = std::iter::once( ("my-tag", ["my-class-1", "my-class-2"].into_iter().cloned().collect()) ).collect(); let mut b = ammonia::Builder::default(); b.allowed_classes(Clone::clone(&allowed_classes)); assert_eq!(allowed_classes, b.clone_allowed_classes());
fn strip_comments(&mut self, value: bool) -> &mut Self
[src]
Configures the handling of HTML comments.
If this option is false, comments will be preserved.
Examples
use ammonia::Builder; let a = Builder::new().strip_comments(false) .clean("<!-- yes -->") .to_string(); assert_eq!( a, "<!-- yes -->");
Defaults
true
fn will_strip_comments(&self) -> bool
[src]
Returns true
if comment stripping is turned on.
Examples
let mut a = ammonia::Builder::new(); a.strip_comments(true); assert!(a.will_strip_comments()); a.strip_comments(false); assert!(!a.will_strip_comments());
fn id_prefix(&mut self, value: Option<&'a str>) -> &mut Self
[src]
Prefixes all "id" attribute values with a given string. Note that the tag and attribute themselves must still be whitelisted.
Examples
#[macro_use] extern crate maplit; use ammonia::Builder; let attributes = hashset!["id"]; let a = Builder::new() .generic_attributes(attributes) .id_prefix(Some("safe-")) .clean("<b id=42>") .to_string(); assert_eq!(a, "<b id=\"safe-42\"></b>");
Defaults
None
fn new() -> Self
[src]
Constructs a Builder
instance configured with the default options.
Examples
use ammonia::{Builder, Url, UrlRelative}; let input = "<!-- comments will be stripped -->This is an <a href=.>Ammonia</a> example using <a href=struct.Builder.html#method.new onclick=xss>the <code onmouseover=xss>new()</code> function</a>."; let output = "This is an <a href=\"https://docs.rs/ammonia/1.0/ammonia/\" rel=\"noopener noreferrer\">Ammonia</a> example using <a href=\"https://docs.rs/ammonia/1.0/ammonia/struct.Builder.html#method.new\" rel=\"noopener noreferrer\">the <code>new()</code> function</a>."; let result = Builder::new() // <-- .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); assert_eq!(result, output);
fn clean(&self, src: &str) -> Document
[src]
Sanitizes an HTML fragment in a string according to the configured options.
Examples
use ammonia::{Builder, Url, UrlRelative}; let input = "<!-- comments will be stripped -->This is an <a href=.>Ammonia</a> example using <a href=struct.Builder.html#method.new onclick=xss>the <code onmouseover=xss>new()</code> function</a>."; let output = "This is an <a href=\"https://docs.rs/ammonia/1.0/ammonia/\" rel=\"noopener noreferrer\">Ammonia</a> example using <a href=\"https://docs.rs/ammonia/1.0/ammonia/struct.Builder.html#method.new\" rel=\"noopener noreferrer\">the <code>new()</code> function</a>."; let result = Builder::new() .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?)) .clean(input) .to_string(); // <-- assert_eq!(result, output);
fn clean_from_reader<R>(&self, src: R) -> Result<Document> where
R: Read,
[src]
R: Read,
Sanitizes an HTML fragment from a reader according to the configured options.
The input should be in UTF-8 encoding, otherwise the decoding is lossy, just
like when using String::from_utf8_lossy
.
To avoid consuming the reader, a mutable reference can be passed to this method.
Examples
use ammonia::Builder; let a = Builder::new() .clean_from_reader(&b"<!-- no -->"[..])? // notice the `b` .to_string(); assert_eq!(a, "");