Enum ammonia::UrlRelative[][src]

pub enum UrlRelative {
    Deny,
    PassThrough,
    RewriteWithBase(Url),
    Custom(Box<UrlRelativeEvaluate>),
    // some variants omitted
}

Policy for relative URLs, that is, URLs that do not specify the scheme in full.

This policy kicks in, if set, for any attribute named src or href, as well as the data attribute of an object tag.

Examples

Deny

  • <a href="test"> is a file-relative URL, and will be removed
  • <a href="/test"> is a domain-relative URL, and will be removed
  • <a href="//example.com/test"> is a scheme-relative URL, and will be removed
  • <a href="http://example.com/test"> is an absolute URL, and will be kept

PassThrough

No changes will be made to any URLs, except if a disallowed scheme is used.

RewriteWithBase

If the base is set to http://notriddle.com/some-directory/some-file

  • <a href="test"> will be rewritten to <a href="http://notriddle.com/some-directory/test">
  • <a href="/test"> will be rewritten to <a href="http://notriddle.com/test">
  • <a href="//example.com/test"> will be rewritten to <a href="http://example.com/test">
  • <a href="http://example.com/test"> is an absolute URL, so it will be kept as-is

Custom

Pass the relative URL to a function. If it returns Some(string), then that one gets used. Otherwise, it will remove the attribute (like Deny does).

use std::borrow::Cow;
fn is_absolute_path(url: &str) -> bool {
    let u = url.as_bytes();
    // `//a/b/c` is "protocol-relative", meaning "a" is a hostname
    // `/a/b/c` is an absolute path, and what we want to do stuff to.
    u.get(0) == Some(&b'/') && u.get(1) != Some(&b'/')
}
fn evaluate(url: &str) -> Option<Cow<str>> {
    if is_absolute_path(url) {
        Some(Cow::Owned(String::from("/root") + url))
    } else {
        Some(Cow::Borrowed(url))
    }
}
fn main() {
    let a = ammonia::Builder::new()
        .url_relative(ammonia::UrlRelative::Custom(Box::new(evaluate)))
        .clean("<a href=/test/path>fixed</a><a href=path>passed</a><a href=http://google.com/>skipped</a>")
        .to_string();
    assert_eq!(a, "<a href=\"/root/test/path\" rel=\"noopener noreferrer\">fixed</a><a href=\"path\" rel=\"noopener noreferrer\">passed</a><a href=\"http://google.com/\" rel=\"noopener noreferrer\">skipped</a>");
}

This function is only applied to relative URLs. To filter all of the URLs, use the not-yet-implemented Content Security Policy.

Variants

Relative URLs will be completely stripped from the document.

Relative URLs will be passed through unchanged.

Relative URLs will be changed into absolute URLs, based on this base URL.

Rewrite URLs with a custom function.

Trait Implementations

impl Debug for UrlRelative
[src]

Formats the value using the given formatter. Read more

Auto Trait Implementations

impl Send for UrlRelative

impl Sync for UrlRelative