[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
+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!()
}