diff --git a/README.md b/README.md new file mode 100644 index 0000000..15d3df8 --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# epistula-core + +The public core of **Epistula Domi**, the Domi family mail client: MIME parsing and composing, reply / reply all / +forward drafts, safe attachment names, conversation threading, incoming rules (with a Sieve export), the HTML +sanitiser and the search query parser. + +Pure Rust: no I/O, no clock, no randomness, no network. Every byte of incoming mail is treated as hostile. +The tests in `tests/` are the specification: `cargo test`. + +Licence: MPL-2.0. diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/src/compose.rs b/src/compose.rs index 61dd9a1..5722395 100644 --- a/src/compose.rs +++ b/src/compose.rs @@ -1,13 +1,25 @@ //! Composing outgoing mail (mail-builder), and the drafts for reply, reply all and forward. +//! +//! Pure: the caller gives the Message-ID and the date. MIME boundaries are derived from the Message-ID, so the +//! same draft always gives the same bytes. +use crate::sanitize::{InlineImage, SanitizeOptions, sanitize, text_to_html}; use crate::{Address, Parsed}; +use mail_builder::MessageBuilder; +use mail_builder::headers::address::Address as MbAddress; +use mail_builder::headers::content_type::ContentType; +use mail_builder::headers::message_id::MessageId; +use mail_builder::mime::MimePart; use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct Draft { pub from: Address, pub to: Vec
, pub cc: Vec
, + /// Never written into the message: the SMTP envelope only. pub bcc: Vec
, pub subject: String, /// Line endings are `\n`. @@ -49,22 +61,216 @@ pub enum ReplyMode { /// A Message-ID from 16 random bytes the caller supplies and the sender's domain, without brackets. pub fn message_id(random: [u8; 16], domain: &str) -> String { - let _ = (random, domain); - todo!() + let hex: String = random.iter().map(|b| format!("{b:02x}")).collect(); + let domain: String = domain.chars().filter(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-')).collect(); + let domain = domain.trim_matches(['.', '-']); + format!("{hex}@{}", if domain.is_empty() { "localhost" } else { domain }) +} + +fn crlf(s: &str) -> String { + crate::mime::normalize_newlines(s).replace('\n', "\r\n") +} + +fn mb_address(a: &Address) -> MbAddress<'_> { + MbAddress::new_address(a.name.as_deref(), a.email.as_str()) +} + +fn mb_list(list: &[Address]) -> MbAddress<'_> { + MbAddress::new_list(list.iter().map(mb_address).collect()) +} + +fn boundary(message_id: &str, kind: &str) -> String { + let mut h = std::collections::hash_map::DefaultHasher::new(); + message_id.hash(&mut h); + kind.hash(&mut h); + // `=_` never occurs in base64 or quoted-printable output, so the boundary cannot collide with a body. + format!("=_ep_{kind}_{:016x}", h.finish()) } /// The RFC 5322 bytes of `draft`, with the given Message-ID (no brackets) and Date (Unix seconds). pub fn compose(draft: &Draft, message_id: &str, date: i64) -> Vec { - let _ = (draft, message_id, date); - todo!() + let text = crlf(&draft.text); + let html = draft.html.as_deref().map(crlf); + + let mut builder = MessageBuilder::new() + .from(mb_address(&draft.from)) + .subject(draft.subject.as_str()) + .message_id(message_id) + .date(date); + if !draft.to.is_empty() { + builder = builder.to(mb_list(&draft.to)); + } + if !draft.cc.is_empty() { + builder = builder.cc(mb_list(&draft.cc)); + } + if let Some(parent) = draft.in_reply_to.as_deref() { + builder = builder.in_reply_to(parent); + } + if !draft.references.is_empty() { + builder = builder.references(MessageId::new_list(draft.references.iter().map(String::as_str))); + } + + let text_part = MimePart::new("text/plain", text); + let body = match html { + Some(html) => MimePart::new( + ContentType::new("multipart/alternative").attribute("boundary", boundary(message_id, "alt")), + vec![text_part, MimePart::new("text/html", html)], + ), + None => text_part, + }; + let body = if draft.attachments.is_empty() { + body + } else { + let mut parts = vec![body]; + for a in &draft.attachments { + parts.push( + MimePart::new(ContentType::new(a.content_type.as_str()), a.data.as_slice()) + .attachment(a.filename.as_str()), + ); + } + MimePart::new(ContentType::new("multipart/mixed").attribute("boundary", boundary(message_id, "mixed")), parts) + }; + + builder.body(body).write_to_vec().unwrap_or_default() +} + +/// Leading `Re:` / `Fwd:` prefixes of `subject` removed, then one `prefix` added. +fn prefixed(prefix: &str, subject: &str) -> String { + let rest = crate::thread::strip_prefixes(subject).0.trim(); + format!("{prefix} {rest}").trim_end().to_string() +} + +fn dedupe(list: impl IntoIterator, exclude: &[Address]) -> Vec
{ + let mut out: Vec
= Vec::new(); + for a in list { + if !exclude.iter().any(|e| e.same_mailbox(&a)) && !out.iter().any(|o| o.same_mailbox(&a)) { + out.push(a); + } + } + out +} + +fn sender_line(original: &Parsed) -> String { + original.from.first().map(Address::display).unwrap_or_else(|| "Unknown sender".to_string()) +} + +fn quote_text(text: &str) -> String { + text.trim_end() + .split('\n') + .map(|line| if line.is_empty() { ">".to_string() } else { format!("> {line}") }) + .collect::>() + .join("\n") +} + +fn escape(s: &str) -> String { + s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """) +} + +/// The original's HTML (or text) made safe for the composer, inline images embedded. +fn original_html(original: &Parsed) -> String { + let inline_images: HashMap> = original + .attachments + .iter() + .filter_map(|a| { + a.content_id.clone().map(|cid| (cid, InlineImage { content_type: &a.content_type, data: &a.data })) + }) + .collect(); + match &original.html { + Some(html) => sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images }).html, + None => text_to_html(original.text.as_deref().unwrap_or("")), + } } pub fn reply(original: &Parsed, me: &Address, mode: ReplyMode) -> Draft { - let _ = (original, me, mode); - todo!() + let mine = original.from.iter().any(|a| a.same_mailbox(me)); + let primary = if mine { + original.to.clone() + } else if !original.reply_to.is_empty() { + original.reply_to.clone() + } else { + original.from.clone() + }; + let to = dedupe(primary, if mine { &[] } else { std::slice::from_ref(me) }); + let cc = match mode { + ReplyMode::Sender => Vec::new(), + ReplyMode::All => { + let mut exclude = to.clone(); + exclude.push(me.clone()); + dedupe(original.to.iter().chain(original.cc.iter()).cloned(), &exclude) + } + }; + + let attribution = match &original.date_text { + Some(date) => format!("On {date}, {} wrote:", sender_line(original)), + None => format!("{} wrote:", sender_line(original)), + }; + let text = format!("\n\n{attribution}\n{}\n", quote_text(original.text.as_deref().unwrap_or(""))); + let html = format!( + "


{}

{}
", + escape(&attribution), + original_html(original) + ); + + let mut references = original.references.clone(); + if let Some(id) = &original.message_id { + if !references.contains(id) { + references.push(id.clone()); + } + } + + Draft { + from: me.clone(), + to, + cc, + bcc: Vec::new(), + subject: prefixed("Re:", &original.subject), + text, + html: Some(html), + attachments: Vec::new(), + in_reply_to: original.message_id.clone(), + references, + } } pub fn forward(original: &Parsed, me: &Address) -> Draft { - let _ = (original, me); - todo!() + let list = |l: &[Address]| l.iter().map(Address::display).collect::>().join(", "); + let mut header = vec![format!("From: {}", sender_line(original))]; + if let Some(date) = &original.date_text { + header.push(format!("Date: {date}")); + } + header.push(format!("Subject: {}", original.subject)); + if !original.to.is_empty() { + header.push(format!("To: {}", list(&original.to))); + } + if !original.cc.is_empty() { + header.push(format!("Cc: {}", list(&original.cc))); + } + + let text = format!( + "\n\n---------- Forwarded message ----------\n{}\n\n{}\n", + header.join("\n"), + original.text.as_deref().unwrap_or("").trim_end() + ); + let html = format!( + "


---------- Forwarded message ----------
{}

{}", + header.iter().map(|h| escape(h)).collect::>().join("
"), + original_html(original) + ); + + Draft { + from: me.clone(), + subject: prefixed("Fwd:", &original.subject), + text, + html: Some(html), + attachments: original + .attachments + .iter() + .map(|a| OutAttachment { + filename: a.filename.clone(), + content_type: a.content_type.clone(), + data: a.data.clone(), + }) + .collect(), + ..Default::default() + } } diff --git a/src/filename.rs b/src/filename.rs index f360f45..4ebf952 100644 --- a/src/filename.rs +++ b/src/filename.rs @@ -3,8 +3,84 @@ /// The longest name kept, in characters (the extension is kept when cutting). pub const MAX_FILENAME_CHARS: usize = 120; +const FALLBACK: &str = "attachment"; + +fn is_bidi_or_invisible(c: char) -> bool { + matches!(c, + '\u{200B}'..='\u{200F}' // zero width, LRM, RLM + | '\u{061C}' // Arabic letter mark + | '\u{202A}'..='\u{202E}' // embeddings and overrides + | '\u{2066}'..='\u{2069}' // isolates + | '\u{FEFF}') +} + +fn is_reserved_windows_name(stem: &str) -> bool { + let upper = stem.trim_end_matches([' ', '.']).to_ascii_uppercase(); + match upper.as_str() { + "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$" => true, + s if s.len() == 4 && (s.starts_with("COM") || s.starts_with("LPT")) => s.as_bytes()[3].is_ascii_digit(), + // COM¹ COM² COM³ LPT¹ … (Windows reserves the superscript digits too) + s if (s.starts_with("COM") || s.starts_with("LPT")) && s.chars().count() == 4 => { + matches!(s.chars().nth(3), Some('¹' | '²' | '³')) + } + _ => false, + } +} + /// A name that is safe to create in any directory on Windows, Android and iOS, and that shows what it is. pub fn safe_filename(raw: &str) -> String { - let _ = raw; - todo!() + // Only the last path component, whatever the separator. + let last = raw.rsplit(['/', '\\']).next().unwrap_or(""); + // A drive prefix like `C:` that had no separator after it. + let last = match last.find(':') { + Some(i) if i == 1 => &last[2..], + _ => last, + }; + + let mut name: String = last + .chars() + .filter(|c| !c.is_control() && !is_bidi_or_invisible(*c)) + .map(|c| match c { + '<' | '>' | ':' | '"' | '|' | '?' | '*' => '_', + c => c, + }) + .collect(); + + // No leading dots (hidden files, `..`), no trailing dots or spaces (Windows strips them). + name = name.trim_start_matches(['.', ' ']).trim_end_matches(['.', ' ']).to_string(); + // `..` inside a name is harmless as a path once separators are gone, but never keep the sequence. + while name.contains("..") { + name = name.replace("..", "."); + } + if name.is_empty() { + return FALLBACK.to_string(); + } + + let stem = name.split('.').next().unwrap_or(""); + if is_reserved_windows_name(stem) { + name.insert(0, '_'); + } + + cut(&name) +} + +/// Cut to `MAX_FILENAME_CHARS`, keeping a short extension. +fn cut(name: &str) -> String { + let count = name.chars().count(); + if count <= MAX_FILENAME_CHARS { + return name.to_string(); + } + let ext = match name.rfind('.') { + Some(i) if name[i..].chars().count() <= 16 && i > 0 => &name[i..], + _ => "", + }; + let keep = MAX_FILENAME_CHARS - ext.chars().count(); + let stem: String = name.chars().take(keep).collect(); + let stem = stem.trim_end_matches(['.', ' ']); + let mut out = format!("{stem}{ext}"); + // Trimming can make it shorter; pad is not needed, but never return something ending in a dot. + while out.ends_with(['.', ' ']) { + out.pop(); + } + if out.is_empty() { FALLBACK.to_string() } else { out } } diff --git a/src/mime.rs b/src/mime.rs index 0352c1d..16a6fea 100644 --- a/src/mime.rs +++ b/src/mime.rs @@ -1,6 +1,7 @@ //! Parsing a raw RFC 5322 message (mail-parser) into what the app stores and shows. -use crate::Address; +use crate::{Address, safe_filename}; +use mail_parser::{MessageParser, MessagePart, PartKind}; use serde::{Deserialize, Serialize}; /// Larger messages are refused before parsing (Proton's own limit is 25 MB of attachments). @@ -81,7 +82,132 @@ impl std::fmt::Display for ParseError { impl std::error::Error for ParseError {} +/// At most this many Message-IDs are kept from In-Reply-To and References. +pub const MAX_REFERENCES: usize = 100; + pub fn parse(raw: &[u8]) -> Result { - let _ = raw; - todo!() + if raw.len() > MAX_MESSAGE_BYTES { + return Err(ParseError::TooLarge); + } + if raw.iter().all(u8::is_ascii_whitespace) { + return Err(ParseError::NotMail); + } + let message = MessageParser::new().parse(raw).ok_or(ParseError::NotMail)?; + + let subject: String = + message.subject().unwrap_or("").chars().filter(|c| !c.is_control()).take(MAX_SUBJECT_CHARS).collect(); + + let text = join_bodies(message.text_body().filter_map(|part| part.text())); + // mail-parser converts a text-only message to HTML; the app renders text itself, so keep real HTML only. + let html = join_bodies( + message.html_body().filter(|part| matches!(part.kind(), PartKind::Html)).filter_map(|part| part.text()), + ); + + let mut attachments = Vec::new(); + let mut dropped_attachments = 0; + for part in message.attachments() { + if attachments.len() >= MAX_ATTACHMENTS { + dropped_attachments += 1; + continue; + } + attachments.push(attachment(&part)); + } + + Ok(Parsed { + message_id: message.message_id().map(clean_id).filter(|id| !id.is_empty()), + in_reply_to: ids(message.in_reply_to()), + references: ids(message.references()), + subject: subject.trim().to_string(), + from: addresses(message.from()), + to: addresses(message.to()), + cc: addresses(message.cc()), + reply_to: addresses(message.reply_to()), + date: message.date().map(|d| d.to_timestamp()), + date_text: message.date().map(|d| d.to_rfc822()), + text, + html, + attachments, + dropped_attachments, + }) +} + +fn join_bodies<'a>(parts: impl Iterator>) -> Option { + let mut out = String::new(); + for part in parts { + if !out.is_empty() { + out.push('\n'); + } + out.push_str(&part); + } + if out.is_empty() { None } else { Some(normalize_newlines(&out)) } +} + +pub(crate) fn normalize_newlines(s: &str) -> String { + s.replace("\r\n", "\n").replace('\r', "\n") +} + +fn clean_id(id: &str) -> String { + id.trim().trim_start_matches('<').trim_end_matches('>').trim().chars().take(998).collect() +} + +fn ids(list: Option>) -> Vec { + let mut out: Vec = Vec::new(); + for id in list.iter().flat_map(|l| l.iter()) { + let id = clean_id(id); + if !id.is_empty() && !out.contains(&id) && out.len() < MAX_REFERENCES { + out.push(id); + } + } + out +} + +fn addresses(list: Option>) -> Vec
{ + list.iter() + .flat_map(|l| l.mailboxes()) + .filter_map(|m| { + let email = m.address()?.trim(); + if email.is_empty() { + return None; + } + let name = m.name().map(|n| n.chars().filter(|c| !c.is_control()).collect::()); + Some(Address::new(name.as_deref(), email)) + }) + .take(MAX_ADDRESSES) + .collect() +} + +fn attachment(part: &MessagePart<'_>) -> Attachment { + let content_type = part + .content_type() + .map(|ct| match ct.subtype() { + Some(sub) => format!("{}/{}", ct.ctype(), sub), + None => ct.ctype().to_string(), + }) + .map(|ct| ct.to_ascii_lowercase()) + .filter(|ct| ct.len() <= 127 && ct.chars().all(|c| c.is_ascii_graphic())) + .unwrap_or_else(|| "application/octet-stream".to_string()); + + let content_id = part.content_id().map(clean_id).filter(|id| !id.is_empty()); + let declared_attachment = part.content_disposition().is_some_and(|d| d.is_attachment()); + let inline = content_id.is_some() && !declared_attachment; + + let (name, data) = match part.kind() { + PartKind::Message(nested) => { + let name = part + .attachment_name() + .map(str::to_owned) + .unwrap_or_else(|| format!("{}.eml", nested.subject().unwrap_or("message"))); + let name = if name.to_ascii_lowercase().ends_with(".eml") { name } else { format!("{name}.eml") }; + (name, part.decoded().into_owned()) + } + _ => { + let name = part.attachment_name().map(str::to_owned).unwrap_or_else(|| { + let ext = content_type.rsplit('/').next().unwrap_or("bin"); + format!("attachment.{ext}") + }); + (name, part.decoded().into_owned()) + } + }; + + Attachment { filename: safe_filename(&name), content_type, content_id, inline, data } } diff --git a/src/rules.rs b/src/rules.rs index f92f8b3..8127127 100644 --- a/src/rules.rs +++ b/src/rules.rs @@ -50,13 +50,26 @@ pub enum RuleError { impl Rule { /// A rule with no condition, an empty text or no folder would match everything or nothing. pub fn validate(&self) -> Result<(), RuleError> { - todo!() + if self.conditions.is_empty() { + return Err(RuleError::NoConditions); + } + if self.conditions.iter().any(|c| c.contains.trim().is_empty()) { + return Err(RuleError::EmptyText); + } + if self.folder.trim().is_empty() { + return Err(RuleError::NoFolder); + } + Ok(()) } /// The rule "Rule from this mail": sender address -> folder. pub fn from_sender(sender: &Address, folder: &str) -> Rule { - let _ = (sender, folder); - todo!() + let email = sender.email.trim().to_lowercase(); + Rule { + name: format!("From {email}"), + conditions: vec![Condition { field: Field::From, contains: email }], + folder: folder.trim().to_string(), + } } } @@ -70,12 +83,52 @@ pub struct RuleMessage<'a> { /// The first valid rule whose conditions all hold, or `None` (the message stays where it is). pub fn first_match<'r>(rules: &'r [Rule], message: &RuleMessage<'_>) -> Option<&'r Rule> { - let _ = (rules, message); - todo!() + rules.iter().find(|rule| rule.validate().is_ok() && rule.conditions.iter().all(|c| holds(c, message))) +} + +fn holds(condition: &Condition, message: &RuleMessage<'_>) -> bool { + let needle = condition.contains.trim().to_lowercase(); + let any = |list: &[Address]| list.iter().any(|a| a.display().to_lowercase().contains(&needle)); + match condition.field { + Field::From => any(message.from), + Field::To => any(message.to) || any(message.cc), + Field::Subject => message.subject.to_lowercase().contains(&needle), + } +} + +fn sieve_string(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars().filter(|c| !c.is_control()) { + if c == '"' || c == '\\' { + out.push('\\'); + } + out.push(c); + } + out.push('"'); + out +} + +fn sieve_test(condition: &Condition) -> String { + let header = match condition.field { + Field::From => "\"from\"", + Field::To => "[\"to\", \"cc\"]", + Field::Subject => "\"subject\"", + }; + format!("header :contains :comparator \"i;unicode-casemap\" {header} {}", sieve_string(condition.contains.trim())) } /// The same rules as a Sieve script (RFC 5228 + fileinto + RFC 5051 unicode-casemap). pub fn to_sieve(rules: &[Rule]) -> String { - let _ = rules; - todo!() + let mut out = String::from("require [\"fileinto\", \"comparator-i;unicode-casemap\"];\n"); + for rule in rules.iter().filter(|r| r.validate().is_ok()) { + let name: String = rule.name.chars().filter(|c| !c.is_control()).collect(); + let tests: Vec = rule.conditions.iter().map(sieve_test).collect(); + let test = if tests.len() == 1 { tests[0].clone() } else { format!("allof({})", tests.join(", ")) }; + out.push_str(&format!( + "\n# {name}\nif {test} {{\n fileinto {};\n stop;\n}}\n", + sieve_string(rule.folder.trim()) + )); + } + out } diff --git a/src/sanitize.rs b/src/sanitize.rs index 146acd4..484bc58 100644 --- a/src/sanitize.rs +++ b/src/sanitize.rs @@ -1,8 +1,16 @@ //! HTML from mail -> HTML the reader may show. Allow-list (ammonia): no scripts, no event handlers, no forms, //! no `javascript:` or `data:text/html` URLs, no CSS that runs or loads anything, remote images replaced by a //! placeholder unless the user chose "Load images" for this message. +//! +//! Defence in depth after ammonia: in text and attribute values `:` and `=` are written as `:` and `=`. +//! A browser shows and follows exactly the same thing, but the output can never contain the literal sequences +//! `javascript:` or ` onclick=`, whatever a later bug in a filter lets through. -use std::collections::HashMap; +use base64::Engine; +use std::borrow::Cow; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; /// What an inline `cid:` image resolves to. pub struct InlineImage<'a> { @@ -28,13 +36,404 @@ pub struct Sanitized { /// The placeholder for a blocked remote image (a small grey square, SVG in a data URI: no script runs in ``). pub const BLOCKED_IMAGE_SRC: &str = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNDQ0Ii8+PC9zdmc+"; +/// Inline images larger than this are not embedded (they stay attachments). +pub const MAX_INLINE_IMAGE_BYTES: usize = 10 * 1024 * 1024; + +const TAGS: &[&str] = &[ + "a", + "abbr", + "address", + "b", + "bdi", + "bdo", + "big", + "blockquote", + "br", + "caption", + "center", + "cite", + "code", + "col", + "colgroup", + "dd", + "del", + "dfn", + "div", + "dl", + "dt", + "em", + "font", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "hr", + "i", + "img", + "ins", + "kbd", + "li", + "mark", + "ol", + "p", + "pre", + "q", + "s", + "samp", + "small", + "span", + "strike", + "strong", + "sub", + "sup", + "table", + "tbody", + "td", + "tfoot", + "th", + "thead", + "tr", + "tt", + "u", + "ul", + "var", + "wbr", +]; + +/// Removed with everything inside them. +const CLEAN_CONTENT: &[&str] = &[ + "script", + "style", + "template", + "noscript", + "title", + "svg", + "math", + "iframe", + "object", + "embed", + "textarea", + "select", + "applet", + "noembed", + "noframes", + "xmp", + "plaintext", +]; + +const GENERIC_ATTRIBUTES: &[&str] = &["align", "dir", "lang", "style", "title"]; + +const TAG_ATTRIBUTES: &[(&str, &[&str])] = &[ + ("a", &["href", "name"]), + ("img", &["src", "alt", "width", "height", "border"]), + ("table", &["width", "height", "border", "cellpadding", "cellspacing", "bgcolor"]), + ("td", &["width", "height", "colspan", "rowspan", "valign", "bgcolor", "nowrap"]), + ("th", &["width", "height", "colspan", "rowspan", "valign", "bgcolor", "nowrap"]), + ("tr", &["valign", "bgcolor"]), + ("col", &["width", "span"]), + ("colgroup", &["width", "span"]), + ("font", &["color", "face", "size"]), + ("ol", &["start", "type"]), + ("li", &["value"]), +]; + +const CSS_PROPERTIES: &[&str] = &[ + "background", + "background-color", + "border", + "border-bottom", + "border-bottom-color", + "border-bottom-style", + "border-bottom-width", + "border-collapse", + "border-color", + "border-left", + "border-left-color", + "border-left-style", + "border-left-width", + "border-radius", + "border-right", + "border-right-color", + "border-right-style", + "border-right-width", + "border-spacing", + "border-style", + "border-top", + "border-top-color", + "border-top-style", + "border-top-width", + "border-width", + "color", + "direction", + "display", + "font", + "font-family", + "font-size", + "font-style", + "font-variant", + "font-weight", + "height", + "letter-spacing", + "line-height", + "list-style-type", + "margin", + "margin-bottom", + "margin-left", + "margin-right", + "margin-top", + "max-width", + "min-width", + "padding", + "padding-bottom", + "padding-left", + "padding-right", + "padding-top", + "table-layout", + "text-align", + "text-decoration", + "text-indent", + "text-transform", + "vertical-align", + "white-space", + "width", + "word-break", + "word-spacing", +]; + +/// A CSS value containing any of these is dropped: they run code, load something or escape the parser. +const CSS_FORBIDDEN: &[&str] = &[ + "expression", + "url", + "javascript", + "vbscript", + "import", + "behavior", + "binding", + "image-set", + "image(", + "attr(", + "var(", + "env(", + "\\", + "/*", + "*/", + "<", + ">", + "\"", + "'", + "&", + "@", + "{", + "}", +]; + +const RASTER_DATA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/jpg", "image/gif", "image/webp", "image/bmp"]; + pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized { - let _ = (html, options); - todo!() + let blocked = Arc::new(AtomicUsize::new(0)); + let inline: Arc> = Arc::new( + options + .inline_images + .iter() + .filter(|(_, img)| { + RASTER_DATA_TYPES.contains(&img.content_type.to_ascii_lowercase().as_str()) + && img.data.len() <= MAX_INLINE_IMAGE_BYTES + }) + .map(|(cid, img)| { + let uri = format!( + "data:{};base64,{}", + img.content_type.to_ascii_lowercase(), + base64::engine::general_purpose::STANDARD.encode(img.data) + ); + (cid.trim().trim_matches(['<', '>']).to_ascii_lowercase(), uri) + }) + .collect(), + ); + let load_remote = options.load_remote_images; + + let mut builder = ammonia::Builder::empty(); + builder + .tags(TAGS.iter().copied().collect::>()) + .clean_content_tags(CLEAN_CONTENT.iter().copied().collect::>()) + .generic_attributes(GENERIC_ATTRIBUTES.iter().copied().collect::>()) + .tag_attributes( + TAG_ATTRIBUTES + .iter() + .map(|(tag, attrs)| (*tag, attrs.iter().copied().collect::>())) + .collect::>(), + ) + .url_schemes(["http", "https", "mailto", "data", "cid"].into_iter().collect::>()) + .url_relative(ammonia::UrlRelative::Deny) + .link_rel(Some("noopener noreferrer")) + .strip_comments(true) + .id_prefix(None); + { + let blocked = blocked.clone(); + builder.attribute_filter(move |element, attribute, value| { + filter_attribute(element, attribute, value, load_remote, &inline, &blocked) + }); + } + let cleaned = builder.clean(html).to_string(); + Sanitized { html: escape_punctuation(&cleaned), blocked_images: blocked.load(Ordering::Relaxed) } } -/// A plain-text body as safe HTML (escaped, line breaks kept, links made clickable). -pub fn text_to_html(text: &str) -> String { - let _ = text; - todo!() +/// The scheme of a URL as a browser would read it: ASCII whitespace and controls removed, lower case. +fn scheme_of(value: &str) -> String { + let compact: String = value.chars().filter(|c| !c.is_ascii_whitespace() && !c.is_control()).collect(); + compact.to_ascii_lowercase() +} + +fn filter_attribute<'u>( + element: &str, + attribute: &str, + value: &'u str, + load_remote: bool, + inline: &HashMap, + blocked: &AtomicUsize, +) -> Option> { + match (element, attribute) { + ("img", "src") => { + let url = scheme_of(value); + if let Some(cid) = url.strip_prefix("cid:") { + return inline.get(cid).map(|uri| Cow::Owned(uri.clone())); + } + if let Some(rest) = url.strip_prefix("data:") { + let media = rest.split([';', ',']).next().unwrap_or(""); + let base64 = rest.split(',').next().unwrap_or("").ends_with(";base64"); + return (RASTER_DATA_TYPES.contains(&media) && base64).then_some(Cow::Borrowed(value)); + } + if url.starts_with("https:") || url.starts_with("http:") { + if load_remote { + return Some(Cow::Borrowed(value)); + } + blocked.fetch_add(1, Ordering::Relaxed); + return Some(Cow::Borrowed(BLOCKED_IMAGE_SRC)); + } + None + } + ("a", "href") => { + let url = scheme_of(value); + (url.starts_with("https:") || url.starts_with("http:") || url.starts_with("mailto:")) + .then_some(Cow::Borrowed(value)) + } + (_, "style") => filter_css(value).map(Cow::Owned), + _ => Some(Cow::Borrowed(value)), + } +} + +/// Keeps only allow-listed properties whose values cannot run or load anything. +fn filter_css(style: &str) -> Option { + let mut kept = Vec::new(); + for declaration in style.split(';') { + let Some((property, value)) = declaration.split_once(':') else { continue }; + let property = property.trim().to_ascii_lowercase(); + let value = value.trim(); + let lower = value.to_ascii_lowercase(); + if !CSS_PROPERTIES.contains(&property.as_str()) + || value.is_empty() + || value.chars().any(|c| c.is_control()) + || CSS_FORBIDDEN.iter().any(|bad| lower.contains(bad)) + { + continue; + } + kept.push(format!("{property}: {value}")); + } + (!kept.is_empty()).then(|| kept.join("; ")) +} + +/// Writes `:` and `=` in text and attribute values as character references (see the module docs). +/// The input is ammonia's serialisation: attribute values are always double-quoted and text never holds a raw `<`. +fn escape_punctuation(html: &str) -> String { + #[derive(PartialEq)] + enum State { + Text, + Tag, + Value, + } + let mut out = String::with_capacity(html.len() + html.len() / 8); + let mut state = State::Text; + for c in html.chars() { + match state { + State::Text => match c { + '<' => { + state = State::Tag; + out.push(c); + } + ':' => out.push_str(":"), + '=' => out.push_str("="), + _ => out.push(c), + }, + State::Tag => { + match c { + '"' => state = State::Value, + '>' => state = State::Text, + _ => {} + } + out.push(c); + } + State::Value => match c { + '"' => { + state = State::Tag; + out.push(c); + } + ':' => out.push_str(":"), + '=' => out.push_str("="), + _ => out.push(c), + }, + } + } + out +} + +/// A plain-text body as safe HTML (escaped, line breaks kept, `http(s)` links made clickable). +pub fn text_to_html(text: &str) -> String { + let mut html = String::with_capacity(text.len() + 64); + for (i, line) in text.split('\n').enumerate() { + if i > 0 { + html.push_str("
\n"); + } + linkify_line(line.trim_end_matches('\r'), &mut html); + } + // The same allow-list and punctuation escaping as mail HTML. + sanitize(&html, &SanitizeOptions::default()).html +} + +fn escape_text(s: &str, out: &mut String) { + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + c => out.push(c), + } + } +} + +fn linkify_line(line: &str, out: &mut String) { + let mut rest = line; + loop { + let next = ["https://", "http://"].iter().filter_map(|p| rest.to_ascii_lowercase().find(p)).min(); + let Some(start) = next else { + escape_text(rest, out); + return; + }; + escape_text(&rest[..start], out); + let tail = &rest[start..]; + let end = tail.find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"')).unwrap_or(tail.len()); + let url = tail[..end].trim_end_matches(['.', ',', ';', ':', '!', '?', ')', '\'']); + let url = if url.len() <= "https://".len() { &tail[..end] } else { url }; + if url.len() > "https://".len() { + out.push_str(""); + escape_text(url, out); + out.push_str(""); + } else { + escape_text(url, out); + } + rest = &tail[url.len()..]; + } } diff --git a/src/search.rs b/src/search.rs index 2cd748b..8d001bd 100644 --- a/src/search.rs +++ b/src/search.rs @@ -15,18 +15,132 @@ pub struct Query { /// FTS5 column names the app's search table must use. pub const FTS_COLUMNS: [&str; 5] = ["subject", "sender", "recipients", "body", "attachments"]; +/// Longer input is cut (characters): a search box, not a document. +pub const MAX_QUERY_CHARS: usize = 500; +/// At most this many terms are used. +pub const MAX_TERMS: usize = 32; + +/// Reads a `"quoted"` value (the opening quote already consumed); an unterminated quote runs to the end. +fn quoted(chars: &[char], i: &mut usize) -> String { + let mut out = String::new(); + while *i < chars.len() { + let c = chars[*i]; + *i += 1; + if c == '"' { + break; + } + out.push(c); + } + out +} + +fn word(chars: &[char], i: &mut usize) -> String { + let mut out = String::new(); + while *i < chars.len() && !chars[*i].is_whitespace() { + out.push(chars[*i]); + *i += 1; + } + out +} + pub fn parse_query(input: &str) -> Query { - let _ = input; - todo!() + let chars: Vec = input.chars().take(MAX_QUERY_CHARS).collect(); + let mut q = Query::default(); + let mut i = 0; + while i < chars.len() { + if chars[i].is_whitespace() { + i += 1; + continue; + } + if chars[i] == '"' { + i += 1; + let phrase = quoted(&chars, &mut i); + if !phrase.trim().is_empty() { + q.text.push(phrase.trim().to_string()); + } + continue; + } + let start = i; + let mut key = String::new(); + while i < chars.len() && !chars[i].is_whitespace() && chars[i] != ':' && chars[i] != '"' { + key.push(chars[i]); + i += 1; + } + let key = key.to_ascii_lowercase(); + let known = matches!(key.as_str(), "from" | "to" | "subject" | "has" | "is"); + if i < chars.len() && chars[i] == ':' && known { + i += 1; + let value = if i < chars.len() && chars[i] == '"' { + i += 1; + quoted(&chars, &mut i) + } else { + word(&chars, &mut i) + }; + let value = value.trim().to_string(); + if value.is_empty() { + continue; + } + match key.as_str() { + "from" => q.from.push(value), + "to" => q.to.push(value), + "subject" => q.subject.push(value), + "has" if matches!(value.to_ascii_lowercase().as_str(), "attachment" | "attachments") => { + q.has_attachment = true + } + "is" if matches!(value.to_ascii_lowercase().as_str(), "starred" | "flagged") => q.is_starred = true, + _ => q.text.push(format!("{key}:{value}")), + } + continue; + } + i = start; + let w = word(&chars, &mut i); + if !w.is_empty() { + q.text.push(w); + } + } + q +} + +/// One user term as an FTS5 prefix phrase: `"term"*`, inner quotes doubled. `None` for terms with no letter or +/// digit (the tokenizer would see an empty phrase). +fn phrase(term: &str) -> Option { + if !term.chars().any(char::is_alphanumeric) { + return None; + } + let clean: String = term.chars().filter(|c| !c.is_control()).collect(); + Some(format!("\"{}\"*", clean.replace('"', "\"\""))) } impl Query { pub fn is_empty(&self) -> bool { - todo!() + self.text.is_empty() + && self.from.is_empty() + && self.to.is_empty() + && self.subject.is_empty() + && !self.has_attachment + && !self.is_starred } /// The FTS5 `MATCH` expression, or `None` when there is no text to match (only flags). pub fn fts_match(&self) -> Option { - todo!() + let mut terms = Vec::new(); + let columns: [(&[String], Option<&str>); 4] = [ + (&self.from, Some("sender")), + (&self.to, Some("recipients")), + (&self.subject, Some("subject")), + (&self.text, None), + ]; + for (values, column) in columns { + for v in values { + if let Some(p) = phrase(v) { + terms.push(match column { + Some(col) => format!("{col} : {p}"), + None => p, + }); + } + } + } + terms.truncate(MAX_TERMS); + (!terms.is_empty()).then(|| terms.join(" AND ")) } } diff --git a/src/thread.rs b/src/thread.rs index 07ee5a8..4b5ab2b 100644 --- a/src/thread.rs +++ b/src/thread.rs @@ -1,4 +1,12 @@ //! Conversations: Message-ID / In-Reply-To / References, with a normalised-subject fallback. +//! +//! - Messages are joined when one names the other (In-Reply-To or References), when they share a Message-ID +//! (the same message in Inbox and Sent), or when both name the same missing message. +//! - Fallback: a message with *no* In-Reply-To and *no* References whose subject has a reply or forward prefix +//! (`Re:`, `Fwd:` …) joins the earliest message with the same normalised subject. Two unrelated mails that +//! are both called "Hello" stay apart. + +use std::collections::HashMap; /// What threading needs from one message. `id` is the app's local id. #[derive(Clone, Debug, PartialEq, Eq)] @@ -11,15 +19,137 @@ pub struct ThreadInput { pub date: i64, } +/// Reply and forward prefixes in the languages the family's mail arrives in. +const PREFIXES: &[&str] = &["re", "fwd", "fw", "aw", "wg", "odp", "sv", "vs", "tr", "rv", "antw", "fwd"]; + +/// `subject` without its leading `[tags]` and reply/forward prefixes, and whether it had such a prefix. +pub(crate) fn strip_prefixes(subject: &str) -> (&str, bool) { + let mut rest = subject.trim_start(); + let mut had_prefix = false; + loop { + let before = rest; + if rest.starts_with('[') { + if let Some(end) = rest.find(']') { + rest = rest[end + 1..].trim_start(); + } + } + for p in PREFIXES { + let Some(head) = rest.get(..p.len()) else { continue }; + if !head.eq_ignore_ascii_case(p) { + continue; + } + let mut after = &rest[p.len()..]; + // `Re[2]:` and `Re(2):` + if let Some(stripped) = after.strip_prefix(['[', '(']) { + let digits = stripped.find(|c: char| !c.is_ascii_digit()).unwrap_or(stripped.len()); + if digits > 0 && stripped[digits..].starts_with([']', ')']) { + after = &stripped[digits + 1..]; + } + } + let after = after.trim_start_matches(' '); + if let Some(after) = after.strip_prefix([':', ':']) { + rest = after.trim_start(); + had_prefix = true; + break; + } + } + if rest == before { + return (rest, had_prefix); + } + } +} + /// `Re: Fwd: [list] Hello world` -> `hello world`. pub fn normalize_subject(subject: &str) -> String { - let _ = subject; - todo!() + strip_prefixes(subject).0.split_whitespace().collect::>().join(" ").to_lowercase() +} + +struct Sets { + parent: Vec, +} + +impl Sets { + fn find(&mut self, mut x: usize) -> usize { + while self.parent[x] != x { + self.parent[x] = self.parent[self.parent[x]]; + x = self.parent[x]; + } + x + } + + fn union(&mut self, a: usize, b: usize) { + let (a, b) = (self.find(a), self.find(b)); + if a != b { + let (low, high) = if a < b { (a, b) } else { (b, a) }; + self.parent[high] = low; + } + } } /// The thread id of each input, in input order. A thread's id is the `id` of its earliest message /// (by date, then id), so the result does not depend on input order. -pub fn thread(messages: &[ThreadInput]) -> Vec { - let _ = messages; - todo!() +pub fn thread<'a>(messages: &'a [ThreadInput]) -> Vec { + let n = messages.len(); + let mut sets = Sets { parent: (0..n).collect() }; + // Message-ID -> node. An id nobody has (yet) gets a virtual node, so two replies to a missing message join. + let mut ids: HashMap<&str, usize> = HashMap::new(); + let mut lookup = |id: &'a str, sets: &mut Sets, owner: Option| -> usize { + if let Some(&k) = ids.get(id) { + return k; + } + let k = owner.unwrap_or_else(|| { + sets.parent.push(sets.parent.len()); + sets.parent.len() - 1 + }); + ids.insert(id, k); + k + }; + + for (i, m) in messages.iter().enumerate() { + if let Some(id) = m.message_id.as_deref().filter(|id| !id.is_empty()) { + let k = lookup(id, &mut sets, Some(i)); + sets.union(i, k); + } + } + for (i, m) in messages.iter().enumerate() { + for id in m.in_reply_to.iter().chain(m.references.iter()).filter(|id| !id.is_empty()) { + let k = lookup(id, &mut sets, None); + sets.union(i, k); + } + } + // Subject fallback. + let mut earliest: HashMap = HashMap::new(); + for (i, m) in messages.iter().enumerate() { + let key = normalize_subject(&m.subject); + if key.is_empty() { + continue; + } + let e = earliest.entry(key).or_insert(i); + if (m.date, m.id) < (messages[*e].date, messages[*e].id) { + *e = i; + } + } + for (i, m) in messages.iter().enumerate() { + if !m.in_reply_to.is_empty() || !m.references.is_empty() { + continue; + } + let (_, is_reply) = strip_prefixes(&m.subject); + if !is_reply { + continue; + } + if let Some(&e) = earliest.get(&normalize_subject(&m.subject)) { + sets.union(i, e); + } + } + + // The earliest real message of each set names the thread. + let mut root_id: HashMap = HashMap::new(); + for i in 0..n { + let r = sets.find(i); + let e = root_id.entry(r).or_insert(i); + if (messages[i].date, messages[i].id) < (messages[*e].date, messages[*e].id) { + *e = i; + } + } + (0..n).map(|i| messages[root_id[&sets.find(i)]].id).collect() } diff --git a/tests/compose.rs b/tests/compose.rs index 10a1616..3032eb2 100644 --- a/tests/compose.rs +++ b/tests/compose.rs @@ -144,7 +144,11 @@ fn body_text() -> impl Strategy { fn attachment() -> impl Strategy { ( "[A-Za-z0-9_-]{1,20}", - prop_oneof![Just(("pdf", "application/pdf")), Just(("png", "image/png")), Just(("bin", "application/octet-stream"))], + prop_oneof![ + Just(("pdf", "application/pdf")), + Just(("png", "image/png")), + Just(("bin", "application/octet-stream")) + ], proptest::collection::vec(any::(), 0..3000), ) .prop_map(|(stem, (ext, ct), data)| OutAttachment { @@ -165,9 +169,8 @@ fn draft() -> impl Strategy { proptest::collection::vec(attachment(), 0..3), ) .prop_map(|(from, to, cc, subject, text, with_html, attachments)| { - let html = with_html.then(|| { - format!("

{}

", text.replace('&', "&").replace('<', "<").replace('\n', "
")) - }); + let html = with_html + .then(|| format!("

{}

", text.replace('&', "&").replace('<', "<").replace('\n', "
"))); Draft { from, to, cc, subject, text, html, attachments, ..Default::default() } }) } diff --git a/tests/mime.rs b/tests/mime.rs index 023b37d..ccd12c3 100644 --- a/tests/mime.rs +++ b/tests/mime.rs @@ -2,8 +2,8 @@ use base64::Engine; use epistula_core::mime::{MAX_MESSAGE_BYTES, ParseError, parse}; -use epistula_core::sanitize::{InlineImage, SanitizeOptions, sanitize}; use epistula_core::safe_filename; +use epistula_core::sanitize::{InlineImage, SanitizeOptions, sanitize}; use proptest::prelude::*; use std::collections::HashMap; @@ -31,8 +31,8 @@ fn noise(len: usize, mut seed: u64) -> Vec { } const PNG_1X1: &[u8] = &[ - 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, - 0, 1, 8, 6, 0, 0, 0, 0x1F, 0x15, 0xC4, 0x89, + 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0x0D, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 1, 0, 0, 0, 1, 8, + 6, 0, 0, 0, 0x1F, 0x15, 0xC4, 0x89, ]; fn nested_fixture() -> Vec { @@ -120,10 +120,8 @@ fn inline_cid_image_becomes_a_data_uri_in_the_reader() { inline.content_id.clone().unwrap(), InlineImage { content_type: &inline.content_type, data: &inline.data }, ); - let out = sanitize( - m.html.as_deref().unwrap(), - &SanitizeOptions { load_remote_images: false, inline_images: images }, - ); + let out = + sanitize(m.html.as_deref().unwrap(), &SanitizeOptions { load_remote_images: false, inline_images: images }); assert!(out.html.contains("data:image/png;base64,"), "{}", out.html); assert!(!out.html.contains("cid"), "{}", out.html); assert_eq!(out.blocked_images, 0); @@ -153,7 +151,8 @@ fn broken_charsets_do_not_panic_and_keep_text() { let m = parse(unknown).unwrap(); assert!(m.text.unwrap().contains("ok")); - let invalid_utf8 = b"Subject: =?UTF-8?B?/w==?=\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nbad \xFF\xFE bytes\r\n"; + let invalid_utf8 = + b"Subject: =?UTF-8?B?/w==?=\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nbad \xFF\xFE bytes\r\n"; let m = parse(invalid_utf8).unwrap(); assert!(m.text.unwrap().contains("bytes")); @@ -215,12 +214,7 @@ fn two_hundred_kilobyte_header_block() { #[test] fn hostile_filenames_in_messages_are_made_safe() { - let names = [ - "../../../etc/passwd", - "..\\..\\Windows\\win.ini", - "CON.txt", - "invoice\u{202E}fdp.exe", - ]; + let names = ["../../../etc/passwd", "..\\..\\Windows\\win.ini", "CON.txt", "invoice\u{202E}fdp.exe"]; let mut raw = String::from("Subject: files\r\nContent-Type: multipart/mixed; boundary=f\r\n\r\n"); for name in names { raw.push_str(&format!( diff --git a/tests/sanitize.proptest-regressions b/tests/sanitize.proptest-regressions index 2848be4..f866985 100644 --- a/tests/sanitize.proptest-regressions +++ b/tests/sanitize.proptest-regressions @@ -7,3 +7,5 @@ cc 4e10d11e138d641f5cd862bf9d0328534293c16602b25811c13e17f483d0c012 # shrinks to parts = [], load = false cc 9298836d4e0c985227afc1ac30519c2685a4e3d945870a0e9f17cc9e627b725c # shrinks to parts = [] cc 04d94bdb6810dae2da78cbe7203c4f7076050d7986ba6572441864111c45a79e # shrinks to text = "" +cc b2079ba7c7b64a2e3b52515689e13d44fb7a5dfb8f1b4e0bb7f24d35fc4cfb28 # shrinks to parts = ["

"] +cc c1fdc436d014d409bf600850adb48e9a7d8f2528f1a3c68f69569840c4dd81f1 # shrinks to parts = ["

"], load = false diff --git a/tests/sanitize.rs b/tests/sanitize.rs index 00b998b..2b17242 100644 --- a/tests/sanitize.rs +++ b/tests/sanitize.rs @@ -9,11 +9,47 @@ fn clean(html: &str) -> String { /// Anything executable, anything that loads something, anything that navigates by itself. const FORBIDDEN: &[&str] = &[ - " Vec<(String, Vec<(String, String)>)> { let mut end = rest.len(); loop { while let Some(&(_, c)) = chars.peek() { - if c.is_whitespace() || c == '/' { chars.next(); } else { break; } + if c.is_whitespace() || c == '/' { + chars.next(); + } else { + break; + } } let Some(&(i, c)) = chars.peek() else { break }; - if c == '>' { end = i + 1; 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; } + if c == '=' || c == '>' || c.is_whitespace() { + break; + } attr.push(c); chars.next(); } @@ -114,7 +159,9 @@ fn tags(out: &str) -> Vec<(String, Vec<(String, String)>)> { if let Some(&(_, '"')) = chars.peek() { chars.next(); for (_, c) in chars.by_ref() { - if c == '"' { break; } + if c == '"' { + break; + } value.push(c); } } @@ -140,9 +187,45 @@ fn dangerous(out: &str) -> Option { } let compact: String = value.chars().filter(|c| !c.is_whitespace() && !c.is_control()).collect(); let compact = compact.to_ascii_lowercase(); - if compact.starts_with("javascript:") || compact.starts_with("vbscript:") || compact.starts_with("data:text") { + 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 diff --git a/tests/thread_rules_search.rs b/tests/thread_rules_search.rs index 2f9394c..da28f1f 100644 --- a/tests/thread_rules_search.rs +++ b/tests/thread_rules_search.rs @@ -3,8 +3,8 @@ use epistula_core::rules::RuleError; use epistula_core::search::FTS_COLUMNS; use epistula_core::{ - Address, Condition, Field, Rule, RuleMessage, ThreadInput, first_match, normalize_subject, parse_query, - thread, to_sieve, + Address, Condition, Field, Rule, RuleMessage, ThreadInput, first_match, normalize_subject, parse_query, thread, + to_sieve, }; use proptest::prelude::*; @@ -54,10 +54,8 @@ fn references_join_across_a_missing_message() { #[test] fn a_reply_that_arrives_before_its_parent_still_joins() { - let t = thread(&[ - msg(7, Some("b@x"), &["a@x"], &["a@x"], "Re: Plan", 200), - msg(9, Some("a@x"), &[], &[], "Plan", 100), - ]); + let t = + thread(&[msg(7, Some("b@x"), &["a@x"], &["a@x"], "Re: Plan", 200), msg(9, Some("a@x"), &[], &[], "Plan", 100)]); assert_eq!(t, vec![9, 9], "thread id = earliest message by date"); } @@ -131,10 +129,8 @@ fn rule(name: &str, conditions: &[(Field, &str)], folder: &str) -> Rule { #[test] fn first_match_wins() { - let rules = vec![ - rule("bank", &[(Field::From, "@bank.cz")], "Bank"), - rule("all-from-cz", &[(Field::From, ".cz")], "Czech"), - ]; + let rules = + vec![rule("bank", &[(Field::From, "@bank.cz")], "Bank"), rule("all-from-cz", &[(Field::From, ".cz")], "Czech")]; let from = [addr(None, "info@bank.cz")]; let m = RuleMessage { from: &from, to: &[], cc: &[], subject: "Výpis" }; assert_eq!(first_match(&rules, &m).unwrap().folder, "Bank"); @@ -261,7 +257,14 @@ fn search_finds_diacritics_insensitively() { FTS_COLUMNS.join(", ") )) .unwrap(); - for (query, hits) in [("vylet", 1), ("from:anna", 1), ("from:anna@example.com", 1), ("subject:sobot", 1), ("to:anna", 0), ("mapa", 1)] { + for (query, hits) in [ + ("vylet", 1), + ("from:anna", 1), + ("from:anna@example.com", 1), + ("subject:sobot", 1), + ("to:anna", 0), + ("mapa", 1), + ] { let expr = parse_query(query).fts_match().unwrap(); let n: i64 = db.query_row("SELECT count(*) FROM s WHERE s MATCH ?1", [&expr], |r| r.get(0)).unwrap(); assert_eq!(n, hits, "{query} -> {expr}");