Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
258 changes: 233 additions & 25 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/defguard_mail/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ humantime.workspace = true
image = "0.25" # match with qrforge
mrml = "5.1"
qrforge = {version = "0.1", default-features = false, features = ["image"]}
css-inline = "0.20.2"

[dev-dependencies]
claims.workspace = true
110 changes: 106 additions & 4 deletions crates/defguard_mail/src/templates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use defguard_common::{
db::models::{Session, Settings, user::MFAMethod},
types::UrlParseError,
};
use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd, html};
use reqwest::Url;
use serde::Serialize;
use serde_json::Value;
Expand Down Expand Up @@ -191,6 +192,110 @@ pub async fn desktop_start_mail(
Ok(())
}

/// Iterator that enforces the supported subset of CommonMark
/// so that only elements with a corresponding rule in `MARKDOWN_EMAIL_STYLES`
/// are emitted to the HTML renderer.
struct EmailEventFilter<'a, I: Iterator<Item = Event<'a>>> {
iter: I,
skip_depth: usize,
}

impl<'a, I: Iterator<Item = Event<'a>>> EmailEventFilter<'a, I> {
fn new(iter: I) -> Self {
Self {
iter,
skip_depth: 0,
}
}
}

impl<'a, I: Iterator<Item = Event<'a>>> Iterator for EmailEventFilter<'a, I> {
type Item = Event<'a>;

fn next(&mut self) -> Option<Self::Item> {
loop {
let event = self.iter.next()?;

// Inside a skipped block: track nesting depth and discard.
if self.skip_depth > 0 {
match &event {
Event::Start(_) => self.skip_depth += 1,
Event::End(_) => self.skip_depth -= 1,
_ => {}
}
continue;
}

return Some(match event {
// block elements without styles: skip entirely
Event::Start(Tag::BlockQuote(_) | Tag::List(Some(_)) | Tag::CodeBlock(_)) => {
self.skip_depth = 1;
continue;
}

// inline elements without styles: drop the tag, keep text
Event::Start(Tag::Emphasis | Tag::Strikethrough)
| Event::End(TagEnd::Emphasis | TagEnd::Strikethrough) => continue,

// inline code: render as plain text
Event::Code(text) => Event::Text(text),

// headings: degrade h3-h6 to h2
Event::Start(Tag::Heading {
level,
id,
classes,
attrs,
}) if !matches!(level, HeadingLevel::H1 | HeadingLevel::H2) => {
Event::Start(Tag::Heading {
level: HeadingLevel::H2,
id,
classes,
attrs,
})
}
Event::End(TagEnd::Heading(level))
if !matches!(level, HeadingLevel::H1 | HeadingLevel::H2) =>
{
Event::End(TagEnd::Heading(HeadingLevel::H2))
}

// raw HTML and horizontal rules: strip
Event::Html(_) | Event::InlineHtml(_) | Event::Rule => continue,

other => other,
});
}
}
}

static MARKDOWN_EMAIL_STYLES: &str = r#"
h1 { font-size: 24px; font-weight: 600; color: #141517; line-height: 32px; font-family: Geist, Arial, sans-serif; margin: 0 0 8px 0; }
h2 { font-size: 16px; font-weight: 400; color: #4A5059; line-height: 24px; font-family: Geist, Arial, sans-serif; margin: 0 0 8px 0; }
p { font-size: 14px; font-weight: 400; color: #4A5059; line-height: 20px; font-family: Geist, Arial, sans-serif; margin: 0 0 12px 0; }
a { color: #3961DB; text-decoration: underline; font-size: 14px; line-height: 20px; }
ul { list-style: disc; margin: 0 0 12px 0; padding: 0; }
li { font-size: 14px; font-weight: 400; color: #4A5059; line-height: 20px; font-family: Geist, Arial, sans-serif; margin-left: 21px; }
strong, b { font-weight: 600; }
"#;

/// Renders a markdown string to an inline-styled HTML fragment.
/// Only elements with a corresponding rule in `MARKDOWN_EMAIL_STYLES` are
/// rendered; everything else is stripped or degraded (see `EmailEventFilter`).
pub fn markdown_to_html(content: &str) -> String {
let parser = EmailEventFilter::new(Parser::new(content));
let mut raw_html = String::new();
html::push_html(&mut raw_html, parser);

match css_inline::inline_fragment(&raw_html, MARKDOWN_EMAIL_STYLES) {
Ok(styled) => styled,
Err(err) => {
warn!("Failed to apply inline styles to markdown HTML: {err}");
raw_html
}
}
}

/// Welcome message sent when activating an account through enrollment.
/// Its content is stored in markdown, so it's parsed into HTML and plain text.
pub fn enrollment_welcome_mail(
Expand All @@ -203,10 +308,7 @@ pub fn enrollment_welcome_mail(
get_base_tera_mjml(Context::new(), None, ip_address, device_info)?;

debug!("Render welcome mail template for user enrollment");
// Convert content to HTML.
let parser = pulldown_cmark::Parser::new(content);
let mut html_output = String::new();
pulldown_cmark::html::push_html(&mut html_output, parser);
let html_output = markdown_to_html(content);

context.insert("welcome_message_content", &html_output);

Expand Down
254 changes: 254 additions & 0 deletions crates/defguard_mail/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,260 @@ fn send_enrollment_welcome_mail(_: PgPoolOptions, options: PgConnectOptions) {
tokio::time::sleep(Duration::from_secs(2)).await;
}

mod markdown_to_html {
use crate::templates::markdown_to_html;

fn has_tag(html: &str, tag: &str) -> bool {
html.contains(&format!("<{tag}"))
}

#[test]
fn h1_has_inline_style() {
let html = markdown_to_html("# Title");
assert!(has_tag(&html, "h1"), "h1 tag missing: {html}");
assert!(html.contains("font-size: 24px"), "h1 font-size: {html}");
assert!(html.contains("#141517"), "h1 color: {html}");
assert!(html.contains("font-weight: 600"), "h1 font-weight: {html}");
assert!(html.contains("Title"), "h1 text missing: {html}");
}

#[test]
fn h2_has_inline_style() {
let html = markdown_to_html("## Subtitle");
assert!(has_tag(&html, "h2"), "h2 tag missing: {html}");
assert!(html.contains("font-size: 16px"), "h2 font-size: {html}");
assert!(html.contains("#4A5059"), "h2 color: {html}");
assert!(html.contains("Subtitle"), "h2 text missing: {html}");
}

#[test]
fn paragraph_has_inline_style() {
let html = markdown_to_html("Hello world");
assert!(has_tag(&html, "p"), "p tag missing: {html}");
assert!(html.contains("font-size: 14px"), "p font-size: {html}");
assert!(html.contains("#4A5059"), "p color: {html}");
assert!(html.contains("Hello world"), "p text missing: {html}");
}

#[test]
fn bold_has_inline_style() {
let html = markdown_to_html("**important**");
assert!(has_tag(&html, "strong"), "strong tag missing: {html}");
assert!(
html.contains("font-weight: 600"),
"strong font-weight: {html}"
);
assert!(html.contains("important"), "bold text missing: {html}");
}

#[test]
fn link_has_inline_style_and_href() {
let html = markdown_to_html("[click here](https://example.com)");
assert!(has_tag(&html, "a"), "a tag missing: {html}");
assert!(html.contains("https://example.com"), "href missing: {html}");
assert!(html.contains("#3961DB"), "a color: {html}");
assert!(html.contains("click here"), "link text missing: {html}");
}

#[test]
fn unordered_list_has_inline_styles() {
let html = markdown_to_html("- Alpha\n- Beta");
assert!(has_tag(&html, "ul"), "ul tag missing: {html}");
assert!(has_tag(&html, "li"), "li tag missing: {html}");
assert!(html.contains("Alpha"), "first item text missing: {html}");
assert!(html.contains("Beta"), "second item text missing: {html}");
assert!(html.contains("font-size: 14px"), "li font-size: {html}");
}

#[test]
fn h3_through_h6_are_demoted_to_h2() {
for (level, marker) in [(3, "###"), (4, "####"), (5, "#####"), (6, "######")] {
let html = markdown_to_html(&format!("{marker} Heading {level}"));
assert!(
has_tag(&html, "h2"),
"h{level} must be demoted to h2: {html}"
);
assert!(
!has_tag(&html, &format!("h{level}")),
"h{level} must not appear: {html}"
);
assert!(
html.contains(&format!("Heading {level}")),
"h{level} text must be preserved: {html}"
);
}
}

#[test]
fn horizontal_rule_is_stripped() {
let html = markdown_to_html("---");
assert!(!has_tag(&html, "hr"), "hr must be stripped: {html}");
}

#[test]
fn blockquote_is_stripped() {
let html = markdown_to_html("> confidential");
assert!(
!has_tag(&html, "blockquote"),
"blockquote tag must be stripped: {html}"
);
assert!(
!html.contains("confidential"),
"blockquote content must not appear: {html}"
);
}

#[test]
fn ordered_list_is_stripped() {
let html = markdown_to_html("1. First\n2. Second");
assert!(!has_tag(&html, "ol"), "ol tag must be stripped: {html}");
assert!(
!html.contains("First"),
"ordered list content must not appear: {html}"
);
}

#[test]
fn fenced_code_block_is_stripped() {
let html = markdown_to_html("```rust\nlet x = 1;\n```");
assert!(!has_tag(&html, "pre"), "pre tag must be stripped: {html}");
assert!(!has_tag(&html, "code"), "code tag must be stripped: {html}");
assert!(
!html.contains("let x"),
"code block content must not appear: {html}"
);
}

#[test]
fn indented_code_block_is_stripped() {
let html = markdown_to_html(" indented block");
assert!(!has_tag(&html, "pre"), "pre tag must be stripped: {html}");
assert!(
!html.contains("indented block"),
"indented code block content must not appear: {html}"
);
}

#[test]
fn inline_code_rendered_as_plain_text() {
let html = markdown_to_html("`fn main()`");
assert!(!has_tag(&html, "code"), "code tag must be stripped: {html}");
assert!(
html.contains("fn main()"),
"inline code text must be preserved: {html}"
);
}

#[test]
fn raw_block_html_is_stripped() {
let html = markdown_to_html("<div class=\"x\">content</div>");
assert!(
!html.contains("<div"),
"raw HTML div must be stripped: {html}"
);
}

#[test]
fn script_tag_is_stripped() {
// <script> opens an HTML block consuming its whole line, so "Safe paragraph"
// must be in a separate paragraph to survive stripping.
let html = markdown_to_html("<script>alert('xss')</script>\n\nSafe paragraph.");
assert!(
!html.contains("<script"),
"script tag must be stripped: {html}"
);
assert!(
html.contains("Safe paragraph"),
"surrounding text must survive: {html}"
);
}

#[test]
fn inline_html_is_stripped() {
let html = markdown_to_html("before <b>inline</b> after");
assert!(
!html.contains("<b>"),
"inline HTML b tag must be stripped: {html}"
);
}

#[test]
fn nested_unsupported_blocks_are_fully_stripped() {
let html = markdown_to_html("> 1. nested item");
assert!(
!has_tag(&html, "blockquote"),
"blockquote must be stripped: {html}"
);
assert!(!has_tag(&html, "ol"), "ol must be stripped: {html}");
assert!(
!html.contains("nested item"),
"nested content must not appear: {html}"
);
}

#[test]
fn bold_and_italic_in_same_paragraph() {
let html = markdown_to_html("**bold** and *italic* together");
assert!(has_tag(&html, "strong"), "strong must be present: {html}");
assert!(!has_tag(&html, "em"), "em must be stripped: {html}");
assert!(html.contains("bold"), "bold text must survive: {html}");
assert!(html.contains("italic"), "italic text must survive: {html}");
}

#[test]
fn bold_inside_link() {
let html = markdown_to_html("[**bold link**](https://example.com)");
assert!(has_tag(&html, "a"), "a tag missing: {html}");
assert!(has_tag(&html, "strong"), "strong inside a missing: {html}");
assert!(html.contains("https://example.com"), "href missing: {html}");
assert!(html.contains("bold link"), "link text missing: {html}");
}

#[test]
fn multiple_paragraphs_are_each_styled() {
let html = markdown_to_html("First paragraph.\n\nSecond paragraph.");
assert!(
html.matches("<p").count() >= 2,
"expected at least two p tags: {html}"
);
assert!(html.contains("First paragraph"), "first p text: {html}");
assert!(html.contains("Second paragraph"), "second p text: {html}");
}

#[test]
fn hr_surrounded_by_paragraphs_is_stripped() {
let html = markdown_to_html("Before.\n\n---\n\nAfter.");
assert!(!has_tag(&html, "hr"), "hr must be stripped: {html}");
assert!(
html.contains("Before"),
"text before hr must survive: {html}"
);
assert!(html.contains("After"), "text after hr must survive: {html}");
}

#[test]
fn empty_input_produces_no_tags() {
let html = markdown_to_html("");
assert!(
html.trim().is_empty(),
"empty input must produce no output: {html}"
);
}

#[test]
fn plain_text_is_wrapped_in_paragraph() {
let html = markdown_to_html("Just some text.");
assert!(
has_tag(&html, "p"),
"plain text must be wrapped in p: {html}"
);
assert!(
html.contains("Just some text"),
"text must be preserved: {html}"
);
}
}

#[test]
fn test_mfa_configured_subject_totp() {
// TOTP
Expand Down
Loading
Loading