[core] Tests: the mandatory suites, red against the API stubs (55 tests)

This commit is contained in:
2026-11-08 14:04:09 +01:00
parent eeef676991
commit c59480a0c0
18 changed files with 2876 additions and 0 deletions
Generated
+1260
View File
File diff suppressed because it is too large Load Diff
+26
View File
@@ -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
+70
View File
@@ -0,0 +1,70 @@
//! Composing outgoing mail (mail-builder), and the drafts for reply, reply all and forward.
use crate::{Address, Parsed};
use serde::{Deserialize, Serialize};
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Draft {
pub from: Address,
pub to: Vec<Address>,
pub cc: Vec<Address>,
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 _ = (random, domain);
todo!()
}
/// 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 _ = (draft, message_id, date);
todo!()
}
pub fn reply(original: &Parsed, me: &Address, mode: ReplyMode) -> Draft {
let _ = (original, me, mode);
todo!()
}
pub fn forward(original: &Parsed, me: &Address) -> Draft {
let _ = (original, me);
todo!()
}
+10
View File
@@ -0,0 +1,10 @@
//! 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;
/// A name that is safe to create in any directory on Windows, Android and iOS, and that shows what it is.
pub fn safe_filename(raw: &str) -> String {
let _ = raw;
todo!()
}
+58
View File
@@ -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};
+87
View File
@@ -0,0 +1,87 @@
//! Parsing a raw RFC 5322 message (mail-parser) into what the app stores and shows.
use crate::Address;
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 {}
pub fn parse(raw: &[u8]) -> Result<Parsed, ParseError> {
let _ = raw;
todo!()
}
+81
View File
@@ -0,0 +1,81 @@
//! 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> {
todo!()
}
/// The rule "Rule from this mail": sender address -> folder.
pub fn from_sender(sender: &Address, folder: &str) -> Rule {
let _ = (sender, folder);
todo!()
}
}
/// 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> {
let _ = (rules, message);
todo!()
}
/// The same rules as a Sieve script (RFC 5228 + fileinto + RFC 5051 unicode-casemap).
pub fn to_sieve(rules: &[Rule]) -> String {
let _ = rules;
todo!()
}
+40
View File
@@ -0,0 +1,40 @@
//! 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.
use std::collections::HashMap;
/// 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+";
pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized {
let _ = (html, options);
todo!()
}
/// A plain-text body as safe HTML (escaped, line breaks kept, links made clickable).
pub fn text_to_html(text: &str) -> String {
let _ = text;
todo!()
}
+32
View File
@@ -0,0 +1,32 @@
//! 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"];
pub fn parse_query(input: &str) -> Query {
let _ = input;
todo!()
}
impl Query {
pub fn is_empty(&self) -> bool {
todo!()
}
/// The FTS5 `MATCH` expression, or `None` when there is no text to match (only flags).
pub fn fts_match(&self) -> Option<String> {
todo!()
}
}
+25
View File
@@ -0,0 +1,25 @@
//! Conversations: Message-ID / In-Reply-To / References, with a normalised-subject fallback.
/// 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,
}
/// `Re: Fwd: [list] Hello world` -> `hello world`.
pub fn normalize_subject(subject: &str) -> String {
let _ = subject;
todo!()
}
/// The thread id of each input, in input order. A thread's id is the `id` of its earliest message
/// (by date, then id), so the result does not depend on input order.
pub fn thread(messages: &[ThreadInput]) -> Vec<u64> {
let _ = messages;
todo!()
}
+7
View File
@@ -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, .. }
+194
View File
@@ -0,0 +1,194 @@
//! 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('&', "&amp;").replace('<', "&lt;").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);
}
}
+9
View File
@@ -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 = []
+354
View File
@@ -0,0 +1,354 @@
//! 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::sanitize::{InlineImage, SanitizeOptions, sanitize};
use epistula_core::safe_filename;
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&#58;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);
}
}
+9
View File
@@ -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 4e10d11e138d641f5cd862bf9d0328534293c16602b25811c13e17f483d0c012 # shrinks to parts = [], load = false
cc 9298836d4e0c985227afc1ac30519c2685a4e3d945870a0e9f17cc9e627b725c # shrinks to parts = []
cc 04d94bdb6810dae2da78cbe7203c4f7076050d7986ba6572441864111c45a79e # shrinks to text = ""
+309
View File
@@ -0,0 +1,309 @@
//! 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&#x09;script:alert(1)\">x</a>",
"<a href=\"&#106;avascript: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 (`&#58;`, `&#61;`); undo that so the checks
/// see what a browser sees.
fn decoded(s: &str) -> String {
s.replace("&#58;", ":").replace("&#61;", "=")
}
/// 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("&amp;", "&").replace("&quot;", "\"");
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();
if compact.starts_with("javascript:") || compact.starts_with("vbscript:") || compact.starts_with("data:text") {
return Some(format!("url 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(':', "&#58;");
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&#58;//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&amp;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&#58; #333"), "{out}");
assert!(out.contains("padding&#58; 4px"), "{out}");
assert!(out.contains("href=\"https&#58;//example.cz/x?a&#61;1&amp;b&#61;2\""), "{out}");
assert!(out.contains("href=\"mailto&#58;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&#58;image/png;base64,iVBORw0KGgo&#61;"), "{}", 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 &lt; b &amp; c &gt; d"), "{html}");
assert!(!html.to_ascii_lowercase().contains("<script"), "{html}");
assert!(html.contains("<br>"), "{html}");
assert!(html.contains("<a href=\"https&#58;//example.cz/x?y&#61;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("&#106;".to_string()),
Just("&lt;script&gt;".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
+296
View File
@@ -0,0 +1,296 @@
//! 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));
}
}
}