Struct ammonia::Builder

source ·
pub struct Builder<'a> { /* private fields */ }
Expand description

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 to generic_attributes or the tag_attributes for the <a> tag, and link_rel is not set to None.

    For example, this is going to panic, since link_rel is set to Some("noopener noreferrer") by default, and it makes no sense to simultaneously say that the user is allowed to set their own rel attribute while saying that every link shall be set to a particular value:

    use ammonia::Builder;
    use maplit::hashset;
    
    Builder::default()
        .generic_attributes(hashset!["rel"])
        .clean("");

    This, however, is perfectly valid:

    use ammonia::Builder;
    use maplit::hashset;
    
    Builder::default()
        .generic_attributes(hashset!["rel"])
        .link_rel(None)
        .clean("");
  • The class attribute is in allowed_classes and is in the corresponding tag_attributes or in generic_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:

    use ammonia::Builder;
    use maplit::{hashmap, hashset};
    
    Builder::default()
        .generic_attributes(hashset!["class"])
        .allowed_classes(hashmap!["span" => hashset!["hidden"]])
        .clean("");

    This, however, is perfectly valid:

    use ammonia::Builder;
    use maplit::{hashmap, hashset};
    
    Builder::default()
        .allowed_classes(hashmap!["span" => hashset!["hidden"]])
        .clean("");
  • A tag is in either tags or tag_attributes while also being in clean_content_tags.

    Both tags and tag_attributes are whitelists but clean_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 in tags by default:

    use ammonia::Builder;
    use maplit::hashset;
    
    Builder::default()
        .clean_content_tags(hashset!["aside"])
        .clean("");

    This, however, is valid:

    use ammonia::Builder;
    use maplit::hashset;
    
    Builder::default()
        .rm_tags(&["aside"])
        .clean_content_tags(hashset!["aside"])
        .clean("");

Implementations§

source§

impl<'a> Builder<'a>

source

pub fn tags(&mut self, value: HashSet<&'a str>) -> &mut Self

Sets the tags that are allowed.

§Examples
use ammonia::Builder;
use maplit::hashset;

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, 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
source

pub fn add_tags<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, it: I, ) -> &mut Self

Add additonal whitelisted tags without overwriting old ones.

Does nothing if the tag is already there.

§Examples
let a = ammonia::Builder::default()
    .add_tags(&["my-tag"])
    .clean("<my-tag>test</my-tag> <span>mess</span>").to_string();
assert_eq!("<my-tag>test</my-tag> <span>mess</span>", a);
source

pub fn rm_tags<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, it: I, ) -> &mut Self

Remove already-whitelisted tags.

Does nothing if the tags is already gone.

§Examples
let a = ammonia::Builder::default()
    .rm_tags(&["span"])
    .clean("<span></span>").to_string();
assert_eq!("", a);
source

pub fn clone_tags(&self) -> HashSet<&'a str>

Returns a copy of the set of whitelisted tags.

§Examples
use maplit::hashset;

let tags = hashset!["my-tag-1", "my-tag-2"];

let mut b = ammonia::Builder::default();
b.tags(Clone::clone(&tags));
assert_eq!(tags, b.clone_tags());
source

pub fn clean_content_tags(&mut self, value: HashSet<&'a str>) -> &mut Self

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
use ammonia::Builder;
use maplit::hashset;

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
script, style
source

pub fn add_clean_content_tags<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, it: I, ) -> &mut Self

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(&["my-tag"])
    .clean("<my-tag>test</my-tag><span>mess</span>").to_string();
assert_eq!("<span>mess</span>", a);
source

pub fn rm_clean_content_tags<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, it: I, ) -> &mut Self

Remove already-blacklisted clean-content tags.

Does nothing if the tags aren’t blacklisted.

§Examples
use ammonia::Builder;
use maplit::hashset;

let tag_blacklist = hashset!["script"];
let a = ammonia::Builder::default()
    .clean_content_tags(tag_blacklist)
    .rm_clean_content_tags(&["script"])
    .clean("<script>XSS</script>").to_string();
assert_eq!("XSS", a);
source

pub fn clone_clean_content_tags(&self) -> HashSet<&'a str>

Returns a copy of the set of blacklisted clean-content tags.

§Examples

let tags = hashset!["my-tag-1", "my-tag-2"];

let mut b = ammonia::Builder::default();
b.clean_content_tags(Clone::clone(&tags));
assert_eq!(tags, b.clone_clean_content_tags());
source

pub fn tag_attributes( &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
use ammonia::Builder;
use maplit::{hashmap, hashset};

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
source

pub fn add_tag_attributes<T: 'a + ?Sized + Borrow<str>, U: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, tag: &'a U, it: I, ) -> &mut Self

Add additonal whitelisted tag-specific attributes without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_tags(&["my-tag"])
    .add_tag_attributes("my-tag", &["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);
source

pub fn rm_tag_attributes<'b, 'c, T: 'b + ?Sized + Borrow<str>, U: 'c + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, tag: &'c U, 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", &["href"])
    .clean("<a href=\"/\"></a>").to_string();
assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
source

pub fn clone_tag_attributes(&self) -> HashMap<&'a str, HashSet<&'a str>>

Returns a copy of the set of whitelisted tag-specific attributes.

§Examples
use maplit::{hashmap, hashset};

let tag_attributes = hashmap![
    "my-tag" => hashset!["my-attr-1", "my-attr-2"]
];

let mut b = ammonia::Builder::default();
b.tag_attributes(Clone::clone(&tag_attributes));
assert_eq!(tag_attributes, b.clone_tag_attributes());
source

pub fn tag_attribute_values( &mut self, value: HashMap<&'a str, HashMap<&'a str, HashSet<&'a str>>>, ) -> &mut Self

Sets the values of HTML attributes that are allowed on specific tags.

The value is structured as a map from tag names to a map from attribute names to a set of attribute values.

If a tag is not itself whitelisted, adding entries to this map will do nothing.

§Examples
use ammonia::Builder;
use maplit::{hashmap, hashset};

let tags = hashset!["my-tag"];
let tag_attribute_values = hashmap![
    "my-tag" => hashmap![
        "my-attr" => hashset!["val"],
    ],
];
let a = Builder::new().tags(tags).tag_attribute_values(tag_attribute_values)
    .clean("<my-tag my-attr=val>")
    .to_string();
assert_eq!(a, "<my-tag my-attr=\"val\"></my-tag>");
§Defaults

None.

source

pub fn add_tag_attribute_values<T: 'a + ?Sized + Borrow<str>, U: 'a + ?Sized + Borrow<str>, V: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, tag: &'a U, attribute: &'a V, it: I, ) -> &mut Self

Add additonal whitelisted tag-specific attribute values without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_tags(&["my-tag"])
    .add_tag_attribute_values("my-tag", "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);
source

pub fn rm_tag_attribute_values<'b, 'c, T: 'b + ?Sized + Borrow<str>, U: 'c + ?Sized + Borrow<str>, V: 'c + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, tag: &'c U, attribute: &'c V, it: I, ) -> &mut Self

Remove already-whitelisted tag-specific attribute values.

Does nothing if the attribute or the value is already gone.

§Examples
let a = ammonia::Builder::default()
    .rm_tag_attributes("a", &["href"])
    .add_tag_attribute_values("a", "href", &["/"])
    .rm_tag_attribute_values("a", "href", &["/"])
    .clean("<a href=\"/\"></a>").to_string();
assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
source

pub fn clone_tag_attribute_values( &self, ) -> HashMap<&'a str, HashMap<&'a str, HashSet<&'a str>>>

Returns a copy of the set of whitelisted tag-specific attribute values.

§Examples
use maplit::{hashmap, hashset};

let attribute_values = hashmap![
    "my-attr-1" => hashset!["foo"],
    "my-attr-2" => hashset!["baz", "bar"],
];
let tag_attribute_values = hashmap![
    "my-tag" => attribute_values
];

let mut b = ammonia::Builder::default();
b.tag_attribute_values(Clone::clone(&tag_attribute_values));
assert_eq!(tag_attribute_values, b.clone_tag_attribute_values());
source

pub fn set_tag_attribute_values( &mut self, value: HashMap<&'a str, HashMap<&'a str, &'a str>>, ) -> &mut Self

Sets the values of HTML attributes that are to be set on specific tags.

The value is structured as a map from tag names to a map from attribute names to an attribute value.

If a tag is not itself whitelisted, adding entries to this map will do nothing.

§Examples
use ammonia::Builder;
use maplit::{hashmap, hashset};

let tags = hashset!["my-tag"];
let set_tag_attribute_values = hashmap![
    "my-tag" => hashmap![
        "my-attr" => "val",
    ],
];
let a = Builder::new().tags(tags).set_tag_attribute_values(set_tag_attribute_values)
    .clean("<my-tag>")
    .to_string();
assert_eq!(a, "<my-tag my-attr=\"val\"></my-tag>");
§Defaults

None.

source

pub fn set_tag_attribute_value<T: 'a + ?Sized + Borrow<str>, A: 'a + ?Sized + Borrow<str>, V: 'a + ?Sized + Borrow<str>>( &mut self, tag: &'a T, attribute: &'a A, value: &'a V, ) -> &mut Self

Add an attribute value to set on a specific element.

§Examples
let a = ammonia::Builder::default()
    .add_tags(&["my-tag"])
    .set_tag_attribute_value("my-tag", "my-attr", "val")
    .clean("<my-tag>test</my-tag> <span>mess</span>").to_string();
assert_eq!("<my-tag my-attr=\"val\">test</my-tag> <span>mess</span>", a);
source

pub fn rm_set_tag_attribute_value<T: 'a + ?Sized + Borrow<str>, A: 'a + ?Sized + Borrow<str>>( &mut self, tag: &'a T, attribute: &'a A, ) -> &mut Self

Remove existing tag-specific attribute values to be set.

Does nothing if the attribute is already gone.

§Examples
let a = ammonia::Builder::default()
    // this does nothing, since no value is set for this tag attribute yet
    .rm_set_tag_attribute_value("a", "target")
    .set_tag_attribute_value("a", "target", "_blank")
    .rm_set_tag_attribute_value("a", "target")
    .clean("<a href=\"/\"></a>").to_string();
assert_eq!("<a href=\"/\" rel=\"noopener noreferrer\"></a>", a);
source

pub fn get_set_tag_attribute_value<T: 'a + ?Sized + Borrow<str>, A: 'a + ?Sized + Borrow<str>>( &self, tag: &'a T, attribute: &'a A, ) -> Option<&'a str>

Returns the value that will be set for the attribute on the element, if any.

§Examples
let mut b = ammonia::Builder::default();
b.set_tag_attribute_value("a", "target", "_blank");
let value = b.get_set_tag_attribute_value("a", "target");
assert_eq!(value, Some("_blank"));
source

pub fn clone_set_tag_attribute_values( &self, ) -> HashMap<&'a str, HashMap<&'a str, &'a str>>

Returns a copy of the set of tag-specific attribute values to be set.

§Examples
use maplit::{hashmap, hashset};

let attribute_values = hashmap![
    "my-attr-1" => "foo",
    "my-attr-2" => "bar",
];
let set_tag_attribute_values = hashmap![
    "my-tag" => attribute_values,
];

let mut b = ammonia::Builder::default();
b.set_tag_attribute_values(Clone::clone(&set_tag_attribute_values));
assert_eq!(set_tag_attribute_values, b.clone_set_tag_attribute_values());
source

pub fn generic_attribute_prefixes( &mut self, value: HashSet<&'a str>, ) -> &mut Self

Sets the prefix of attributes that are allowed on any tag.

§Examples
use ammonia::Builder;
use maplit::hashset;

let prefixes = hashset!["data-"];
let a = Builder::new()
    .generic_attribute_prefixes(prefixes)
    .clean("<b data-val=1>")
    .to_string();
assert_eq!(a, "<b data-val=\"1\"></b>");
§Defaults

No attribute prefixes are allowed by default.

source

pub fn add_generic_attribute_prefixes<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, it: I, ) -> &mut Self

Add additional whitelisted attribute prefix without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_generic_attribute_prefixes(&["my-"])
    .clean("<span my-attr>mess</span>").to_string();
assert_eq!("<span my-attr=\"\">mess</span>", a);
source

pub fn rm_generic_attribute_prefixes<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, it: I, ) -> &mut Self

Remove already-whitelisted attribute prefixes.

Does nothing if the attribute prefix is already gone.

§Examples
let a = ammonia::Builder::default()
    .add_generic_attribute_prefixes(&["data-", "code-"])
    .rm_generic_attribute_prefixes(&["data-"])
    .clean("<span code-test=\"foo\" data-test=\"cool\"></span>").to_string();
assert_eq!("<span code-test=\"foo\"></span>", a);
source

pub fn clone_generic_attribute_prefixes(&self) -> Option<HashSet<&'a str>>

Returns a copy of the set of whitelisted attribute prefixes.

§Examples
use maplit::hashset;

let generic_attribute_prefixes = hashset!["my-prfx-1-", "my-prfx-2-"];

let mut b = ammonia::Builder::default();
b.generic_attribute_prefixes(Clone::clone(&generic_attribute_prefixes));
assert_eq!(Some(generic_attribute_prefixes), b.clone_generic_attribute_prefixes());
source

pub fn generic_attributes(&mut self, value: HashSet<&'a str>) -> &mut Self

Sets the attributes that are allowed on any tag.

§Examples
use ammonia::Builder;
use maplit::hashset;

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
source

pub fn add_generic_attributes<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, it: I, ) -> &mut Self

Add additonal whitelisted attributes without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_generic_attributes(&["my-attr"])
    .clean("<span my-attr>mess</span>").to_string();
assert_eq!("<span my-attr=\"\">mess</span>", a);
source

pub fn rm_generic_attributes<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &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(&["title"])
    .clean("<span title=\"cool\"></span>").to_string();
assert_eq!("<span></span>", a);
source

pub fn clone_generic_attributes(&self) -> HashSet<&'a str>

Returns a copy of the set of whitelisted attributes.

§Examples
use maplit::hashset;

let generic_attributes = hashset!["my-attr-1", "my-attr-2"];

let mut b = ammonia::Builder::default();
b.generic_attributes(Clone::clone(&generic_attributes));
assert_eq!(generic_attributes, b.clone_generic_attributes());
source

pub fn url_schemes(&mut self, value: HashSet<&'a str>) -> &mut Self

Sets the URL schemes permitted on href and src attributes.

§Examples
use ammonia::Builder;
use maplit::hashset;

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&amp;xl=0&amp;dn=zero_len.fil&amp;xt=urn:bitprint:3I42H3S6NNFQ2MSVX7XZKYAYSCX5QBYJ.LWPNACQDBZRYXW3VHJVCJ64QBZNGHOHHHZWCLNQ&amp;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
source

pub fn add_url_schemes<T: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, it: I, ) -> &mut Self

Add additonal whitelisted URL schemes without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_url_schemes(&["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);
source

pub fn rm_url_schemes<'b, T: 'b + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &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(&["ftp"])
    .clean("<a href=\"ftp://ftp.mozilla.org/\"></a>").to_string();
assert_eq!("<a rel=\"noopener noreferrer\"></a>", a);
source

pub fn clone_url_schemes(&self) -> HashSet<&'a str>

Returns a copy of the set of whitelisted URL schemes.

§Examples
use maplit::hashset;

let url_schemes = hashset!["my-scheme-1", "my-scheme-2"];

let mut b = ammonia::Builder::default();
b.url_schemes(Clone::clone(&url_schemes));
assert_eq!(url_schemes, b.clone_url_schemes());
source

pub fn url_relative(&mut self, value: UrlRelative<'a>) -> &mut Self

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
source

pub fn attribute_filter<'cb, CallbackFn>( &mut self, callback: CallbackFn, ) -> &mut Self
where CallbackFn: for<'u> Fn(&str, &str, &'u str) -> Option<Cow<'u, str>> + Send + Sync + 'static,

Allows rewriting of all attributes using a callback.

The callback takes name of the element, attribute and its value. Returns None to remove the attribute, or a value to use.

Rewriting of attributes with URLs is done before url_relative().

§Panics

If more than one callback is set.

§Examples
use ammonia::Builder;
let a = Builder::new()
    .attribute_filter(|element, attribute, value| {
        match (element, attribute) {
            ("img", "src") => None,
            _ => Some(value.into())
        }
    })
    .link_rel(None)
    .clean("<a href=/><img alt=Home src=foo></a>")
    .to_string();
assert_eq!(a,
    r#"<a href="/"><img alt="Home"></a>"#);
source

pub fn is_url_relative_deny(&self) -> bool

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());
source

pub fn is_url_relative_pass_through(&self) -> bool

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());
source

pub fn is_url_relative_custom(&self) -> bool

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());

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:

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")

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"));
source

pub fn allowed_classes( &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
use ammonia::Builder;
use maplit::{hashmap, hashset};

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.

source

pub fn add_allowed_classes<T: 'a + ?Sized + Borrow<str>, U: 'a + ?Sized + Borrow<str>, I: IntoIter<Item = &'a T>>( &mut self, tag: &'a U, it: I, ) -> &mut Self

Add additonal whitelisted classes without overwriting old ones.

§Examples
let a = ammonia::Builder::default()
    .add_allowed_classes("a", &["onebox"])
    .clean("<a href=/ class=onebox>mess</span>").to_string();
assert_eq!("<a href=\"/\" class=\"onebox\" rel=\"noopener noreferrer\">mess</a>", a);
source

pub fn rm_allowed_classes<'b, 'c, T: 'b + ?Sized + Borrow<str>, U: 'c + ?Sized + Borrow<str>, I: IntoIter<Item = &'b T>>( &mut self, tag: &'c U, 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", &["active"])
    .rm_allowed_classes("span", &["active"])
    .clean("<span class=active>").to_string();
assert_eq!("<span class=\"\"></span>", a);
source

pub fn clone_allowed_classes(&self) -> HashMap<&'a str, HashSet<&'a str>>

Returns a copy of the set of whitelisted class attributes.

§Examples
use maplit::{hashmap, hashset};

let allowed_classes = hashmap![
    "my-tag" => hashset!["my-class-1", "my-class-2"]
];

let mut b = ammonia::Builder::default();
b.allowed_classes(Clone::clone(&allowed_classes));
assert_eq!(allowed_classes, b.clone_allowed_classes());
source

pub fn strip_comments(&mut self, value: bool) -> &mut Self

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

source

pub fn will_strip_comments(&self) -> bool

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());
source

pub fn id_prefix(&mut self, value: Option<&'a str>) -> &mut Self

Prefixes all “id” attribute values with a given string. Note that the tag and attribute themselves must still be whitelisted.

§Examples
use ammonia::Builder;
use maplit::hashset;

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

source

pub fn new() -> Self

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);
source

pub fn empty() -> Self

Constructs a Builder instance configured with no allowed tags.

§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>empty()</code> function</a>.";
let output = "This is an Ammonia example using the empty() function.";

let result = Builder::empty() // <--
    .url_relative(UrlRelative::RewriteWithBase(Url::parse("https://docs.rs/ammonia/1.0/ammonia/")?))
    .clean(input)
    .to_string();
assert_eq!(result, output);
source

pub fn clean(&self, src: &str) -> Document

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);
source

pub fn clean_from_reader<R>(&self, src: R) -> Result<Document>
where 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, "");

Trait Implementations§

source§

impl<'a> Debug for Builder<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<'a> Default for Builder<'a>

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Builder<'a>

§

impl<'a> !RefUnwindSafe for Builder<'a>

§

impl<'a> Send for Builder<'a>

§

impl<'a> Sync for Builder<'a>

§

impl<'a> Unpin for Builder<'a>

§

impl<'a> !UnwindSafe for Builder<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.