diff --git a/tests/sanitize.rs b/tests/sanitize.rs index 2b17242..cabab27 100644 --- a/tests/sanitize.rs +++ b/tests/sanitize.rs @@ -390,3 +390,399 @@ proptest! { 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 = "
green hi button

hidden


"; + +/// What v0.1.0 wrote for `COLOURED` (recorded before the dark option existed). +const COLOURED_ORIGINAL: &str = "
green hi button

hidden


"; + +/// 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 { + 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 { + 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!("button"), "{html}"); + // Borders and the rule take the rule colour. + assert!(html.contains(&format!("border: 1px solid {}", PALETTE.rule)), "{html}"); + assert!(html.contains(&format!("
", PALETTE.rule)), "{html}"); + // The blocked image is the dark placeholder, and the image itself is untouched (never inverted or dimmed). + assert!(html.contains(&format!("")), "{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: each lands within a few steps of the drawn colour. + for (from, drawn) in [("#c0392b", "#d7594c"), ("#2e7d32", "#36933b"), ("#1a43a6", "#517ce4")] { + let out = dark(&format!("

x

")); + 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}")); + let want = parse_colour(drawn).unwrap(); + assert!(contrast(got, PALETTE.body) >= MIN_CONTRAST, "{from} -> {got}"); + assert!(contrast(got, PALETTE.body) < MIN_CONTRAST + 0.4, "{from} -> {got}: lightened more than needed"); + let far = |a: u8, b: u8| a.abs_diff(b) > 8; + assert!(!(far(got.r, want.r) || far(got.g, want.g) || far(got.b, want.b)), "{from} -> {got}, drawn {drawn}"); + } + // A colour that is already readable stays as it is, and is no change. + let light = dark("

x

"); + 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!("

x

y")); + 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!("

x

")).html); + assert!(!html.contains("color"), "{colour}: {html}"); + } +} + +#[test] +fn important_is_removed_so_the_reader_wins() { + let out = dark("

x

"); + 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")); + 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!("
<{tag} style=\"background-color: #ffeb3b\">x
")).html, + ); + assert!(!html.contains("background"), "{tag}: {html}"); + } + // A white or grey background on words is no highlight: it just goes. + let white = decoded(&dark("x").html); + assert!(!white.contains("background"), "{white}"); + // A background of nothing is no change. + let none = dark("
x
y
"); + assert!(!none.colours_changed, "{}", none.html); +} + +#[test] +fn bgcolor_is_removed_and_counts_as_a_change() { + let out = dark("
x
"); + assert!(!out.html.contains("bgcolor"), "{}", out.html); + assert!(out.colours_changed); +} + +#[test] +fn borders_take_the_rule_colour() { + let out = dark( + "
x
", + ); + 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( + "Buy now", + ); + 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 { + 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 { + 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::()), 1..5)).prop_map(|(tag, decls)| { + let style: Vec = 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", style.join("; ")) + }), + colour_value().prop_map(|v| format!("f")), + colour_value().prop_map(|v| format!("
t
")), + 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::(), g in any::(), b in any::()) { + let from = Rgb { r, g, b }; + let out = dark(&format!("

x

")); + 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); + } +}